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 "AMDGPUSubtarget.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
19 #include "SIDefines.h"
20 #include "SIInstrInfo.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "SIRegisterInfo.h"
23 #include "Utils/AMDGPUBaseInfo.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/DAGCombine.h"
37 #include "llvm/CodeGen/ISDOpcodes.h"
38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineLoopInfo.h"
45 #include "llvm/CodeGen/MachineMemOperand.h"
46 #include "llvm/CodeGen/MachineModuleInfo.h"
47 #include "llvm/CodeGen/MachineOperand.h"
48 #include "llvm/CodeGen/MachineRegisterInfo.h"
49 #include "llvm/CodeGen/SelectionDAG.h"
50 #include "llvm/CodeGen/SelectionDAGNodes.h"
51 #include "llvm/CodeGen/TargetCallingConv.h"
52 #include "llvm/CodeGen/TargetRegisterInfo.h"
53 #include "llvm/CodeGen/ValueTypes.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/DiagnosticInfo.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/GlobalValue.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CodeGen.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/KnownBits.h"
72 #include "llvm/Support/MachineValueType.h"
73 #include "llvm/Support/MathExtras.h"
74 #include "llvm/Target/TargetOptions.h"
75 #include <cassert>
76 #include <cmath>
77 #include <cstdint>
78 #include <iterator>
79 #include <tuple>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 #define DEBUG_TYPE "si-lower"
86 
87 STATISTIC(NumTailCalls, "Number of tail calls");
88 
89 static cl::opt<bool> DisableLoopAlignment(
90   "amdgpu-disable-loop-alignment",
91   cl::desc("Do not align and prefetch loops"),
92   cl::init(false));
93 
94 static cl::opt<bool> VGPRReserveforSGPRSpill(
95     "amdgpu-reserve-vgpr-for-sgpr-spill",
96     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
97 
98 static cl::opt<bool> UseDivergentRegisterIndexing(
99   "amdgpu-use-divergent-register-indexing",
100   cl::Hidden,
101   cl::desc("Use indirect register addressing for divergent indexes"),
102   cl::init(false));
103 
104 static bool hasFP32Denormals(const MachineFunction &MF) {
105   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
106   return Info->getMode().allFP32Denormals();
107 }
108 
109 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
110   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
111   return Info->getMode().allFP64FP16Denormals();
112 }
113 
114 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
115   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
116   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
117     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
118       return AMDGPU::SGPR0 + Reg;
119     }
120   }
121   llvm_unreachable("Cannot allocate sgpr");
122 }
123 
124 SITargetLowering::SITargetLowering(const TargetMachine &TM,
125                                    const GCNSubtarget &STI)
126     : AMDGPUTargetLowering(TM, STI),
127       Subtarget(&STI) {
128   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
129   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
130 
131   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
132   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
133 
134   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
135   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
136   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
137 
138   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
139   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
140 
141   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
142   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
143 
144   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
145   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
146 
147   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
148   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
149 
150   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
151   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
152 
153   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
154   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
155 
156   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
157   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
158 
159   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
160   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
161 
162   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
163   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
164 
165   if (Subtarget->has16BitInsts()) {
166     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
167     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
168 
169     // Unless there are also VOP3P operations, not operations are really legal.
170     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
171     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
172     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
173     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
174   }
175 
176   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
177   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
178 
179   computeRegisterProperties(Subtarget->getRegisterInfo());
180 
181   // The boolean content concept here is too inflexible. Compares only ever
182   // really produce a 1-bit result. Any copy/extend from these will turn into a
183   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
184   // it's what most targets use.
185   setBooleanContents(ZeroOrOneBooleanContent);
186   setBooleanVectorContents(ZeroOrOneBooleanContent);
187 
188   // We need to custom lower vector stores from local memory
189   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
190   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
195   setOperationAction(ISD::LOAD, MVT::i1, Custom);
196   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
197 
198   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
199   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
202   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
203   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
204   setOperationAction(ISD::STORE, MVT::i1, Custom);
205   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
206 
207   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
208   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
209   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
210   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
211   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
212   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
213   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
214   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
215   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
216   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
217   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
218   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
219   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
220   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
221   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
222   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
223 
224   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
225   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
226   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
227   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
228   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
229 
230   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
231   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
232 
233   setOperationAction(ISD::SELECT, MVT::i1, Promote);
234   setOperationAction(ISD::SELECT, MVT::i64, Custom);
235   setOperationAction(ISD::SELECT, MVT::f64, Promote);
236   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
237 
238   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
239   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
241   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
242   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
243 
244   setOperationAction(ISD::SETCC, MVT::i1, Promote);
245   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
246   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
247   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
248 
249   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
250   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
251   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
252   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
253   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
254   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
255   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
256   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
257 
258   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
266 
267   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
268   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
269   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
270   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
271   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
272   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
273 
274   setOperationAction(ISD::UADDO, MVT::i32, Legal);
275   setOperationAction(ISD::USUBO, MVT::i32, Legal);
276 
277   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
278   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
279 
280   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
281   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
282   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
283 
284 #if 0
285   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
286   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
287 #endif
288 
289   // We only support LOAD/STORE and vector manipulation ops for vectors
290   // with > 4 elements.
291   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
292                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
293                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
294                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
295     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
296       switch (Op) {
297       case ISD::LOAD:
298       case ISD::STORE:
299       case ISD::BUILD_VECTOR:
300       case ISD::BITCAST:
301       case ISD::EXTRACT_VECTOR_ELT:
302       case ISD::INSERT_VECTOR_ELT:
303       case ISD::INSERT_SUBVECTOR:
304       case ISD::EXTRACT_SUBVECTOR:
305       case ISD::SCALAR_TO_VECTOR:
306         break;
307       case ISD::CONCAT_VECTORS:
308         setOperationAction(Op, VT, Custom);
309         break;
310       default:
311         setOperationAction(Op, VT, Expand);
312         break;
313       }
314     }
315   }
316 
317   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
318 
319   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
320   // is expanded to avoid having two separate loops in case the index is a VGPR.
321 
322   // Most operations are naturally 32-bit vector operations. We only support
323   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
324   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
325     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
326     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
327 
328     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
329     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
330 
331     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
332     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
333 
334     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
335     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
336   }
337 
338   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
339     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
340     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
341 
342     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
343     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
344 
345     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
346     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
347 
348     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
349     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
350   }
351 
352   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
353     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
354     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
355 
356     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
357     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
358 
359     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
360     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
361 
362     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
363     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
364   }
365 
366   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
367     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
368     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
369 
370     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
371     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
372 
373     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
374     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
375 
376     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
377     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
378   }
379 
380   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
382   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
383   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
384 
385   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
386   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
387 
388   // Avoid stack access for these.
389   // TODO: Generalize to more vector types.
390   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
394 
395   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
400 
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
403   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
404 
405   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
406   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
407   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
408   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
409 
410   // Deal with vec3 vector operations when widened to vec4.
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
415 
416   // Deal with vec5 vector operations when widened to vec8.
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
419   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
420   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
421 
422   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
423   // and output demarshalling
424   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
425   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
426 
427   // We can't return success/failure, only the old value,
428   // let LLVM add the comparison
429   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
430   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
431 
432   if (Subtarget->hasFlatAddressSpace()) {
433     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
434     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
435   }
436 
437   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
438 
439   // FIXME: This should be narrowed to i32, but that only happens if i64 is
440   // illegal.
441   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
442   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
443   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
444 
445   // On SI this is s_memtime and s_memrealtime on VI.
446   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
447   setOperationAction(ISD::TRAP, MVT::Other, Custom);
448   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
449 
450   if (Subtarget->has16BitInsts()) {
451     setOperationAction(ISD::FPOW, 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_ZERO_UNDEF, MVT::i32, Custom);
474 
475   if (Subtarget->hasFFBL())
476     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
477 
478   // We only really have 32-bit BFE instructions (and 16-bit on VI).
479   //
480   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
481   // effort to match them now. We want this to be false for i64 cases when the
482   // extraction isn't restricted to the upper or lower half. Ideally we would
483   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
484   // span the midpoint are probably relatively rare, so don't worry about them
485   // for now.
486   if (Subtarget->hasBFE())
487     setHasExtractBitsInsn(true);
488 
489   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
490   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
491   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
492   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
493 
494 
495   // These are really only legal for ieee_mode functions. We should be avoiding
496   // them for functions that don't have ieee_mode enabled, so just say they are
497   // legal.
498   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
499   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
500   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
501   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
502 
503 
504   if (Subtarget->haveRoundOpsF64()) {
505     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
506     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
507     setOperationAction(ISD::FRINT, MVT::f64, Legal);
508   } else {
509     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
510     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
511     setOperationAction(ISD::FRINT, MVT::f64, Custom);
512     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
513   }
514 
515   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
516 
517   setOperationAction(ISD::FSIN, MVT::f32, Custom);
518   setOperationAction(ISD::FCOS, MVT::f32, Custom);
519   setOperationAction(ISD::FDIV, MVT::f32, Custom);
520   setOperationAction(ISD::FDIV, MVT::f64, Custom);
521 
522   if (Subtarget->has16BitInsts()) {
523     setOperationAction(ISD::Constant, MVT::i16, Legal);
524 
525     setOperationAction(ISD::SMIN, MVT::i16, Legal);
526     setOperationAction(ISD::SMAX, MVT::i16, Legal);
527 
528     setOperationAction(ISD::UMIN, MVT::i16, Legal);
529     setOperationAction(ISD::UMAX, MVT::i16, Legal);
530 
531     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
532     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
533 
534     setOperationAction(ISD::ROTR, MVT::i16, Promote);
535     setOperationAction(ISD::ROTL, MVT::i16, Promote);
536 
537     setOperationAction(ISD::SDIV, MVT::i16, Promote);
538     setOperationAction(ISD::UDIV, MVT::i16, Promote);
539     setOperationAction(ISD::SREM, MVT::i16, Promote);
540     setOperationAction(ISD::UREM, MVT::i16, Promote);
541 
542     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
543 
544     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
545     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
546     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
547     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
548     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
549 
550     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
551 
552     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
553 
554     setOperationAction(ISD::LOAD, MVT::i16, Custom);
555 
556     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
557 
558     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
559     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
560     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
561     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
562 
563     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
564     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
565 
566     // F16 - Constant Actions.
567     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
568 
569     // F16 - Load/Store Actions.
570     setOperationAction(ISD::LOAD, MVT::f16, Promote);
571     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
572     setOperationAction(ISD::STORE, MVT::f16, Promote);
573     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
574 
575     // F16 - VOP1 Actions.
576     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
577     setOperationAction(ISD::FCOS, MVT::f16, Custom);
578     setOperationAction(ISD::FSIN, MVT::f16, Custom);
579 
580     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
581     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
582 
583     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
584     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
585     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
586     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
587     setOperationAction(ISD::FROUND, MVT::f16, Custom);
588 
589     // F16 - VOP2 Actions.
590     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
591     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
592 
593     setOperationAction(ISD::FDIV, MVT::f16, Custom);
594 
595     // F16 - VOP3 Actions.
596     setOperationAction(ISD::FMA, MVT::f16, Legal);
597     if (STI.hasMadF16())
598       setOperationAction(ISD::FMAD, MVT::f16, Legal);
599 
600     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
601       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
602         switch (Op) {
603         case ISD::LOAD:
604         case ISD::STORE:
605         case ISD::BUILD_VECTOR:
606         case ISD::BITCAST:
607         case ISD::EXTRACT_VECTOR_ELT:
608         case ISD::INSERT_VECTOR_ELT:
609         case ISD::INSERT_SUBVECTOR:
610         case ISD::EXTRACT_SUBVECTOR:
611         case ISD::SCALAR_TO_VECTOR:
612           break;
613         case ISD::CONCAT_VECTORS:
614           setOperationAction(Op, VT, Custom);
615           break;
616         default:
617           setOperationAction(Op, VT, Expand);
618           break;
619         }
620       }
621     }
622 
623     // v_perm_b32 can handle either of these.
624     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
625     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
626     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
627 
628     // XXX - Do these do anything? Vector constants turn into build_vector.
629     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
630     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
631 
632     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
633     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
634 
635     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
636     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
637     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
638     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
639 
640     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
641     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
642     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
643     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
644 
645     setOperationAction(ISD::AND, MVT::v2i16, Promote);
646     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
647     setOperationAction(ISD::OR, MVT::v2i16, Promote);
648     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
649     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
650     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
651 
652     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
653     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
654     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
655     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
656 
657     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
658     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
659     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
660     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
661 
662     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
663     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
664     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
665     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
666 
667     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
668     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
669     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
670 
671     if (!Subtarget->hasVOP3PInsts()) {
672       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
673       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
674     }
675 
676     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
677     // This isn't really legal, but this avoids the legalizer unrolling it (and
678     // allows matching fneg (fabs x) patterns)
679     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
680 
681     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
682     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
683     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
684     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
685 
686     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
687     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
688 
689     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
690     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
691   }
692 
693   if (Subtarget->hasVOP3PInsts()) {
694     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
695     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
696     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
697     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
698     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
699     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
700     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
701     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
702     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
703     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
704 
705     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
706     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
707     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
708 
709     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
710     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
711 
712     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
713 
714     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
715     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
716 
717     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
718     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
719 
720     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
721     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
722     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
723     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
724     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
725     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
726 
727     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
728     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
729     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
730     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
731 
732     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
733     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
734     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
735 
736     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
737     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
738 
739     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
740     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
741     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
742 
743     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
744     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
745     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
746   }
747 
748   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
749   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
750 
751   if (Subtarget->has16BitInsts()) {
752     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
753     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
754     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
755     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
756   } else {
757     // Legalization hack.
758     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
759     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
760 
761     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
762     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
763   }
764 
765   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
766     setOperationAction(ISD::SELECT, VT, Custom);
767   }
768 
769   setOperationAction(ISD::SMULO, MVT::i64, Custom);
770   setOperationAction(ISD::UMULO, MVT::i64, Custom);
771 
772   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
773   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
774   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
775   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
776   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
777   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
778   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
779 
780   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
781   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
782   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
783   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
784   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
785   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
786   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
787   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
788   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
789 
790   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
791   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
792   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
793   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
794   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
795   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
796   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
797   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
798 
799   setTargetDAGCombine(ISD::ADD);
800   setTargetDAGCombine(ISD::ADDCARRY);
801   setTargetDAGCombine(ISD::SUB);
802   setTargetDAGCombine(ISD::SUBCARRY);
803   setTargetDAGCombine(ISD::FADD);
804   setTargetDAGCombine(ISD::FSUB);
805   setTargetDAGCombine(ISD::FMINNUM);
806   setTargetDAGCombine(ISD::FMAXNUM);
807   setTargetDAGCombine(ISD::FMINNUM_IEEE);
808   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
809   setTargetDAGCombine(ISD::FMA);
810   setTargetDAGCombine(ISD::SMIN);
811   setTargetDAGCombine(ISD::SMAX);
812   setTargetDAGCombine(ISD::UMIN);
813   setTargetDAGCombine(ISD::UMAX);
814   setTargetDAGCombine(ISD::SETCC);
815   setTargetDAGCombine(ISD::AND);
816   setTargetDAGCombine(ISD::OR);
817   setTargetDAGCombine(ISD::XOR);
818   setTargetDAGCombine(ISD::SINT_TO_FP);
819   setTargetDAGCombine(ISD::UINT_TO_FP);
820   setTargetDAGCombine(ISD::FCANONICALIZE);
821   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
822   setTargetDAGCombine(ISD::ZERO_EXTEND);
823   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
824   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
825   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
826 
827   // All memory operations. Some folding on the pointer operand is done to help
828   // matching the constant offsets in the addressing modes.
829   setTargetDAGCombine(ISD::LOAD);
830   setTargetDAGCombine(ISD::STORE);
831   setTargetDAGCombine(ISD::ATOMIC_LOAD);
832   setTargetDAGCombine(ISD::ATOMIC_STORE);
833   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
834   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
835   setTargetDAGCombine(ISD::ATOMIC_SWAP);
836   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
837   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
838   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
839   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
840   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
841   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
842   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
843   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
844   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
845   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
846   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
847 
848   // FIXME: In other contexts we pretend this is a per-function property.
849   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
850 
851   setSchedulingPreference(Sched::RegPressure);
852 }
853 
854 const GCNSubtarget *SITargetLowering::getSubtarget() const {
855   return Subtarget;
856 }
857 
858 //===----------------------------------------------------------------------===//
859 // TargetLowering queries
860 //===----------------------------------------------------------------------===//
861 
862 // v_mad_mix* support a conversion from f16 to f32.
863 //
864 // There is only one special case when denormals are enabled we don't currently,
865 // where this is OK to use.
866 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
867                                        EVT DestVT, EVT SrcVT) const {
868   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
869           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
870     DestVT.getScalarType() == MVT::f32 &&
871     SrcVT.getScalarType() == MVT::f16 &&
872     // TODO: This probably only requires no input flushing?
873     !hasFP32Denormals(DAG.getMachineFunction());
874 }
875 
876 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
877   // SI has some legal vector types, but no legal vector operations. Say no
878   // shuffles are legal in order to prefer scalarizing some vector operations.
879   return false;
880 }
881 
882 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
883                                                     CallingConv::ID CC,
884                                                     EVT VT) const {
885   if (CC == CallingConv::AMDGPU_KERNEL)
886     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
887 
888   if (VT.isVector()) {
889     EVT ScalarVT = VT.getScalarType();
890     unsigned Size = ScalarVT.getSizeInBits();
891     if (Size == 32)
892       return ScalarVT.getSimpleVT();
893 
894     if (Size > 32)
895       return MVT::i32;
896 
897     if (Size == 16 && Subtarget->has16BitInsts())
898       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
899   } else if (VT.getSizeInBits() > 32)
900     return MVT::i32;
901 
902   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
903 }
904 
905 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
906                                                          CallingConv::ID CC,
907                                                          EVT VT) const {
908   if (CC == CallingConv::AMDGPU_KERNEL)
909     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
910 
911   if (VT.isVector()) {
912     unsigned NumElts = VT.getVectorNumElements();
913     EVT ScalarVT = VT.getScalarType();
914     unsigned Size = ScalarVT.getSizeInBits();
915 
916     if (Size == 32)
917       return NumElts;
918 
919     if (Size > 32)
920       return NumElts * ((Size + 31) / 32);
921 
922     if (Size == 16 && Subtarget->has16BitInsts())
923       return (NumElts + 1) / 2;
924   } else if (VT.getSizeInBits() > 32)
925     return (VT.getSizeInBits() + 31) / 32;
926 
927   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
928 }
929 
930 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
931   LLVMContext &Context, CallingConv::ID CC,
932   EVT VT, EVT &IntermediateVT,
933   unsigned &NumIntermediates, MVT &RegisterVT) const {
934   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
935     unsigned NumElts = VT.getVectorNumElements();
936     EVT ScalarVT = VT.getScalarType();
937     unsigned Size = ScalarVT.getSizeInBits();
938     if (Size == 32) {
939       RegisterVT = ScalarVT.getSimpleVT();
940       IntermediateVT = RegisterVT;
941       NumIntermediates = NumElts;
942       return NumIntermediates;
943     }
944 
945     if (Size > 32) {
946       RegisterVT = MVT::i32;
947       IntermediateVT = RegisterVT;
948       NumIntermediates = NumElts * ((Size + 31) / 32);
949       return NumIntermediates;
950     }
951 
952     // FIXME: We should fix the ABI to be the same on targets without 16-bit
953     // support, but unless we can properly handle 3-vectors, it will be still be
954     // inconsistent.
955     if (Size == 16 && Subtarget->has16BitInsts()) {
956       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
957       IntermediateVT = RegisterVT;
958       NumIntermediates = (NumElts + 1) / 2;
959       return NumIntermediates;
960     }
961   }
962 
963   return TargetLowering::getVectorTypeBreakdownForCallingConv(
964     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
965 }
966 
967 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
968   assert(DMaskLanes != 0);
969 
970   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
971     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
972     return EVT::getVectorVT(Ty->getContext(),
973                             EVT::getEVT(VT->getElementType()),
974                             NumElts);
975   }
976 
977   return EVT::getEVT(Ty);
978 }
979 
980 // Peek through TFE struct returns to only use the data size.
981 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
982   auto *ST = dyn_cast<StructType>(Ty);
983   if (!ST)
984     return memVTFromImageData(Ty, DMaskLanes);
985 
986   // Some intrinsics return an aggregate type - special case to work out the
987   // correct memVT.
988   //
989   // Only limited forms of aggregate type currently expected.
990   if (ST->getNumContainedTypes() != 2 ||
991       !ST->getContainedType(1)->isIntegerTy(32))
992     return EVT();
993   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
994 }
995 
996 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
997                                           const CallInst &CI,
998                                           MachineFunction &MF,
999                                           unsigned IntrID) const {
1000   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1001           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1002     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1003                                                   (Intrinsic::ID)IntrID);
1004     if (Attr.hasFnAttribute(Attribute::ReadNone))
1005       return false;
1006 
1007     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1008 
1009     if (RsrcIntr->IsImage) {
1010       Info.ptrVal = MFI->getImagePSV(
1011         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1012         CI.getArgOperand(RsrcIntr->RsrcArg));
1013       Info.align.reset();
1014     } else {
1015       Info.ptrVal = MFI->getBufferPSV(
1016         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1017         CI.getArgOperand(RsrcIntr->RsrcArg));
1018     }
1019 
1020     Info.flags = MachineMemOperand::MODereferenceable;
1021     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1022       unsigned DMaskLanes = 4;
1023 
1024       if (RsrcIntr->IsImage) {
1025         const AMDGPU::ImageDimIntrinsicInfo *Intr
1026           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1027         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1028           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1029 
1030         if (!BaseOpcode->Gather4) {
1031           // If this isn't a gather, we may have excess loaded elements in the
1032           // IR type. Check the dmask for the real number of elements loaded.
1033           unsigned DMask
1034             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1035           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1036         }
1037 
1038         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1039       } else
1040         Info.memVT = EVT::getEVT(CI.getType());
1041 
1042       // FIXME: What does alignment mean for an image?
1043       Info.opc = ISD::INTRINSIC_W_CHAIN;
1044       Info.flags |= MachineMemOperand::MOLoad;
1045     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1046       Info.opc = ISD::INTRINSIC_VOID;
1047 
1048       Type *DataTy = CI.getArgOperand(0)->getType();
1049       if (RsrcIntr->IsImage) {
1050         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1051         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1052         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1053       } else
1054         Info.memVT = EVT::getEVT(DataTy);
1055 
1056       Info.flags |= MachineMemOperand::MOStore;
1057     } else {
1058       // Atomic
1059       Info.opc = ISD::INTRINSIC_W_CHAIN;
1060       Info.memVT = MVT::getVT(CI.getType());
1061       Info.flags = MachineMemOperand::MOLoad |
1062                    MachineMemOperand::MOStore |
1063                    MachineMemOperand::MODereferenceable;
1064 
1065       // XXX - Should this be volatile without known ordering?
1066       Info.flags |= MachineMemOperand::MOVolatile;
1067     }
1068     return true;
1069   }
1070 
1071   switch (IntrID) {
1072   case Intrinsic::amdgcn_atomic_inc:
1073   case Intrinsic::amdgcn_atomic_dec:
1074   case Intrinsic::amdgcn_ds_ordered_add:
1075   case Intrinsic::amdgcn_ds_ordered_swap:
1076   case Intrinsic::amdgcn_ds_fadd:
1077   case Intrinsic::amdgcn_ds_fmin:
1078   case Intrinsic::amdgcn_ds_fmax: {
1079     Info.opc = ISD::INTRINSIC_W_CHAIN;
1080     Info.memVT = MVT::getVT(CI.getType());
1081     Info.ptrVal = CI.getOperand(0);
1082     Info.align.reset();
1083     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1084 
1085     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1086     if (!Vol->isZero())
1087       Info.flags |= MachineMemOperand::MOVolatile;
1088 
1089     return true;
1090   }
1091   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1092     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1093 
1094     Info.opc = ISD::INTRINSIC_VOID;
1095     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1096     Info.ptrVal = MFI->getBufferPSV(
1097       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1098       CI.getArgOperand(1));
1099     Info.align.reset();
1100     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1101 
1102     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1103     if (!Vol || !Vol->isZero())
1104       Info.flags |= MachineMemOperand::MOVolatile;
1105 
1106     return true;
1107   }
1108   case Intrinsic::amdgcn_global_atomic_fadd: {
1109     Info.opc = ISD::INTRINSIC_VOID;
1110     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1111                             ->getPointerElementType());
1112     Info.ptrVal = CI.getOperand(0);
1113     Info.align.reset();
1114     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1115 
1116     return true;
1117   }
1118   case Intrinsic::amdgcn_ds_append:
1119   case Intrinsic::amdgcn_ds_consume: {
1120     Info.opc = ISD::INTRINSIC_W_CHAIN;
1121     Info.memVT = MVT::getVT(CI.getType());
1122     Info.ptrVal = CI.getOperand(0);
1123     Info.align.reset();
1124     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1125 
1126     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1127     if (!Vol->isZero())
1128       Info.flags |= MachineMemOperand::MOVolatile;
1129 
1130     return true;
1131   }
1132   case Intrinsic::amdgcn_global_atomic_csub: {
1133     Info.opc = ISD::INTRINSIC_W_CHAIN;
1134     Info.memVT = MVT::getVT(CI.getType());
1135     Info.ptrVal = CI.getOperand(0);
1136     Info.align.reset();
1137     Info.flags = MachineMemOperand::MOLoad |
1138                  MachineMemOperand::MOStore |
1139                  MachineMemOperand::MODereferenceable |
1140                  MachineMemOperand::MOVolatile;
1141     return true;
1142   }
1143   case Intrinsic::amdgcn_ds_gws_init:
1144   case Intrinsic::amdgcn_ds_gws_barrier:
1145   case Intrinsic::amdgcn_ds_gws_sema_v:
1146   case Intrinsic::amdgcn_ds_gws_sema_br:
1147   case Intrinsic::amdgcn_ds_gws_sema_p:
1148   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1149     Info.opc = ISD::INTRINSIC_VOID;
1150 
1151     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1152     Info.ptrVal =
1153         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1154 
1155     // This is an abstract access, but we need to specify a type and size.
1156     Info.memVT = MVT::i32;
1157     Info.size = 4;
1158     Info.align = Align(4);
1159 
1160     Info.flags = MachineMemOperand::MOStore;
1161     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1162       Info.flags = MachineMemOperand::MOLoad;
1163     return true;
1164   }
1165   default:
1166     return false;
1167   }
1168 }
1169 
1170 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1171                                             SmallVectorImpl<Value*> &Ops,
1172                                             Type *&AccessTy) const {
1173   switch (II->getIntrinsicID()) {
1174   case Intrinsic::amdgcn_atomic_inc:
1175   case Intrinsic::amdgcn_atomic_dec:
1176   case Intrinsic::amdgcn_ds_ordered_add:
1177   case Intrinsic::amdgcn_ds_ordered_swap:
1178   case Intrinsic::amdgcn_ds_fadd:
1179   case Intrinsic::amdgcn_ds_fmin:
1180   case Intrinsic::amdgcn_ds_fmax: {
1181     Value *Ptr = II->getArgOperand(0);
1182     AccessTy = II->getType();
1183     Ops.push_back(Ptr);
1184     return true;
1185   }
1186   default:
1187     return false;
1188   }
1189 }
1190 
1191 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1192   if (!Subtarget->hasFlatInstOffsets()) {
1193     // Flat instructions do not have offsets, and only have the register
1194     // address.
1195     return AM.BaseOffs == 0 && AM.Scale == 0;
1196   }
1197 
1198   return AM.Scale == 0 &&
1199          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1200                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1201                                   /*Signed=*/false));
1202 }
1203 
1204 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1205   if (Subtarget->hasFlatGlobalInsts())
1206     return AM.Scale == 0 &&
1207            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1208                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1209                                     /*Signed=*/true));
1210 
1211   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1212       // Assume the we will use FLAT for all global memory accesses
1213       // on VI.
1214       // FIXME: This assumption is currently wrong.  On VI we still use
1215       // MUBUF instructions for the r + i addressing mode.  As currently
1216       // implemented, the MUBUF instructions only work on buffer < 4GB.
1217       // It may be possible to support > 4GB buffers with MUBUF instructions,
1218       // by setting the stride value in the resource descriptor which would
1219       // increase the size limit to (stride * 4GB).  However, this is risky,
1220       // because it has never been validated.
1221     return isLegalFlatAddressingMode(AM);
1222   }
1223 
1224   return isLegalMUBUFAddressingMode(AM);
1225 }
1226 
1227 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1228   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1229   // additionally can do r + r + i with addr64. 32-bit has more addressing
1230   // mode options. Depending on the resource constant, it can also do
1231   // (i64 r0) + (i32 r1) * (i14 i).
1232   //
1233   // Private arrays end up using a scratch buffer most of the time, so also
1234   // assume those use MUBUF instructions. Scratch loads / stores are currently
1235   // implemented as mubuf instructions with offen bit set, so slightly
1236   // different than the normal addr64.
1237   if (!isUInt<12>(AM.BaseOffs))
1238     return false;
1239 
1240   // FIXME: Since we can split immediate into soffset and immediate offset,
1241   // would it make sense to allow any immediate?
1242 
1243   switch (AM.Scale) {
1244   case 0: // r + i or just i, depending on HasBaseReg.
1245     return true;
1246   case 1:
1247     return true; // We have r + r or r + i.
1248   case 2:
1249     if (AM.HasBaseReg) {
1250       // Reject 2 * r + r.
1251       return false;
1252     }
1253 
1254     // Allow 2 * r as r + r
1255     // Or  2 * r + i is allowed as r + r + i.
1256     return true;
1257   default: // Don't allow n * r
1258     return false;
1259   }
1260 }
1261 
1262 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1263                                              const AddrMode &AM, Type *Ty,
1264                                              unsigned AS, Instruction *I) const {
1265   // No global is ever allowed as a base.
1266   if (AM.BaseGV)
1267     return false;
1268 
1269   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1270     return isLegalGlobalAddressingMode(AM);
1271 
1272   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1273       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1274       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1275     // If the offset isn't a multiple of 4, it probably isn't going to be
1276     // correctly aligned.
1277     // FIXME: Can we get the real alignment here?
1278     if (AM.BaseOffs % 4 != 0)
1279       return isLegalMUBUFAddressingMode(AM);
1280 
1281     // There are no SMRD extloads, so if we have to do a small type access we
1282     // will use a MUBUF load.
1283     // FIXME?: We also need to do this if unaligned, but we don't know the
1284     // alignment here.
1285     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1286       return isLegalGlobalAddressingMode(AM);
1287 
1288     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1289       // SMRD instructions have an 8-bit, dword offset on SI.
1290       if (!isUInt<8>(AM.BaseOffs / 4))
1291         return false;
1292     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1293       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1294       // in 8-bits, it can use a smaller encoding.
1295       if (!isUInt<32>(AM.BaseOffs / 4))
1296         return false;
1297     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1298       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1299       if (!isUInt<20>(AM.BaseOffs))
1300         return false;
1301     } else
1302       llvm_unreachable("unhandled generation");
1303 
1304     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1305       return true;
1306 
1307     if (AM.Scale == 1 && AM.HasBaseReg)
1308       return true;
1309 
1310     return false;
1311 
1312   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1313     return isLegalMUBUFAddressingMode(AM);
1314   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1315              AS == AMDGPUAS::REGION_ADDRESS) {
1316     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1317     // field.
1318     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1319     // an 8-bit dword offset but we don't know the alignment here.
1320     if (!isUInt<16>(AM.BaseOffs))
1321       return false;
1322 
1323     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1324       return true;
1325 
1326     if (AM.Scale == 1 && AM.HasBaseReg)
1327       return true;
1328 
1329     return false;
1330   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1331              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1332     // For an unknown address space, this usually means that this is for some
1333     // reason being used for pure arithmetic, and not based on some addressing
1334     // computation. We don't have instructions that compute pointers with any
1335     // addressing modes, so treat them as having no offset like flat
1336     // instructions.
1337     return isLegalFlatAddressingMode(AM);
1338   }
1339 
1340   // Assume a user alias of global for unknown address spaces.
1341   return isLegalGlobalAddressingMode(AM);
1342 }
1343 
1344 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1345                                         const SelectionDAG &DAG) const {
1346   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1347     return (MemVT.getSizeInBits() <= 4 * 32);
1348   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1349     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1350     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1351   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1352     return (MemVT.getSizeInBits() <= 2 * 32);
1353   }
1354   return true;
1355 }
1356 
1357 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1358     unsigned Size, unsigned AddrSpace, unsigned Align,
1359     MachineMemOperand::Flags Flags, bool *IsFast) const {
1360   if (IsFast)
1361     *IsFast = false;
1362 
1363   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1364       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1365     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1366     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1367     // with adjacent offsets.
1368     bool AlignedBy4 = (Align % 4 == 0);
1369     if (IsFast)
1370       *IsFast = AlignedBy4;
1371 
1372     return AlignedBy4;
1373   }
1374 
1375   // FIXME: We have to be conservative here and assume that flat operations
1376   // will access scratch.  If we had access to the IR function, then we
1377   // could determine if any private memory was used in the function.
1378   if (!Subtarget->hasUnalignedScratchAccess() &&
1379       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1380        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1381     bool AlignedBy4 = Align >= 4;
1382     if (IsFast)
1383       *IsFast = AlignedBy4;
1384 
1385     return AlignedBy4;
1386   }
1387 
1388   if (Subtarget->hasUnalignedBufferAccess()) {
1389     // If we have an uniform constant load, it still requires using a slow
1390     // buffer instruction if unaligned.
1391     if (IsFast) {
1392       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1393       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1394       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1395                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1396         Align >= 4 : Align != 2;
1397     }
1398 
1399     return true;
1400   }
1401 
1402   // Smaller than dword value must be aligned.
1403   if (Size < 32)
1404     return false;
1405 
1406   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1407   // byte-address are ignored, thus forcing Dword alignment.
1408   // This applies to private, global, and constant memory.
1409   if (IsFast)
1410     *IsFast = true;
1411 
1412   return Size >= 32 && Align >= 4;
1413 }
1414 
1415 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1416     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1417     bool *IsFast) const {
1418   if (IsFast)
1419     *IsFast = false;
1420 
1421   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1422   // which isn't a simple VT.
1423   // Until MVT is extended to handle this, simply check for the size and
1424   // rely on the condition below: allow accesses if the size is a multiple of 4.
1425   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1426                            VT.getStoreSize() > 16)) {
1427     return false;
1428   }
1429 
1430   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1431                                             Align, Flags, IsFast);
1432 }
1433 
1434 EVT SITargetLowering::getOptimalMemOpType(
1435     const MemOp &Op, const AttributeList &FuncAttributes) const {
1436   // FIXME: Should account for address space here.
1437 
1438   // The default fallback uses the private pointer size as a guess for a type to
1439   // use. Make sure we switch these to 64-bit accesses.
1440 
1441   if (Op.size() >= 16 &&
1442       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1443     return MVT::v4i32;
1444 
1445   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1446     return MVT::v2i32;
1447 
1448   // Use the default.
1449   return MVT::Other;
1450 }
1451 
1452 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1453                                            unsigned DestAS) const {
1454   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1455 }
1456 
1457 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1458   const MemSDNode *MemNode = cast<MemSDNode>(N);
1459   const Value *Ptr = MemNode->getMemOperand()->getValue();
1460   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1461   return I && I->getMetadata("amdgpu.noclobber");
1462 }
1463 
1464 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1465                                            unsigned DestAS) const {
1466   // Flat -> private/local is a simple truncate.
1467   // Flat -> global is no-op
1468   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1469     return true;
1470 
1471   return isNoopAddrSpaceCast(SrcAS, DestAS);
1472 }
1473 
1474 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1475   const MemSDNode *MemNode = cast<MemSDNode>(N);
1476 
1477   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1478 }
1479 
1480 TargetLoweringBase::LegalizeTypeAction
1481 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1482   int NumElts = VT.getVectorNumElements();
1483   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1484     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1485   return TargetLoweringBase::getPreferredVectorAction(VT);
1486 }
1487 
1488 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1489                                                          Type *Ty) const {
1490   // FIXME: Could be smarter if called for vector constants.
1491   return true;
1492 }
1493 
1494 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1495   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1496     switch (Op) {
1497     case ISD::LOAD:
1498     case ISD::STORE:
1499 
1500     // These operations are done with 32-bit instructions anyway.
1501     case ISD::AND:
1502     case ISD::OR:
1503     case ISD::XOR:
1504     case ISD::SELECT:
1505       // TODO: Extensions?
1506       return true;
1507     default:
1508       return false;
1509     }
1510   }
1511 
1512   // SimplifySetCC uses this function to determine whether or not it should
1513   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1514   if (VT == MVT::i1 && Op == ISD::SETCC)
1515     return false;
1516 
1517   return TargetLowering::isTypeDesirableForOp(Op, VT);
1518 }
1519 
1520 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1521                                                    const SDLoc &SL,
1522                                                    SDValue Chain,
1523                                                    uint64_t Offset) const {
1524   const DataLayout &DL = DAG.getDataLayout();
1525   MachineFunction &MF = DAG.getMachineFunction();
1526   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1527 
1528   const ArgDescriptor *InputPtrReg;
1529   const TargetRegisterClass *RC;
1530 
1531   std::tie(InputPtrReg, RC)
1532     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1533 
1534   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1535   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1536   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1537     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1538 
1539   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1540 }
1541 
1542 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1543                                             const SDLoc &SL) const {
1544   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1545                                                FIRST_IMPLICIT);
1546   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1547 }
1548 
1549 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1550                                          const SDLoc &SL, SDValue Val,
1551                                          bool Signed,
1552                                          const ISD::InputArg *Arg) const {
1553   // First, if it is a widened vector, narrow it.
1554   if (VT.isVector() &&
1555       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1556     EVT NarrowedVT =
1557         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1558                          VT.getVectorNumElements());
1559     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1560                       DAG.getConstant(0, SL, MVT::i32));
1561   }
1562 
1563   // Then convert the vector elements or scalar value.
1564   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1565       VT.bitsLT(MemVT)) {
1566     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1567     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1568   }
1569 
1570   if (MemVT.isFloatingPoint())
1571     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1572   else if (Signed)
1573     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1574   else
1575     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1576 
1577   return Val;
1578 }
1579 
1580 SDValue SITargetLowering::lowerKernargMemParameter(
1581   SelectionDAG &DAG, EVT VT, EVT MemVT,
1582   const SDLoc &SL, SDValue Chain,
1583   uint64_t Offset, unsigned Align, bool Signed,
1584   const ISD::InputArg *Arg) const {
1585   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1586 
1587   // Try to avoid using an extload by loading earlier than the argument address,
1588   // and extracting the relevant bits. The load should hopefully be merged with
1589   // the previous argument.
1590   if (MemVT.getStoreSize() < 4 && Align < 4) {
1591     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1592     int64_t AlignDownOffset = alignDown(Offset, 4);
1593     int64_t OffsetDiff = Offset - AlignDownOffset;
1594 
1595     EVT IntVT = MemVT.changeTypeToInteger();
1596 
1597     // TODO: If we passed in the base kernel offset we could have a better
1598     // alignment than 4, but we don't really need it.
1599     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1600     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1601                                MachineMemOperand::MODereferenceable |
1602                                MachineMemOperand::MOInvariant);
1603 
1604     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1605     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1606 
1607     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1608     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1609     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1610 
1611 
1612     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1613   }
1614 
1615   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1616   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1617                              MachineMemOperand::MODereferenceable |
1618                              MachineMemOperand::MOInvariant);
1619 
1620   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1621   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1622 }
1623 
1624 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1625                                               const SDLoc &SL, SDValue Chain,
1626                                               const ISD::InputArg &Arg) const {
1627   MachineFunction &MF = DAG.getMachineFunction();
1628   MachineFrameInfo &MFI = MF.getFrameInfo();
1629 
1630   if (Arg.Flags.isByVal()) {
1631     unsigned Size = Arg.Flags.getByValSize();
1632     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1633     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1634   }
1635 
1636   unsigned ArgOffset = VA.getLocMemOffset();
1637   unsigned ArgSize = VA.getValVT().getStoreSize();
1638 
1639   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1640 
1641   // Create load nodes to retrieve arguments from the stack.
1642   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1643   SDValue ArgValue;
1644 
1645   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1646   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1647   MVT MemVT = VA.getValVT();
1648 
1649   switch (VA.getLocInfo()) {
1650   default:
1651     break;
1652   case CCValAssign::BCvt:
1653     MemVT = VA.getLocVT();
1654     break;
1655   case CCValAssign::SExt:
1656     ExtType = ISD::SEXTLOAD;
1657     break;
1658   case CCValAssign::ZExt:
1659     ExtType = ISD::ZEXTLOAD;
1660     break;
1661   case CCValAssign::AExt:
1662     ExtType = ISD::EXTLOAD;
1663     break;
1664   }
1665 
1666   ArgValue = DAG.getExtLoad(
1667     ExtType, SL, VA.getLocVT(), Chain, FIN,
1668     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1669     MemVT);
1670   return ArgValue;
1671 }
1672 
1673 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1674   const SIMachineFunctionInfo &MFI,
1675   EVT VT,
1676   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1677   const ArgDescriptor *Reg;
1678   const TargetRegisterClass *RC;
1679 
1680   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1681   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1682 }
1683 
1684 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1685                                    CallingConv::ID CallConv,
1686                                    ArrayRef<ISD::InputArg> Ins,
1687                                    BitVector &Skipped,
1688                                    FunctionType *FType,
1689                                    SIMachineFunctionInfo *Info) {
1690   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1691     const ISD::InputArg *Arg = &Ins[I];
1692 
1693     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1694            "vector type argument should have been split");
1695 
1696     // First check if it's a PS input addr.
1697     if (CallConv == CallingConv::AMDGPU_PS &&
1698         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1699       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1700 
1701       // Inconveniently only the first part of the split is marked as isSplit,
1702       // so skip to the end. We only want to increment PSInputNum once for the
1703       // entire split argument.
1704       if (Arg->Flags.isSplit()) {
1705         while (!Arg->Flags.isSplitEnd()) {
1706           assert((!Arg->VT.isVector() ||
1707                   Arg->VT.getScalarSizeInBits() == 16) &&
1708                  "unexpected vector split in ps argument type");
1709           if (!SkipArg)
1710             Splits.push_back(*Arg);
1711           Arg = &Ins[++I];
1712         }
1713       }
1714 
1715       if (SkipArg) {
1716         // We can safely skip PS inputs.
1717         Skipped.set(Arg->getOrigArgIndex());
1718         ++PSInputNum;
1719         continue;
1720       }
1721 
1722       Info->markPSInputAllocated(PSInputNum);
1723       if (Arg->Used)
1724         Info->markPSInputEnabled(PSInputNum);
1725 
1726       ++PSInputNum;
1727     }
1728 
1729     Splits.push_back(*Arg);
1730   }
1731 }
1732 
1733 // Allocate special inputs passed in VGPRs.
1734 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1735                                                       MachineFunction &MF,
1736                                                       const SIRegisterInfo &TRI,
1737                                                       SIMachineFunctionInfo &Info) const {
1738   const LLT S32 = LLT::scalar(32);
1739   MachineRegisterInfo &MRI = MF.getRegInfo();
1740 
1741   if (Info.hasWorkItemIDX()) {
1742     Register Reg = AMDGPU::VGPR0;
1743     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1744 
1745     CCInfo.AllocateReg(Reg);
1746     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1747   }
1748 
1749   if (Info.hasWorkItemIDY()) {
1750     Register Reg = AMDGPU::VGPR1;
1751     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1752 
1753     CCInfo.AllocateReg(Reg);
1754     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1755   }
1756 
1757   if (Info.hasWorkItemIDZ()) {
1758     Register Reg = AMDGPU::VGPR2;
1759     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1760 
1761     CCInfo.AllocateReg(Reg);
1762     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1763   }
1764 }
1765 
1766 // Try to allocate a VGPR at the end of the argument list, or if no argument
1767 // VGPRs are left allocating a stack slot.
1768 // If \p Mask is is given it indicates bitfield position in the register.
1769 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1770 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1771                                          ArgDescriptor Arg = ArgDescriptor()) {
1772   if (Arg.isSet())
1773     return ArgDescriptor::createArg(Arg, Mask);
1774 
1775   ArrayRef<MCPhysReg> ArgVGPRs
1776     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1777   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1778   if (RegIdx == ArgVGPRs.size()) {
1779     // Spill to stack required.
1780     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1781 
1782     return ArgDescriptor::createStack(Offset, Mask);
1783   }
1784 
1785   unsigned Reg = ArgVGPRs[RegIdx];
1786   Reg = CCInfo.AllocateReg(Reg);
1787   assert(Reg != AMDGPU::NoRegister);
1788 
1789   MachineFunction &MF = CCInfo.getMachineFunction();
1790   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1791   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1792   return ArgDescriptor::createRegister(Reg, Mask);
1793 }
1794 
1795 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1796                                              const TargetRegisterClass *RC,
1797                                              unsigned NumArgRegs) {
1798   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1799   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1800   if (RegIdx == ArgSGPRs.size())
1801     report_fatal_error("ran out of SGPRs for arguments");
1802 
1803   unsigned Reg = ArgSGPRs[RegIdx];
1804   Reg = CCInfo.AllocateReg(Reg);
1805   assert(Reg != AMDGPU::NoRegister);
1806 
1807   MachineFunction &MF = CCInfo.getMachineFunction();
1808   MF.addLiveIn(Reg, RC);
1809   return ArgDescriptor::createRegister(Reg);
1810 }
1811 
1812 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1813   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1814 }
1815 
1816 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1817   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1818 }
1819 
1820 /// Allocate implicit function VGPR arguments at the end of allocated user
1821 /// arguments.
1822 void SITargetLowering::allocateSpecialInputVGPRs(
1823   CCState &CCInfo, MachineFunction &MF,
1824   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1825   const unsigned Mask = 0x3ff;
1826   ArgDescriptor Arg;
1827 
1828   if (Info.hasWorkItemIDX()) {
1829     Arg = allocateVGPR32Input(CCInfo, Mask);
1830     Info.setWorkItemIDX(Arg);
1831   }
1832 
1833   if (Info.hasWorkItemIDY()) {
1834     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1835     Info.setWorkItemIDY(Arg);
1836   }
1837 
1838   if (Info.hasWorkItemIDZ())
1839     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1840 }
1841 
1842 /// Allocate implicit function VGPR arguments in fixed registers.
1843 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1844   CCState &CCInfo, MachineFunction &MF,
1845   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1846   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1847   if (!Reg)
1848     report_fatal_error("failed to allocated VGPR for implicit arguments");
1849 
1850   const unsigned Mask = 0x3ff;
1851   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1852   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1853   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1854 }
1855 
1856 void SITargetLowering::allocateSpecialInputSGPRs(
1857   CCState &CCInfo,
1858   MachineFunction &MF,
1859   const SIRegisterInfo &TRI,
1860   SIMachineFunctionInfo &Info) const {
1861   auto &ArgInfo = Info.getArgInfo();
1862 
1863   // TODO: Unify handling with private memory pointers.
1864 
1865   if (Info.hasDispatchPtr())
1866     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1867 
1868   if (Info.hasQueuePtr())
1869     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1870 
1871   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1872   // constant offset from the kernarg segment.
1873   if (Info.hasImplicitArgPtr())
1874     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1875 
1876   if (Info.hasDispatchID())
1877     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1878 
1879   // flat_scratch_init is not applicable for non-kernel functions.
1880 
1881   if (Info.hasWorkGroupIDX())
1882     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1883 
1884   if (Info.hasWorkGroupIDY())
1885     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1886 
1887   if (Info.hasWorkGroupIDZ())
1888     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1889 }
1890 
1891 // Allocate special inputs passed in user SGPRs.
1892 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1893                                             MachineFunction &MF,
1894                                             const SIRegisterInfo &TRI,
1895                                             SIMachineFunctionInfo &Info) const {
1896   if (Info.hasImplicitBufferPtr()) {
1897     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1898     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1899     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1900   }
1901 
1902   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1903   if (Info.hasPrivateSegmentBuffer()) {
1904     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1905     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1906     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1907   }
1908 
1909   if (Info.hasDispatchPtr()) {
1910     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1911     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1912     CCInfo.AllocateReg(DispatchPtrReg);
1913   }
1914 
1915   if (Info.hasQueuePtr()) {
1916     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1917     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1918     CCInfo.AllocateReg(QueuePtrReg);
1919   }
1920 
1921   if (Info.hasKernargSegmentPtr()) {
1922     MachineRegisterInfo &MRI = MF.getRegInfo();
1923     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1924     CCInfo.AllocateReg(InputPtrReg);
1925 
1926     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1927     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1928   }
1929 
1930   if (Info.hasDispatchID()) {
1931     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1932     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1933     CCInfo.AllocateReg(DispatchIDReg);
1934   }
1935 
1936   if (Info.hasFlatScratchInit()) {
1937     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1938     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1939     CCInfo.AllocateReg(FlatScratchInitReg);
1940   }
1941 
1942   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1943   // these from the dispatch pointer.
1944 }
1945 
1946 // Allocate special input registers that are initialized per-wave.
1947 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1948                                            MachineFunction &MF,
1949                                            SIMachineFunctionInfo &Info,
1950                                            CallingConv::ID CallConv,
1951                                            bool IsShader) const {
1952   if (Info.hasWorkGroupIDX()) {
1953     unsigned Reg = Info.addWorkGroupIDX();
1954     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1955     CCInfo.AllocateReg(Reg);
1956   }
1957 
1958   if (Info.hasWorkGroupIDY()) {
1959     unsigned Reg = Info.addWorkGroupIDY();
1960     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1961     CCInfo.AllocateReg(Reg);
1962   }
1963 
1964   if (Info.hasWorkGroupIDZ()) {
1965     unsigned Reg = Info.addWorkGroupIDZ();
1966     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1967     CCInfo.AllocateReg(Reg);
1968   }
1969 
1970   if (Info.hasWorkGroupInfo()) {
1971     unsigned Reg = Info.addWorkGroupInfo();
1972     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1973     CCInfo.AllocateReg(Reg);
1974   }
1975 
1976   if (Info.hasPrivateSegmentWaveByteOffset()) {
1977     // Scratch wave offset passed in system SGPR.
1978     unsigned PrivateSegmentWaveByteOffsetReg;
1979 
1980     if (IsShader) {
1981       PrivateSegmentWaveByteOffsetReg =
1982         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1983 
1984       // This is true if the scratch wave byte offset doesn't have a fixed
1985       // location.
1986       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1987         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1988         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1989       }
1990     } else
1991       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1992 
1993     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1994     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1995   }
1996 }
1997 
1998 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1999                                      MachineFunction &MF,
2000                                      const SIRegisterInfo &TRI,
2001                                      SIMachineFunctionInfo &Info) {
2002   // Now that we've figured out where the scratch register inputs are, see if
2003   // should reserve the arguments and use them directly.
2004   MachineFrameInfo &MFI = MF.getFrameInfo();
2005   bool HasStackObjects = MFI.hasStackObjects();
2006   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2007 
2008   // Record that we know we have non-spill stack objects so we don't need to
2009   // check all stack objects later.
2010   if (HasStackObjects)
2011     Info.setHasNonSpillStackObjects(true);
2012 
2013   // Everything live out of a block is spilled with fast regalloc, so it's
2014   // almost certain that spilling will be required.
2015   if (TM.getOptLevel() == CodeGenOpt::None)
2016     HasStackObjects = true;
2017 
2018   // For now assume stack access is needed in any callee functions, so we need
2019   // the scratch registers to pass in.
2020   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2021 
2022   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2023     // If we have stack objects, we unquestionably need the private buffer
2024     // resource. For the Code Object V2 ABI, this will be the first 4 user
2025     // SGPR inputs. We can reserve those and use them directly.
2026 
2027     Register PrivateSegmentBufferReg =
2028         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2029     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2030   } else {
2031     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2032     // We tentatively reserve the last registers (skipping the last registers
2033     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2034     // we'll replace these with the ones immediately after those which were
2035     // really allocated. In the prologue copies will be inserted from the
2036     // argument to these reserved registers.
2037 
2038     // Without HSA, relocations are used for the scratch pointer and the
2039     // buffer resource setup is always inserted in the prologue. Scratch wave
2040     // offset is still in an input SGPR.
2041     Info.setScratchRSrcReg(ReservedBufferReg);
2042   }
2043 
2044   MachineRegisterInfo &MRI = MF.getRegInfo();
2045 
2046   // For entry functions we have to set up the stack pointer if we use it,
2047   // whereas non-entry functions get this "for free". This means there is no
2048   // intrinsic advantage to using S32 over S34 in cases where we do not have
2049   // calls but do need a frame pointer (i.e. if we are requested to have one
2050   // because frame pointer elimination is disabled). To keep things simple we
2051   // only ever use S32 as the call ABI stack pointer, and so using it does not
2052   // imply we need a separate frame pointer.
2053   //
2054   // Try to use s32 as the SP, but move it if it would interfere with input
2055   // arguments. This won't work with calls though.
2056   //
2057   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2058   // registers.
2059   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2060     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2061   } else {
2062     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2063 
2064     if (MFI.hasCalls())
2065       report_fatal_error("call in graphics shader with too many input SGPRs");
2066 
2067     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2068       if (!MRI.isLiveIn(Reg)) {
2069         Info.setStackPtrOffsetReg(Reg);
2070         break;
2071       }
2072     }
2073 
2074     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2075       report_fatal_error("failed to find register for SP");
2076   }
2077 
2078   // hasFP should be accurate for entry functions even before the frame is
2079   // finalized, because it does not rely on the known stack size, only
2080   // properties like whether variable sized objects are present.
2081   if (ST.getFrameLowering()->hasFP(MF)) {
2082     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2083   }
2084 }
2085 
2086 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2087   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2088   return !Info->isEntryFunction();
2089 }
2090 
2091 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2092 
2093 }
2094 
2095 void SITargetLowering::insertCopiesSplitCSR(
2096   MachineBasicBlock *Entry,
2097   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2098   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2099 
2100   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2101   if (!IStart)
2102     return;
2103 
2104   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2105   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2106   MachineBasicBlock::iterator MBBI = Entry->begin();
2107   for (const MCPhysReg *I = IStart; *I; ++I) {
2108     const TargetRegisterClass *RC = nullptr;
2109     if (AMDGPU::SReg_64RegClass.contains(*I))
2110       RC = &AMDGPU::SGPR_64RegClass;
2111     else if (AMDGPU::SReg_32RegClass.contains(*I))
2112       RC = &AMDGPU::SGPR_32RegClass;
2113     else
2114       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2115 
2116     Register NewVR = MRI->createVirtualRegister(RC);
2117     // Create copy from CSR to a virtual register.
2118     Entry->addLiveIn(*I);
2119     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2120       .addReg(*I);
2121 
2122     // Insert the copy-back instructions right before the terminator.
2123     for (auto *Exit : Exits)
2124       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2125               TII->get(TargetOpcode::COPY), *I)
2126         .addReg(NewVR);
2127   }
2128 }
2129 
2130 SDValue SITargetLowering::LowerFormalArguments(
2131     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2132     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2133     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2134   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2135 
2136   MachineFunction &MF = DAG.getMachineFunction();
2137   const Function &Fn = MF.getFunction();
2138   FunctionType *FType = MF.getFunction().getFunctionType();
2139   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2140 
2141   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2142     DiagnosticInfoUnsupported NoGraphicsHSA(
2143         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2144     DAG.getContext()->diagnose(NoGraphicsHSA);
2145     return DAG.getEntryNode();
2146   }
2147 
2148   SmallVector<ISD::InputArg, 16> Splits;
2149   SmallVector<CCValAssign, 16> ArgLocs;
2150   BitVector Skipped(Ins.size());
2151   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2152                  *DAG.getContext());
2153 
2154   bool IsShader = AMDGPU::isShader(CallConv);
2155   bool IsKernel = AMDGPU::isKernel(CallConv);
2156   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2157 
2158   if (IsShader) {
2159     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2160 
2161     // At least one interpolation mode must be enabled or else the GPU will
2162     // hang.
2163     //
2164     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2165     // set PSInputAddr, the user wants to enable some bits after the compilation
2166     // based on run-time states. Since we can't know what the final PSInputEna
2167     // will look like, so we shouldn't do anything here and the user should take
2168     // responsibility for the correct programming.
2169     //
2170     // Otherwise, the following restrictions apply:
2171     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2172     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2173     //   enabled too.
2174     if (CallConv == CallingConv::AMDGPU_PS) {
2175       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2176            ((Info->getPSInputAddr() & 0xF) == 0 &&
2177             Info->isPSInputAllocated(11))) {
2178         CCInfo.AllocateReg(AMDGPU::VGPR0);
2179         CCInfo.AllocateReg(AMDGPU::VGPR1);
2180         Info->markPSInputAllocated(0);
2181         Info->markPSInputEnabled(0);
2182       }
2183       if (Subtarget->isAmdPalOS()) {
2184         // For isAmdPalOS, the user does not enable some bits after compilation
2185         // based on run-time states; the register values being generated here are
2186         // the final ones set in hardware. Therefore we need to apply the
2187         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2188         // a bit is set in PSInputAddr but not PSInputEnable is where the
2189         // frontend set up an input arg for a particular interpolation mode, but
2190         // nothing uses that input arg. Really we should have an earlier pass
2191         // that removes such an arg.)
2192         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2193         if ((PsInputBits & 0x7F) == 0 ||
2194             ((PsInputBits & 0xF) == 0 &&
2195              (PsInputBits >> 11 & 1)))
2196           Info->markPSInputEnabled(
2197               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2198       }
2199     }
2200 
2201     assert(!Info->hasDispatchPtr() &&
2202            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2203            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2204            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2205            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2206            !Info->hasWorkItemIDZ());
2207   } else if (IsKernel) {
2208     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2209   } else {
2210     Splits.append(Ins.begin(), Ins.end());
2211   }
2212 
2213   if (IsEntryFunc) {
2214     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2215     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2216   } else {
2217     // For the fixed ABI, pass workitem IDs in the last argument register.
2218     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2219       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2220   }
2221 
2222   if (IsKernel) {
2223     analyzeFormalArgumentsCompute(CCInfo, Ins);
2224   } else {
2225     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2226     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2227   }
2228 
2229   SmallVector<SDValue, 16> Chains;
2230 
2231   // FIXME: This is the minimum kernel argument alignment. We should improve
2232   // this to the maximum alignment of the arguments.
2233   //
2234   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2235   // kern arg offset.
2236   const unsigned KernelArgBaseAlign = 16;
2237 
2238    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2239     const ISD::InputArg &Arg = Ins[i];
2240     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2241       InVals.push_back(DAG.getUNDEF(Arg.VT));
2242       continue;
2243     }
2244 
2245     CCValAssign &VA = ArgLocs[ArgIdx++];
2246     MVT VT = VA.getLocVT();
2247 
2248     if (IsEntryFunc && VA.isMemLoc()) {
2249       VT = Ins[i].VT;
2250       EVT MemVT = VA.getLocVT();
2251 
2252       const uint64_t Offset = VA.getLocMemOffset();
2253       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2254 
2255       SDValue Arg = lowerKernargMemParameter(
2256         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2257       Chains.push_back(Arg.getValue(1));
2258 
2259       auto *ParamTy =
2260         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2261       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2262           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2263                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2264         // On SI local pointers are just offsets into LDS, so they are always
2265         // less than 16-bits.  On CI and newer they could potentially be
2266         // real pointers, so we can't guarantee their size.
2267         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2268                           DAG.getValueType(MVT::i16));
2269       }
2270 
2271       InVals.push_back(Arg);
2272       continue;
2273     } else if (!IsEntryFunc && VA.isMemLoc()) {
2274       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2275       InVals.push_back(Val);
2276       if (!Arg.Flags.isByVal())
2277         Chains.push_back(Val.getValue(1));
2278       continue;
2279     }
2280 
2281     assert(VA.isRegLoc() && "Parameter must be in a register!");
2282 
2283     Register Reg = VA.getLocReg();
2284     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2285     EVT ValVT = VA.getValVT();
2286 
2287     Reg = MF.addLiveIn(Reg, RC);
2288     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2289 
2290     if (Arg.Flags.isSRet()) {
2291       // The return object should be reasonably addressable.
2292 
2293       // FIXME: This helps when the return is a real sret. If it is a
2294       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2295       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2296       unsigned NumBits
2297         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2298       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2299         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2300     }
2301 
2302     // If this is an 8 or 16-bit value, it is really passed promoted
2303     // to 32 bits. Insert an assert[sz]ext to capture this, then
2304     // truncate to the right size.
2305     switch (VA.getLocInfo()) {
2306     case CCValAssign::Full:
2307       break;
2308     case CCValAssign::BCvt:
2309       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2310       break;
2311     case CCValAssign::SExt:
2312       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2313                         DAG.getValueType(ValVT));
2314       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2315       break;
2316     case CCValAssign::ZExt:
2317       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2318                         DAG.getValueType(ValVT));
2319       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2320       break;
2321     case CCValAssign::AExt:
2322       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2323       break;
2324     default:
2325       llvm_unreachable("Unknown loc info!");
2326     }
2327 
2328     InVals.push_back(Val);
2329   }
2330 
2331   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2332     // Special inputs come after user arguments.
2333     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2334   }
2335 
2336   // Start adding system SGPRs.
2337   if (IsEntryFunc) {
2338     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2339   } else {
2340     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2341     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2342   }
2343 
2344   auto &ArgUsageInfo =
2345     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2346   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2347 
2348   unsigned StackArgSize = CCInfo.getNextStackOffset();
2349   Info->setBytesInStackArgArea(StackArgSize);
2350 
2351   return Chains.empty() ? Chain :
2352     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2353 }
2354 
2355 // TODO: If return values can't fit in registers, we should return as many as
2356 // possible in registers before passing on stack.
2357 bool SITargetLowering::CanLowerReturn(
2358   CallingConv::ID CallConv,
2359   MachineFunction &MF, bool IsVarArg,
2360   const SmallVectorImpl<ISD::OutputArg> &Outs,
2361   LLVMContext &Context) const {
2362   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2363   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2364   // for shaders. Vector types should be explicitly handled by CC.
2365   if (AMDGPU::isEntryFunctionCC(CallConv))
2366     return true;
2367 
2368   SmallVector<CCValAssign, 16> RVLocs;
2369   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2370   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2371 }
2372 
2373 SDValue
2374 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2375                               bool isVarArg,
2376                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2377                               const SmallVectorImpl<SDValue> &OutVals,
2378                               const SDLoc &DL, SelectionDAG &DAG) const {
2379   MachineFunction &MF = DAG.getMachineFunction();
2380   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2381 
2382   if (AMDGPU::isKernel(CallConv)) {
2383     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2384                                              OutVals, DL, DAG);
2385   }
2386 
2387   bool IsShader = AMDGPU::isShader(CallConv);
2388 
2389   Info->setIfReturnsVoid(Outs.empty());
2390   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2391 
2392   // CCValAssign - represent the assignment of the return value to a location.
2393   SmallVector<CCValAssign, 48> RVLocs;
2394   SmallVector<ISD::OutputArg, 48> Splits;
2395 
2396   // CCState - Info about the registers and stack slots.
2397   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2398                  *DAG.getContext());
2399 
2400   // Analyze outgoing return values.
2401   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2402 
2403   SDValue Flag;
2404   SmallVector<SDValue, 48> RetOps;
2405   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2406 
2407   // Add return address for callable functions.
2408   if (!Info->isEntryFunction()) {
2409     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2410     SDValue ReturnAddrReg = CreateLiveInRegister(
2411       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2412 
2413     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2414         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2415         MVT::i64);
2416     Chain =
2417         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2418     Flag = Chain.getValue(1);
2419     RetOps.push_back(ReturnAddrVirtualReg);
2420   }
2421 
2422   // Copy the result values into the output registers.
2423   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2424        ++I, ++RealRVLocIdx) {
2425     CCValAssign &VA = RVLocs[I];
2426     assert(VA.isRegLoc() && "Can only return in registers!");
2427     // TODO: Partially return in registers if return values don't fit.
2428     SDValue Arg = OutVals[RealRVLocIdx];
2429 
2430     // Copied from other backends.
2431     switch (VA.getLocInfo()) {
2432     case CCValAssign::Full:
2433       break;
2434     case CCValAssign::BCvt:
2435       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2436       break;
2437     case CCValAssign::SExt:
2438       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2439       break;
2440     case CCValAssign::ZExt:
2441       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2442       break;
2443     case CCValAssign::AExt:
2444       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2445       break;
2446     default:
2447       llvm_unreachable("Unknown loc info!");
2448     }
2449 
2450     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2451     Flag = Chain.getValue(1);
2452     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2453   }
2454 
2455   // FIXME: Does sret work properly?
2456   if (!Info->isEntryFunction()) {
2457     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2458     const MCPhysReg *I =
2459       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2460     if (I) {
2461       for (; *I; ++I) {
2462         if (AMDGPU::SReg_64RegClass.contains(*I))
2463           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2464         else if (AMDGPU::SReg_32RegClass.contains(*I))
2465           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2466         else
2467           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2468       }
2469     }
2470   }
2471 
2472   // Update chain and glue.
2473   RetOps[0] = Chain;
2474   if (Flag.getNode())
2475     RetOps.push_back(Flag);
2476 
2477   unsigned Opc = AMDGPUISD::ENDPGM;
2478   if (!IsWaveEnd)
2479     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2480   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2481 }
2482 
2483 SDValue SITargetLowering::LowerCallResult(
2484     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2485     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2486     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2487     SDValue ThisVal) const {
2488   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2489 
2490   // Assign locations to each value returned by this call.
2491   SmallVector<CCValAssign, 16> RVLocs;
2492   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2493                  *DAG.getContext());
2494   CCInfo.AnalyzeCallResult(Ins, RetCC);
2495 
2496   // Copy all of the result registers out of their specified physreg.
2497   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2498     CCValAssign VA = RVLocs[i];
2499     SDValue Val;
2500 
2501     if (VA.isRegLoc()) {
2502       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2503       Chain = Val.getValue(1);
2504       InFlag = Val.getValue(2);
2505     } else if (VA.isMemLoc()) {
2506       report_fatal_error("TODO: return values in memory");
2507     } else
2508       llvm_unreachable("unknown argument location type");
2509 
2510     switch (VA.getLocInfo()) {
2511     case CCValAssign::Full:
2512       break;
2513     case CCValAssign::BCvt:
2514       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2515       break;
2516     case CCValAssign::ZExt:
2517       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2518                         DAG.getValueType(VA.getValVT()));
2519       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2520       break;
2521     case CCValAssign::SExt:
2522       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2523                         DAG.getValueType(VA.getValVT()));
2524       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2525       break;
2526     case CCValAssign::AExt:
2527       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2528       break;
2529     default:
2530       llvm_unreachable("Unknown loc info!");
2531     }
2532 
2533     InVals.push_back(Val);
2534   }
2535 
2536   return Chain;
2537 }
2538 
2539 // Add code to pass special inputs required depending on used features separate
2540 // from the explicit user arguments present in the IR.
2541 void SITargetLowering::passSpecialInputs(
2542     CallLoweringInfo &CLI,
2543     CCState &CCInfo,
2544     const SIMachineFunctionInfo &Info,
2545     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2546     SmallVectorImpl<SDValue> &MemOpChains,
2547     SDValue Chain) const {
2548   // If we don't have a call site, this was a call inserted by
2549   // legalization. These can never use special inputs.
2550   if (!CLI.CB)
2551     return;
2552 
2553   SelectionDAG &DAG = CLI.DAG;
2554   const SDLoc &DL = CLI.DL;
2555 
2556   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2557   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2558 
2559   const AMDGPUFunctionArgInfo *CalleeArgInfo
2560     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2561   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2562     auto &ArgUsageInfo =
2563       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2564     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2565   }
2566 
2567   // TODO: Unify with private memory register handling. This is complicated by
2568   // the fact that at least in kernels, the input argument is not necessarily
2569   // in the same location as the input.
2570   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2571     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2572     AMDGPUFunctionArgInfo::QUEUE_PTR,
2573     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2574     AMDGPUFunctionArgInfo::DISPATCH_ID,
2575     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2576     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2577     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2578   };
2579 
2580   for (auto InputID : InputRegs) {
2581     const ArgDescriptor *OutgoingArg;
2582     const TargetRegisterClass *ArgRC;
2583 
2584     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID);
2585     if (!OutgoingArg)
2586       continue;
2587 
2588     const ArgDescriptor *IncomingArg;
2589     const TargetRegisterClass *IncomingArgRC;
2590     std::tie(IncomingArg, IncomingArgRC)
2591       = CallerArgInfo.getPreloadedValue(InputID);
2592     assert(IncomingArgRC == ArgRC);
2593 
2594     // All special arguments are ints for now.
2595     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2596     SDValue InputReg;
2597 
2598     if (IncomingArg) {
2599       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2600     } else {
2601       // The implicit arg ptr is special because it doesn't have a corresponding
2602       // input for kernels, and is computed from the kernarg segment pointer.
2603       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2604       InputReg = getImplicitArgPtr(DAG, DL);
2605     }
2606 
2607     if (OutgoingArg->isRegister()) {
2608       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2609       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2610         report_fatal_error("failed to allocate implicit input argument");
2611     } else {
2612       unsigned SpecialArgOffset =
2613           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2614       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2615                                               SpecialArgOffset);
2616       MemOpChains.push_back(ArgStore);
2617     }
2618   }
2619 
2620   // Pack workitem IDs into a single register or pass it as is if already
2621   // packed.
2622   const ArgDescriptor *OutgoingArg;
2623   const TargetRegisterClass *ArgRC;
2624 
2625   std::tie(OutgoingArg, ArgRC) =
2626     CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2627   if (!OutgoingArg)
2628     std::tie(OutgoingArg, ArgRC) =
2629       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2630   if (!OutgoingArg)
2631     std::tie(OutgoingArg, ArgRC) =
2632       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2633   if (!OutgoingArg)
2634     return;
2635 
2636   const ArgDescriptor *IncomingArgX
2637     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2638   const ArgDescriptor *IncomingArgY
2639     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2640   const ArgDescriptor *IncomingArgZ
2641     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2642 
2643   SDValue InputReg;
2644   SDLoc SL;
2645 
2646   // If incoming ids are not packed we need to pack them.
2647   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2648     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2649 
2650   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2651     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2652     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2653                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2654     InputReg = InputReg.getNode() ?
2655                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2656   }
2657 
2658   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2659     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2660     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2661                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2662     InputReg = InputReg.getNode() ?
2663                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2664   }
2665 
2666   if (!InputReg.getNode()) {
2667     // Workitem ids are already packed, any of present incoming arguments
2668     // will carry all required fields.
2669     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2670       IncomingArgX ? *IncomingArgX :
2671       IncomingArgY ? *IncomingArgY :
2672                      *IncomingArgZ, ~0u);
2673     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2674   }
2675 
2676   if (OutgoingArg->isRegister()) {
2677     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2678     CCInfo.AllocateReg(OutgoingArg->getRegister());
2679   } else {
2680     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2681     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2682                                             SpecialArgOffset);
2683     MemOpChains.push_back(ArgStore);
2684   }
2685 }
2686 
2687 static bool canGuaranteeTCO(CallingConv::ID CC) {
2688   return CC == CallingConv::Fast;
2689 }
2690 
2691 /// Return true if we might ever do TCO for calls with this calling convention.
2692 static bool mayTailCallThisCC(CallingConv::ID CC) {
2693   switch (CC) {
2694   case CallingConv::C:
2695     return true;
2696   default:
2697     return canGuaranteeTCO(CC);
2698   }
2699 }
2700 
2701 bool SITargetLowering::isEligibleForTailCallOptimization(
2702     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2703     const SmallVectorImpl<ISD::OutputArg> &Outs,
2704     const SmallVectorImpl<SDValue> &OutVals,
2705     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2706   if (!mayTailCallThisCC(CalleeCC))
2707     return false;
2708 
2709   MachineFunction &MF = DAG.getMachineFunction();
2710   const Function &CallerF = MF.getFunction();
2711   CallingConv::ID CallerCC = CallerF.getCallingConv();
2712   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2713   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2714 
2715   // Kernels aren't callable, and don't have a live in return address so it
2716   // doesn't make sense to do a tail call with entry functions.
2717   if (!CallerPreserved)
2718     return false;
2719 
2720   bool CCMatch = CallerCC == CalleeCC;
2721 
2722   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2723     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2724       return true;
2725     return false;
2726   }
2727 
2728   // TODO: Can we handle var args?
2729   if (IsVarArg)
2730     return false;
2731 
2732   for (const Argument &Arg : CallerF.args()) {
2733     if (Arg.hasByValAttr())
2734       return false;
2735   }
2736 
2737   LLVMContext &Ctx = *DAG.getContext();
2738 
2739   // Check that the call results are passed in the same way.
2740   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2741                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2742                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2743     return false;
2744 
2745   // The callee has to preserve all registers the caller needs to preserve.
2746   if (!CCMatch) {
2747     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2748     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2749       return false;
2750   }
2751 
2752   // Nothing more to check if the callee is taking no arguments.
2753   if (Outs.empty())
2754     return true;
2755 
2756   SmallVector<CCValAssign, 16> ArgLocs;
2757   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2758 
2759   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2760 
2761   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2762   // If the stack arguments for this call do not fit into our own save area then
2763   // the call cannot be made tail.
2764   // TODO: Is this really necessary?
2765   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2766     return false;
2767 
2768   const MachineRegisterInfo &MRI = MF.getRegInfo();
2769   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2770 }
2771 
2772 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2773   if (!CI->isTailCall())
2774     return false;
2775 
2776   const Function *ParentFn = CI->getParent()->getParent();
2777   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2778     return false;
2779   return true;
2780 }
2781 
2782 // The wave scratch offset register is used as the global base pointer.
2783 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2784                                     SmallVectorImpl<SDValue> &InVals) const {
2785   SelectionDAG &DAG = CLI.DAG;
2786   const SDLoc &DL = CLI.DL;
2787   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2788   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2789   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2790   SDValue Chain = CLI.Chain;
2791   SDValue Callee = CLI.Callee;
2792   bool &IsTailCall = CLI.IsTailCall;
2793   CallingConv::ID CallConv = CLI.CallConv;
2794   bool IsVarArg = CLI.IsVarArg;
2795   bool IsSibCall = false;
2796   bool IsThisReturn = false;
2797   MachineFunction &MF = DAG.getMachineFunction();
2798 
2799   if (Callee.isUndef() || isNullConstant(Callee)) {
2800     if (!CLI.IsTailCall) {
2801       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2802         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2803     }
2804 
2805     return Chain;
2806   }
2807 
2808   if (IsVarArg) {
2809     return lowerUnhandledCall(CLI, InVals,
2810                               "unsupported call to variadic function ");
2811   }
2812 
2813   if (!CLI.CB)
2814     report_fatal_error("unsupported libcall legalization");
2815 
2816   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2817       !CLI.CB->getCalledFunction()) {
2818     return lowerUnhandledCall(CLI, InVals,
2819                               "unsupported indirect call to function ");
2820   }
2821 
2822   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2823     return lowerUnhandledCall(CLI, InVals,
2824                               "unsupported required tail call to function ");
2825   }
2826 
2827   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2828     // Note the issue is with the CC of the calling function, not of the call
2829     // itself.
2830     return lowerUnhandledCall(CLI, InVals,
2831                           "unsupported call from graphics shader of function ");
2832   }
2833 
2834   if (IsTailCall) {
2835     IsTailCall = isEligibleForTailCallOptimization(
2836       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2837     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2838       report_fatal_error("failed to perform tail call elimination on a call "
2839                          "site marked musttail");
2840     }
2841 
2842     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2843 
2844     // A sibling call is one where we're under the usual C ABI and not planning
2845     // to change that but can still do a tail call:
2846     if (!TailCallOpt && IsTailCall)
2847       IsSibCall = true;
2848 
2849     if (IsTailCall)
2850       ++NumTailCalls;
2851   }
2852 
2853   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2854   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2855   SmallVector<SDValue, 8> MemOpChains;
2856 
2857   // Analyze operands of the call, assigning locations to each operand.
2858   SmallVector<CCValAssign, 16> ArgLocs;
2859   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2860   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2861 
2862   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2863     // With a fixed ABI, allocate fixed registers before user arguments.
2864     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2865   }
2866 
2867   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2868 
2869   // Get a count of how many bytes are to be pushed on the stack.
2870   unsigned NumBytes = CCInfo.getNextStackOffset();
2871 
2872   if (IsSibCall) {
2873     // Since we're not changing the ABI to make this a tail call, the memory
2874     // operands are already available in the caller's incoming argument space.
2875     NumBytes = 0;
2876   }
2877 
2878   // FPDiff is the byte offset of the call's argument area from the callee's.
2879   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2880   // by this amount for a tail call. In a sibling call it must be 0 because the
2881   // caller will deallocate the entire stack and the callee still expects its
2882   // arguments to begin at SP+0. Completely unused for non-tail calls.
2883   int32_t FPDiff = 0;
2884   MachineFrameInfo &MFI = MF.getFrameInfo();
2885 
2886   // Adjust the stack pointer for the new arguments...
2887   // These operations are automatically eliminated by the prolog/epilog pass
2888   if (!IsSibCall) {
2889     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2890 
2891     SmallVector<SDValue, 4> CopyFromChains;
2892 
2893     // In the HSA case, this should be an identity copy.
2894     SDValue ScratchRSrcReg
2895       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2896     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2897     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2898     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2899   }
2900 
2901   MVT PtrVT = MVT::i32;
2902 
2903   // Walk the register/memloc assignments, inserting copies/loads.
2904   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2905     CCValAssign &VA = ArgLocs[i];
2906     SDValue Arg = OutVals[i];
2907 
2908     // Promote the value if needed.
2909     switch (VA.getLocInfo()) {
2910     case CCValAssign::Full:
2911       break;
2912     case CCValAssign::BCvt:
2913       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2914       break;
2915     case CCValAssign::ZExt:
2916       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2917       break;
2918     case CCValAssign::SExt:
2919       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2920       break;
2921     case CCValAssign::AExt:
2922       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2923       break;
2924     case CCValAssign::FPExt:
2925       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2926       break;
2927     default:
2928       llvm_unreachable("Unknown loc info!");
2929     }
2930 
2931     if (VA.isRegLoc()) {
2932       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2933     } else {
2934       assert(VA.isMemLoc());
2935 
2936       SDValue DstAddr;
2937       MachinePointerInfo DstInfo;
2938 
2939       unsigned LocMemOffset = VA.getLocMemOffset();
2940       int32_t Offset = LocMemOffset;
2941 
2942       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2943       MaybeAlign Alignment;
2944 
2945       if (IsTailCall) {
2946         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2947         unsigned OpSize = Flags.isByVal() ?
2948           Flags.getByValSize() : VA.getValVT().getStoreSize();
2949 
2950         // FIXME: We can have better than the minimum byval required alignment.
2951         Alignment =
2952             Flags.isByVal()
2953                 ? Flags.getNonZeroByValAlign()
2954                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2955 
2956         Offset = Offset + FPDiff;
2957         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2958 
2959         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2960         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2961 
2962         // Make sure any stack arguments overlapping with where we're storing
2963         // are loaded before this eventual operation. Otherwise they'll be
2964         // clobbered.
2965 
2966         // FIXME: Why is this really necessary? This seems to just result in a
2967         // lot of code to copy the stack and write them back to the same
2968         // locations, which are supposed to be immutable?
2969         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2970       } else {
2971         DstAddr = PtrOff;
2972         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2973         Alignment =
2974             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2975       }
2976 
2977       if (Outs[i].Flags.isByVal()) {
2978         SDValue SizeNode =
2979             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2980         SDValue Cpy =
2981             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2982                           Outs[i].Flags.getNonZeroByValAlign(),
2983                           /*isVol = */ false, /*AlwaysInline = */ true,
2984                           /*isTailCall = */ false, DstInfo,
2985                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2986 
2987         MemOpChains.push_back(Cpy);
2988       } else {
2989         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2990                                      Alignment ? Alignment->value() : 0);
2991         MemOpChains.push_back(Store);
2992       }
2993     }
2994   }
2995 
2996   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
2997     // Copy special input registers after user input arguments.
2998     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2999   }
3000 
3001   if (!MemOpChains.empty())
3002     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3003 
3004   // Build a sequence of copy-to-reg nodes chained together with token chain
3005   // and flag operands which copy the outgoing args into the appropriate regs.
3006   SDValue InFlag;
3007   for (auto &RegToPass : RegsToPass) {
3008     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3009                              RegToPass.second, InFlag);
3010     InFlag = Chain.getValue(1);
3011   }
3012 
3013 
3014   SDValue PhysReturnAddrReg;
3015   if (IsTailCall) {
3016     // Since the return is being combined with the call, we need to pass on the
3017     // return address.
3018 
3019     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3020     SDValue ReturnAddrReg = CreateLiveInRegister(
3021       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3022 
3023     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3024                                         MVT::i64);
3025     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3026     InFlag = Chain.getValue(1);
3027   }
3028 
3029   // We don't usually want to end the call-sequence here because we would tidy
3030   // the frame up *after* the call, however in the ABI-changing tail-call case
3031   // we've carefully laid out the parameters so that when sp is reset they'll be
3032   // in the correct location.
3033   if (IsTailCall && !IsSibCall) {
3034     Chain = DAG.getCALLSEQ_END(Chain,
3035                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3036                                DAG.getTargetConstant(0, DL, MVT::i32),
3037                                InFlag, DL);
3038     InFlag = Chain.getValue(1);
3039   }
3040 
3041   std::vector<SDValue> Ops;
3042   Ops.push_back(Chain);
3043   Ops.push_back(Callee);
3044   // Add a redundant copy of the callee global which will not be legalized, as
3045   // we need direct access to the callee later.
3046   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3047     const GlobalValue *GV = GSD->getGlobal();
3048     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3049   } else {
3050     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3051   }
3052 
3053   if (IsTailCall) {
3054     // Each tail call may have to adjust the stack by a different amount, so
3055     // this information must travel along with the operation for eventual
3056     // consumption by emitEpilogue.
3057     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3058 
3059     Ops.push_back(PhysReturnAddrReg);
3060   }
3061 
3062   // Add argument registers to the end of the list so that they are known live
3063   // into the call.
3064   for (auto &RegToPass : RegsToPass) {
3065     Ops.push_back(DAG.getRegister(RegToPass.first,
3066                                   RegToPass.second.getValueType()));
3067   }
3068 
3069   // Add a register mask operand representing the call-preserved registers.
3070 
3071   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3072   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3073   assert(Mask && "Missing call preserved mask for calling convention");
3074   Ops.push_back(DAG.getRegisterMask(Mask));
3075 
3076   if (InFlag.getNode())
3077     Ops.push_back(InFlag);
3078 
3079   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3080 
3081   // If we're doing a tall call, use a TC_RETURN here rather than an
3082   // actual call instruction.
3083   if (IsTailCall) {
3084     MFI.setHasTailCall();
3085     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3086   }
3087 
3088   // Returns a chain and a flag for retval copy to use.
3089   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3090   Chain = Call.getValue(0);
3091   InFlag = Call.getValue(1);
3092 
3093   uint64_t CalleePopBytes = NumBytes;
3094   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3095                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3096                              InFlag, DL);
3097   if (!Ins.empty())
3098     InFlag = Chain.getValue(1);
3099 
3100   // Handle result values, copying them out of physregs into vregs that we
3101   // return.
3102   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3103                          InVals, IsThisReturn,
3104                          IsThisReturn ? OutVals[0] : SDValue());
3105 }
3106 
3107 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3108 // except for applying the wave size scale to the increment amount.
3109 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3110     SDValue Op, SelectionDAG &DAG) const {
3111   const MachineFunction &MF = DAG.getMachineFunction();
3112   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3113 
3114   SDLoc dl(Op);
3115   EVT VT = Op.getValueType();
3116   SDValue Tmp1 = Op;
3117   SDValue Tmp2 = Op.getValue(1);
3118   SDValue Tmp3 = Op.getOperand(2);
3119   SDValue Chain = Tmp1.getOperand(0);
3120 
3121   Register SPReg = Info->getStackPtrOffsetReg();
3122 
3123   // Chain the dynamic stack allocation so that it doesn't modify the stack
3124   // pointer when other instructions are using the stack.
3125   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3126 
3127   SDValue Size  = Tmp2.getOperand(1);
3128   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3129   Chain = SP.getValue(1);
3130   unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
3131   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3132   const TargetFrameLowering *TFL = ST.getFrameLowering();
3133   unsigned Opc =
3134     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3135     ISD::ADD : ISD::SUB;
3136 
3137   SDValue ScaledSize = DAG.getNode(
3138       ISD::SHL, dl, VT, Size,
3139       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3140 
3141   unsigned StackAlign = TFL->getStackAlignment();
3142   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3143   if (Align > StackAlign) {
3144     Tmp1 = DAG.getNode(
3145       ISD::AND, dl, VT, Tmp1,
3146       DAG.getConstant(-(uint64_t)Align << ST.getWavefrontSizeLog2(), dl, VT));
3147   }
3148 
3149   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3150   Tmp2 = DAG.getCALLSEQ_END(
3151       Chain, DAG.getIntPtrConstant(0, dl, true),
3152       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3153 
3154   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3155 }
3156 
3157 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3158                                                   SelectionDAG &DAG) const {
3159   // We only handle constant sizes here to allow non-entry block, static sized
3160   // allocas. A truly dynamic value is more difficult to support because we
3161   // don't know if the size value is uniform or not. If the size isn't uniform,
3162   // we would need to do a wave reduction to get the maximum size to know how
3163   // much to increment the uniform stack pointer.
3164   SDValue Size = Op.getOperand(1);
3165   if (isa<ConstantSDNode>(Size))
3166       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3167 
3168   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3169 }
3170 
3171 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3172                                              const MachineFunction &MF) const {
3173   Register Reg = StringSwitch<Register>(RegName)
3174     .Case("m0", AMDGPU::M0)
3175     .Case("exec", AMDGPU::EXEC)
3176     .Case("exec_lo", AMDGPU::EXEC_LO)
3177     .Case("exec_hi", AMDGPU::EXEC_HI)
3178     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3179     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3180     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3181     .Default(Register());
3182 
3183   if (Reg == AMDGPU::NoRegister) {
3184     report_fatal_error(Twine("invalid register name \""
3185                              + StringRef(RegName)  + "\"."));
3186 
3187   }
3188 
3189   if (!Subtarget->hasFlatScrRegister() &&
3190        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3191     report_fatal_error(Twine("invalid register \""
3192                              + StringRef(RegName)  + "\" for subtarget."));
3193   }
3194 
3195   switch (Reg) {
3196   case AMDGPU::M0:
3197   case AMDGPU::EXEC_LO:
3198   case AMDGPU::EXEC_HI:
3199   case AMDGPU::FLAT_SCR_LO:
3200   case AMDGPU::FLAT_SCR_HI:
3201     if (VT.getSizeInBits() == 32)
3202       return Reg;
3203     break;
3204   case AMDGPU::EXEC:
3205   case AMDGPU::FLAT_SCR:
3206     if (VT.getSizeInBits() == 64)
3207       return Reg;
3208     break;
3209   default:
3210     llvm_unreachable("missing register type checking");
3211   }
3212 
3213   report_fatal_error(Twine("invalid type for register \""
3214                            + StringRef(RegName) + "\"."));
3215 }
3216 
3217 // If kill is not the last instruction, split the block so kill is always a
3218 // proper terminator.
3219 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3220                                                     MachineBasicBlock *BB) const {
3221   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3222 
3223   MachineBasicBlock::iterator SplitPoint(&MI);
3224   ++SplitPoint;
3225 
3226   if (SplitPoint == BB->end()) {
3227     // Don't bother with a new block.
3228     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3229     return BB;
3230   }
3231 
3232   MachineFunction *MF = BB->getParent();
3233   MachineBasicBlock *SplitBB
3234     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3235 
3236   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3237   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3238 
3239   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3240   BB->addSuccessor(SplitBB);
3241 
3242   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3243   return SplitBB;
3244 }
3245 
3246 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3247 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3248 // be the first instruction in the remainder block.
3249 //
3250 /// \returns { LoopBody, Remainder }
3251 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3252 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3253   MachineFunction *MF = MBB.getParent();
3254   MachineBasicBlock::iterator I(&MI);
3255 
3256   // To insert the loop we need to split the block. Move everything after this
3257   // point to a new block, and insert a new empty block between the two.
3258   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3259   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3260   MachineFunction::iterator MBBI(MBB);
3261   ++MBBI;
3262 
3263   MF->insert(MBBI, LoopBB);
3264   MF->insert(MBBI, RemainderBB);
3265 
3266   LoopBB->addSuccessor(LoopBB);
3267   LoopBB->addSuccessor(RemainderBB);
3268 
3269   // Move the rest of the block into a new block.
3270   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3271 
3272   if (InstInLoop) {
3273     auto Next = std::next(I);
3274 
3275     // Move instruction to loop body.
3276     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3277 
3278     // Move the rest of the block.
3279     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3280   } else {
3281     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3282   }
3283 
3284   MBB.addSuccessor(LoopBB);
3285 
3286   return std::make_pair(LoopBB, RemainderBB);
3287 }
3288 
3289 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3290 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3291   MachineBasicBlock *MBB = MI.getParent();
3292   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3293   auto I = MI.getIterator();
3294   auto E = std::next(I);
3295 
3296   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3297     .addImm(0);
3298 
3299   MIBundleBuilder Bundler(*MBB, I, E);
3300   finalizeBundle(*MBB, Bundler.begin());
3301 }
3302 
3303 MachineBasicBlock *
3304 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3305                                          MachineBasicBlock *BB) const {
3306   const DebugLoc &DL = MI.getDebugLoc();
3307 
3308   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3309 
3310   MachineBasicBlock *LoopBB;
3311   MachineBasicBlock *RemainderBB;
3312   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3313 
3314   // Apparently kill flags are only valid if the def is in the same block?
3315   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3316     Src->setIsKill(false);
3317 
3318   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3319 
3320   MachineBasicBlock::iterator I = LoopBB->end();
3321 
3322   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3323     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3324 
3325   // Clear TRAP_STS.MEM_VIOL
3326   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3327     .addImm(0)
3328     .addImm(EncodedReg);
3329 
3330   bundleInstWithWaitcnt(MI);
3331 
3332   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3333 
3334   // Load and check TRAP_STS.MEM_VIOL
3335   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3336     .addImm(EncodedReg);
3337 
3338   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3339   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3340     .addReg(Reg, RegState::Kill)
3341     .addImm(0);
3342   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3343     .addMBB(LoopBB);
3344 
3345   return RemainderBB;
3346 }
3347 
3348 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3349 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3350 // will only do one iteration. In the worst case, this will loop 64 times.
3351 //
3352 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3353 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3354   const SIInstrInfo *TII,
3355   MachineRegisterInfo &MRI,
3356   MachineBasicBlock &OrigBB,
3357   MachineBasicBlock &LoopBB,
3358   const DebugLoc &DL,
3359   const MachineOperand &IdxReg,
3360   unsigned InitReg,
3361   unsigned ResultReg,
3362   unsigned PhiReg,
3363   unsigned InitSaveExecReg,
3364   int Offset,
3365   bool UseGPRIdxMode,
3366   bool IsIndirectSrc) {
3367   MachineFunction *MF = OrigBB.getParent();
3368   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3369   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3370   MachineBasicBlock::iterator I = LoopBB.begin();
3371 
3372   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3373   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3374   Register NewExec = MRI.createVirtualRegister(BoolRC);
3375   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3376   Register CondReg = MRI.createVirtualRegister(BoolRC);
3377 
3378   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3379     .addReg(InitReg)
3380     .addMBB(&OrigBB)
3381     .addReg(ResultReg)
3382     .addMBB(&LoopBB);
3383 
3384   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3385     .addReg(InitSaveExecReg)
3386     .addMBB(&OrigBB)
3387     .addReg(NewExec)
3388     .addMBB(&LoopBB);
3389 
3390   // Read the next variant <- also loop target.
3391   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3392     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3393 
3394   // Compare the just read M0 value to all possible Idx values.
3395   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3396     .addReg(CurrentIdxReg)
3397     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3398 
3399   // Update EXEC, save the original EXEC value to VCC.
3400   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3401                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3402           NewExec)
3403     .addReg(CondReg, RegState::Kill);
3404 
3405   MRI.setSimpleHint(NewExec, CondReg);
3406 
3407   if (UseGPRIdxMode) {
3408     unsigned IdxReg;
3409     if (Offset == 0) {
3410       IdxReg = CurrentIdxReg;
3411     } else {
3412       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3413       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3414         .addReg(CurrentIdxReg, RegState::Kill)
3415         .addImm(Offset);
3416     }
3417     unsigned IdxMode = IsIndirectSrc ?
3418       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3419     MachineInstr *SetOn =
3420       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3421       .addReg(IdxReg, RegState::Kill)
3422       .addImm(IdxMode);
3423     SetOn->getOperand(3).setIsUndef();
3424   } else {
3425     // Move index from VCC into M0
3426     if (Offset == 0) {
3427       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3428         .addReg(CurrentIdxReg, RegState::Kill);
3429     } else {
3430       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3431         .addReg(CurrentIdxReg, RegState::Kill)
3432         .addImm(Offset);
3433     }
3434   }
3435 
3436   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3437   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3438   MachineInstr *InsertPt =
3439     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3440                                                   : AMDGPU::S_XOR_B64_term), Exec)
3441       .addReg(Exec)
3442       .addReg(NewExec);
3443 
3444   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3445   // s_cbranch_scc0?
3446 
3447   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3448   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3449     .addMBB(&LoopBB);
3450 
3451   return InsertPt->getIterator();
3452 }
3453 
3454 // This has slightly sub-optimal regalloc when the source vector is killed by
3455 // the read. The register allocator does not understand that the kill is
3456 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3457 // subregister from it, using 1 more VGPR than necessary. This was saved when
3458 // this was expanded after register allocation.
3459 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3460                                                   MachineBasicBlock &MBB,
3461                                                   MachineInstr &MI,
3462                                                   unsigned InitResultReg,
3463                                                   unsigned PhiReg,
3464                                                   int Offset,
3465                                                   bool UseGPRIdxMode,
3466                                                   bool IsIndirectSrc) {
3467   MachineFunction *MF = MBB.getParent();
3468   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3469   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3470   MachineRegisterInfo &MRI = MF->getRegInfo();
3471   const DebugLoc &DL = MI.getDebugLoc();
3472   MachineBasicBlock::iterator I(&MI);
3473 
3474   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3475   Register DstReg = MI.getOperand(0).getReg();
3476   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3477   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3478   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3479   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3480 
3481   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3482 
3483   // Save the EXEC mask
3484   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3485     .addReg(Exec);
3486 
3487   MachineBasicBlock *LoopBB;
3488   MachineBasicBlock *RemainderBB;
3489   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3490 
3491   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3492 
3493   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3494                                       InitResultReg, DstReg, PhiReg, TmpExec,
3495                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3496   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3497   MachineFunction::iterator MBBI(LoopBB);
3498   ++MBBI;
3499   MF->insert(MBBI, LandingPad);
3500   LoopBB->removeSuccessor(RemainderBB);
3501   LandingPad->addSuccessor(RemainderBB);
3502   LoopBB->addSuccessor(LandingPad);
3503   MachineBasicBlock::iterator First = LandingPad->begin();
3504   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3505     .addReg(SaveExec);
3506 
3507   return InsPt;
3508 }
3509 
3510 // Returns subreg index, offset
3511 static std::pair<unsigned, int>
3512 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3513                             const TargetRegisterClass *SuperRC,
3514                             unsigned VecReg,
3515                             int Offset) {
3516   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3517 
3518   // Skip out of bounds offsets, or else we would end up using an undefined
3519   // register.
3520   if (Offset >= NumElts || Offset < 0)
3521     return std::make_pair(AMDGPU::sub0, Offset);
3522 
3523   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3524 }
3525 
3526 // Return true if the index is an SGPR and was set.
3527 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3528                                  MachineRegisterInfo &MRI,
3529                                  MachineInstr &MI,
3530                                  int Offset,
3531                                  bool UseGPRIdxMode,
3532                                  bool IsIndirectSrc) {
3533   MachineBasicBlock *MBB = MI.getParent();
3534   const DebugLoc &DL = MI.getDebugLoc();
3535   MachineBasicBlock::iterator I(&MI);
3536 
3537   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3538   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3539 
3540   assert(Idx->getReg() != AMDGPU::NoRegister);
3541 
3542   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3543     return false;
3544 
3545   if (UseGPRIdxMode) {
3546     unsigned IdxMode = IsIndirectSrc ?
3547       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3548     if (Offset == 0) {
3549       MachineInstr *SetOn =
3550           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3551               .add(*Idx)
3552               .addImm(IdxMode);
3553 
3554       SetOn->getOperand(3).setIsUndef();
3555     } else {
3556       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3557       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3558           .add(*Idx)
3559           .addImm(Offset);
3560       MachineInstr *SetOn =
3561         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3562         .addReg(Tmp, RegState::Kill)
3563         .addImm(IdxMode);
3564 
3565       SetOn->getOperand(3).setIsUndef();
3566     }
3567 
3568     return true;
3569   }
3570 
3571   if (Offset == 0) {
3572     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3573       .add(*Idx);
3574   } else {
3575     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3576       .add(*Idx)
3577       .addImm(Offset);
3578   }
3579 
3580   return true;
3581 }
3582 
3583 // Control flow needs to be inserted if indexing with a VGPR.
3584 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3585                                           MachineBasicBlock &MBB,
3586                                           const GCNSubtarget &ST) {
3587   const SIInstrInfo *TII = ST.getInstrInfo();
3588   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3589   MachineFunction *MF = MBB.getParent();
3590   MachineRegisterInfo &MRI = MF->getRegInfo();
3591 
3592   Register Dst = MI.getOperand(0).getReg();
3593   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3594   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3595 
3596   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3597 
3598   unsigned SubReg;
3599   std::tie(SubReg, Offset)
3600     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3601 
3602   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3603 
3604   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3605     MachineBasicBlock::iterator I(&MI);
3606     const DebugLoc &DL = MI.getDebugLoc();
3607 
3608     if (UseGPRIdxMode) {
3609       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3610       // to avoid interfering with other uses, so probably requires a new
3611       // optimization pass.
3612       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3613         .addReg(SrcReg, RegState::Undef, SubReg)
3614         .addReg(SrcReg, RegState::Implicit)
3615         .addReg(AMDGPU::M0, RegState::Implicit);
3616       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3617     } else {
3618       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3619         .addReg(SrcReg, RegState::Undef, SubReg)
3620         .addReg(SrcReg, RegState::Implicit);
3621     }
3622 
3623     MI.eraseFromParent();
3624 
3625     return &MBB;
3626   }
3627 
3628   const DebugLoc &DL = MI.getDebugLoc();
3629   MachineBasicBlock::iterator I(&MI);
3630 
3631   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3632   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3633 
3634   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3635 
3636   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3637                               Offset, UseGPRIdxMode, true);
3638   MachineBasicBlock *LoopBB = InsPt->getParent();
3639 
3640   if (UseGPRIdxMode) {
3641     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3642       .addReg(SrcReg, RegState::Undef, SubReg)
3643       .addReg(SrcReg, RegState::Implicit)
3644       .addReg(AMDGPU::M0, RegState::Implicit);
3645     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3646   } else {
3647     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3648       .addReg(SrcReg, RegState::Undef, SubReg)
3649       .addReg(SrcReg, RegState::Implicit);
3650   }
3651 
3652   MI.eraseFromParent();
3653 
3654   return LoopBB;
3655 }
3656 
3657 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3658                                           MachineBasicBlock &MBB,
3659                                           const GCNSubtarget &ST) {
3660   const SIInstrInfo *TII = ST.getInstrInfo();
3661   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3662   MachineFunction *MF = MBB.getParent();
3663   MachineRegisterInfo &MRI = MF->getRegInfo();
3664 
3665   Register Dst = MI.getOperand(0).getReg();
3666   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3667   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3668   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3669   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3670   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3671 
3672   // This can be an immediate, but will be folded later.
3673   assert(Val->getReg());
3674 
3675   unsigned SubReg;
3676   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3677                                                          SrcVec->getReg(),
3678                                                          Offset);
3679   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3680 
3681   if (Idx->getReg() == AMDGPU::NoRegister) {
3682     MachineBasicBlock::iterator I(&MI);
3683     const DebugLoc &DL = MI.getDebugLoc();
3684 
3685     assert(Offset == 0);
3686 
3687     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3688         .add(*SrcVec)
3689         .add(*Val)
3690         .addImm(SubReg);
3691 
3692     MI.eraseFromParent();
3693     return &MBB;
3694   }
3695 
3696   const MCInstrDesc &MovRelDesc
3697     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3698 
3699   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3700     MachineBasicBlock::iterator I(&MI);
3701     const DebugLoc &DL = MI.getDebugLoc();
3702     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3703       .addReg(SrcVec->getReg())
3704       .add(*Val)
3705       .addImm(SubReg);
3706     if (UseGPRIdxMode)
3707       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3708 
3709     MI.eraseFromParent();
3710     return &MBB;
3711   }
3712 
3713   if (Val->isReg())
3714     MRI.clearKillFlags(Val->getReg());
3715 
3716   const DebugLoc &DL = MI.getDebugLoc();
3717 
3718   Register PhiReg = MRI.createVirtualRegister(VecRC);
3719 
3720   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3721                               Offset, UseGPRIdxMode, false);
3722   MachineBasicBlock *LoopBB = InsPt->getParent();
3723 
3724   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3725     .addReg(PhiReg)
3726     .add(*Val)
3727     .addImm(AMDGPU::sub0);
3728   if (UseGPRIdxMode)
3729     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3730 
3731   MI.eraseFromParent();
3732   return LoopBB;
3733 }
3734 
3735 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3736   MachineInstr &MI, MachineBasicBlock *BB) const {
3737 
3738   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3739   MachineFunction *MF = BB->getParent();
3740   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3741 
3742   switch (MI.getOpcode()) {
3743   case AMDGPU::S_UADDO_PSEUDO:
3744   case AMDGPU::S_USUBO_PSEUDO: {
3745     const DebugLoc &DL = MI.getDebugLoc();
3746     MachineOperand &Dest0 = MI.getOperand(0);
3747     MachineOperand &Dest1 = MI.getOperand(1);
3748     MachineOperand &Src0 = MI.getOperand(2);
3749     MachineOperand &Src1 = MI.getOperand(3);
3750 
3751     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3752                        ? AMDGPU::S_ADD_I32
3753                        : AMDGPU::S_SUB_I32;
3754     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3755 
3756     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3757         .addImm(1)
3758         .addImm(0);
3759 
3760     MI.eraseFromParent();
3761     return BB;
3762   }
3763   case AMDGPU::S_ADD_U64_PSEUDO:
3764   case AMDGPU::S_SUB_U64_PSEUDO: {
3765     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3766     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3767     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3768     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3769     const DebugLoc &DL = MI.getDebugLoc();
3770 
3771     MachineOperand &Dest = MI.getOperand(0);
3772     MachineOperand &Src0 = MI.getOperand(1);
3773     MachineOperand &Src1 = MI.getOperand(2);
3774 
3775     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3776     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3777 
3778     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3779         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3780     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3781         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3782 
3783     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3784         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3785     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3786         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3787 
3788     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3789 
3790     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3791     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3792     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3793     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3794     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3795         .addReg(DestSub0)
3796         .addImm(AMDGPU::sub0)
3797         .addReg(DestSub1)
3798         .addImm(AMDGPU::sub1);
3799     MI.eraseFromParent();
3800     return BB;
3801   }
3802   case AMDGPU::V_ADD_U64_PSEUDO:
3803   case AMDGPU::V_SUB_U64_PSEUDO: {
3804     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3805     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3806     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3807     const DebugLoc &DL = MI.getDebugLoc();
3808 
3809     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3810 
3811     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3812 
3813     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3814     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3815 
3816     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3817     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3818 
3819     MachineOperand &Dest = MI.getOperand(0);
3820     MachineOperand &Src0 = MI.getOperand(1);
3821     MachineOperand &Src1 = MI.getOperand(2);
3822 
3823     const TargetRegisterClass *Src0RC = Src0.isReg()
3824                                             ? MRI.getRegClass(Src0.getReg())
3825                                             : &AMDGPU::VReg_64RegClass;
3826     const TargetRegisterClass *Src1RC = Src1.isReg()
3827                                             ? MRI.getRegClass(Src1.getReg())
3828                                             : &AMDGPU::VReg_64RegClass;
3829 
3830     const TargetRegisterClass *Src0SubRC =
3831         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3832     const TargetRegisterClass *Src1SubRC =
3833         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3834 
3835     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3836         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3837     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3838         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3839 
3840     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3841         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3842     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3843         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3844 
3845     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
3846     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3847                                .addReg(CarryReg, RegState::Define)
3848                                .add(SrcReg0Sub0)
3849                                .add(SrcReg1Sub0)
3850                                .addImm(0); // clamp bit
3851 
3852     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3853     MachineInstr *HiHalf =
3854         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3855             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3856             .add(SrcReg0Sub1)
3857             .add(SrcReg1Sub1)
3858             .addReg(CarryReg, RegState::Kill)
3859             .addImm(0); // clamp bit
3860 
3861     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3862         .addReg(DestSub0)
3863         .addImm(AMDGPU::sub0)
3864         .addReg(DestSub1)
3865         .addImm(AMDGPU::sub1);
3866     TII->legalizeOperands(*LoHalf);
3867     TII->legalizeOperands(*HiHalf);
3868     MI.eraseFromParent();
3869     return BB;
3870   }
3871   case AMDGPU::S_ADD_CO_PSEUDO:
3872   case AMDGPU::S_SUB_CO_PSEUDO: {
3873     // This pseudo has a chance to be selected
3874     // only from uniform add/subcarry node. All the VGPR operands
3875     // therefore assumed to be splat vectors.
3876     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3877     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3878     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3879     MachineBasicBlock::iterator MII = MI;
3880     const DebugLoc &DL = MI.getDebugLoc();
3881     MachineOperand &Dest = MI.getOperand(0);
3882     MachineOperand &Src0 = MI.getOperand(2);
3883     MachineOperand &Src1 = MI.getOperand(3);
3884     MachineOperand &Src2 = MI.getOperand(4);
3885     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3886                        ? AMDGPU::S_ADDC_U32
3887                        : AMDGPU::S_SUBB_U32;
3888     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3889       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3890       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3891           .addReg(Src0.getReg());
3892       Src0.setReg(RegOp0);
3893     }
3894     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3895       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3896       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3897           .addReg(Src1.getReg());
3898       Src1.setReg(RegOp1);
3899     }
3900     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3901     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3902       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3903           .addReg(Src2.getReg());
3904       Src2.setReg(RegOp2);
3905     }
3906 
3907     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
3908       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3909           .addReg(Src2.getReg())
3910           .addImm(0);
3911     } else {
3912       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
3913           .addReg(Src2.getReg())
3914           .addImm(0);
3915     }
3916 
3917     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
3918     MI.eraseFromParent();
3919     return BB;
3920   }
3921   case AMDGPU::SI_INIT_M0: {
3922     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3923             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3924         .add(MI.getOperand(0));
3925     MI.eraseFromParent();
3926     return BB;
3927   }
3928   case AMDGPU::SI_INIT_EXEC:
3929     // This should be before all vector instructions.
3930     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3931             AMDGPU::EXEC)
3932         .addImm(MI.getOperand(0).getImm());
3933     MI.eraseFromParent();
3934     return BB;
3935 
3936   case AMDGPU::SI_INIT_EXEC_LO:
3937     // This should be before all vector instructions.
3938     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3939             AMDGPU::EXEC_LO)
3940         .addImm(MI.getOperand(0).getImm());
3941     MI.eraseFromParent();
3942     return BB;
3943 
3944   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3945     // Extract the thread count from an SGPR input and set EXEC accordingly.
3946     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3947     //
3948     // S_BFE_U32 count, input, {shift, 7}
3949     // S_BFM_B64 exec, count, 0
3950     // S_CMP_EQ_U32 count, 64
3951     // S_CMOV_B64 exec, -1
3952     MachineInstr *FirstMI = &*BB->begin();
3953     MachineRegisterInfo &MRI = MF->getRegInfo();
3954     Register InputReg = MI.getOperand(0).getReg();
3955     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3956     bool Found = false;
3957 
3958     // Move the COPY of the input reg to the beginning, so that we can use it.
3959     for (auto I = BB->begin(); I != &MI; I++) {
3960       if (I->getOpcode() != TargetOpcode::COPY ||
3961           I->getOperand(0).getReg() != InputReg)
3962         continue;
3963 
3964       if (I == FirstMI) {
3965         FirstMI = &*++BB->begin();
3966       } else {
3967         I->removeFromParent();
3968         BB->insert(FirstMI, &*I);
3969       }
3970       Found = true;
3971       break;
3972     }
3973     assert(Found);
3974     (void)Found;
3975 
3976     // This should be before all vector instructions.
3977     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3978     bool isWave32 = getSubtarget()->isWave32();
3979     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3980     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3981         .addReg(InputReg)
3982         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3983     BuildMI(*BB, FirstMI, DebugLoc(),
3984             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3985             Exec)
3986         .addReg(CountReg)
3987         .addImm(0);
3988     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3989         .addReg(CountReg, RegState::Kill)
3990         .addImm(getSubtarget()->getWavefrontSize());
3991     BuildMI(*BB, FirstMI, DebugLoc(),
3992             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3993             Exec)
3994         .addImm(-1);
3995     MI.eraseFromParent();
3996     return BB;
3997   }
3998 
3999   case AMDGPU::GET_GROUPSTATICSIZE: {
4000     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4001            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4002     DebugLoc DL = MI.getDebugLoc();
4003     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4004         .add(MI.getOperand(0))
4005         .addImm(MFI->getLDSSize());
4006     MI.eraseFromParent();
4007     return BB;
4008   }
4009   case AMDGPU::SI_INDIRECT_SRC_V1:
4010   case AMDGPU::SI_INDIRECT_SRC_V2:
4011   case AMDGPU::SI_INDIRECT_SRC_V4:
4012   case AMDGPU::SI_INDIRECT_SRC_V8:
4013   case AMDGPU::SI_INDIRECT_SRC_V16:
4014   case AMDGPU::SI_INDIRECT_SRC_V32:
4015     return emitIndirectSrc(MI, *BB, *getSubtarget());
4016   case AMDGPU::SI_INDIRECT_DST_V1:
4017   case AMDGPU::SI_INDIRECT_DST_V2:
4018   case AMDGPU::SI_INDIRECT_DST_V4:
4019   case AMDGPU::SI_INDIRECT_DST_V8:
4020   case AMDGPU::SI_INDIRECT_DST_V16:
4021   case AMDGPU::SI_INDIRECT_DST_V32:
4022     return emitIndirectDst(MI, *BB, *getSubtarget());
4023   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4024   case AMDGPU::SI_KILL_I1_PSEUDO:
4025     return splitKillBlock(MI, BB);
4026   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4027     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4028     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4029     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4030 
4031     Register Dst = MI.getOperand(0).getReg();
4032     Register Src0 = MI.getOperand(1).getReg();
4033     Register Src1 = MI.getOperand(2).getReg();
4034     const DebugLoc &DL = MI.getDebugLoc();
4035     Register SrcCond = MI.getOperand(3).getReg();
4036 
4037     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4038     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4039     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4040     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4041 
4042     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4043       .addReg(SrcCond);
4044     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4045       .addImm(0)
4046       .addReg(Src0, 0, AMDGPU::sub0)
4047       .addImm(0)
4048       .addReg(Src1, 0, AMDGPU::sub0)
4049       .addReg(SrcCondCopy);
4050     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4051       .addImm(0)
4052       .addReg(Src0, 0, AMDGPU::sub1)
4053       .addImm(0)
4054       .addReg(Src1, 0, AMDGPU::sub1)
4055       .addReg(SrcCondCopy);
4056 
4057     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4058       .addReg(DstLo)
4059       .addImm(AMDGPU::sub0)
4060       .addReg(DstHi)
4061       .addImm(AMDGPU::sub1);
4062     MI.eraseFromParent();
4063     return BB;
4064   }
4065   case AMDGPU::SI_BR_UNDEF: {
4066     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4067     const DebugLoc &DL = MI.getDebugLoc();
4068     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4069                            .add(MI.getOperand(0));
4070     Br->getOperand(1).setIsUndef(true); // read undef SCC
4071     MI.eraseFromParent();
4072     return BB;
4073   }
4074   case AMDGPU::ADJCALLSTACKUP:
4075   case AMDGPU::ADJCALLSTACKDOWN: {
4076     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4077     MachineInstrBuilder MIB(*MF, &MI);
4078 
4079     // Add an implicit use of the frame offset reg to prevent the restore copy
4080     // inserted after the call from being reorderd after stack operations in the
4081     // the caller's frame.
4082     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4083         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
4084         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
4085     return BB;
4086   }
4087   case AMDGPU::SI_CALL_ISEL: {
4088     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4089     const DebugLoc &DL = MI.getDebugLoc();
4090 
4091     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4092 
4093     MachineInstrBuilder MIB;
4094     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4095 
4096     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4097       MIB.add(MI.getOperand(I));
4098 
4099     MIB.cloneMemRefs(MI);
4100     MI.eraseFromParent();
4101     return BB;
4102   }
4103   case AMDGPU::V_ADD_I32_e32:
4104   case AMDGPU::V_SUB_I32_e32:
4105   case AMDGPU::V_SUBREV_I32_e32: {
4106     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4107     const DebugLoc &DL = MI.getDebugLoc();
4108     unsigned Opc = MI.getOpcode();
4109 
4110     bool NeedClampOperand = false;
4111     if (TII->pseudoToMCOpcode(Opc) == -1) {
4112       Opc = AMDGPU::getVOPe64(Opc);
4113       NeedClampOperand = true;
4114     }
4115 
4116     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4117     if (TII->isVOP3(*I)) {
4118       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4119       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4120       I.addReg(TRI->getVCC(), RegState::Define);
4121     }
4122     I.add(MI.getOperand(1))
4123      .add(MI.getOperand(2));
4124     if (NeedClampOperand)
4125       I.addImm(0); // clamp bit for e64 encoding
4126 
4127     TII->legalizeOperands(*I);
4128 
4129     MI.eraseFromParent();
4130     return BB;
4131   }
4132   case AMDGPU::DS_GWS_INIT:
4133   case AMDGPU::DS_GWS_SEMA_V:
4134   case AMDGPU::DS_GWS_SEMA_BR:
4135   case AMDGPU::DS_GWS_SEMA_P:
4136   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4137   case AMDGPU::DS_GWS_BARRIER:
4138     // A s_waitcnt 0 is required to be the instruction immediately following.
4139     if (getSubtarget()->hasGWSAutoReplay()) {
4140       bundleInstWithWaitcnt(MI);
4141       return BB;
4142     }
4143 
4144     return emitGWSMemViolTestLoop(MI, BB);
4145   case AMDGPU::S_SETREG_B32: {
4146     if (!getSubtarget()->hasDenormModeInst())
4147       return BB;
4148 
4149     // Try to optimize cases that only set the denormal mode or rounding mode.
4150     //
4151     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4152     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4153     // instead.
4154     //
4155     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4156     // allow you to have a no side effect instruction in the output of a
4157     // sideeffecting pattern.
4158 
4159     // TODO: Should also emit a no side effects pseudo if only FP bits are
4160     // touched, even if not all of them or to a variable.
4161     unsigned ID, Offset, Width;
4162     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4163     if (ID != AMDGPU::Hwreg::ID_MODE)
4164       return BB;
4165 
4166     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4167     const unsigned SetMask = WidthMask << Offset;
4168     unsigned SetDenormOp = 0;
4169     unsigned SetRoundOp = 0;
4170 
4171     // The dedicated instructions can only set the whole denorm or round mode at
4172     // once, not a subset of bits in either.
4173     if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4174                                   AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) {
4175       // If this fully sets both the round and denorm mode, emit the two
4176       // dedicated instructions for these.
4177       assert(Offset == 0);
4178       SetRoundOp = AMDGPU::S_ROUND_MODE;
4179       SetDenormOp = AMDGPU::S_DENORM_MODE;
4180     } else if (Width == 4) {
4181       if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) {
4182         SetRoundOp = AMDGPU::S_ROUND_MODE;
4183         assert(Offset == 0);
4184       } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) {
4185         SetDenormOp = AMDGPU::S_DENORM_MODE;
4186         assert(Offset == 4);
4187       }
4188     }
4189 
4190     if (SetRoundOp || SetDenormOp) {
4191       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4192       MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4193       if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4194         unsigned ImmVal = Def->getOperand(1).getImm();
4195         if (SetRoundOp) {
4196           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4197             .addImm(ImmVal & 0xf);
4198 
4199           // If we also have the denorm mode, get just the denorm mode bits.
4200           ImmVal >>= 4;
4201         }
4202 
4203         if (SetDenormOp) {
4204           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4205             .addImm(ImmVal & 0xf);
4206         }
4207 
4208         MI.eraseFromParent();
4209       }
4210     }
4211 
4212     return BB;
4213   }
4214   default:
4215     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4216   }
4217 }
4218 
4219 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4220   return isTypeLegal(VT.getScalarType());
4221 }
4222 
4223 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4224   // This currently forces unfolding various combinations of fsub into fma with
4225   // free fneg'd operands. As long as we have fast FMA (controlled by
4226   // isFMAFasterThanFMulAndFAdd), we should perform these.
4227 
4228   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4229   // most of these combines appear to be cycle neutral but save on instruction
4230   // count / code size.
4231   return true;
4232 }
4233 
4234 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4235                                          EVT VT) const {
4236   if (!VT.isVector()) {
4237     return MVT::i1;
4238   }
4239   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4240 }
4241 
4242 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4243   // TODO: Should i16 be used always if legal? For now it would force VALU
4244   // shifts.
4245   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4246 }
4247 
4248 // Answering this is somewhat tricky and depends on the specific device which
4249 // have different rates for fma or all f64 operations.
4250 //
4251 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4252 // regardless of which device (although the number of cycles differs between
4253 // devices), so it is always profitable for f64.
4254 //
4255 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4256 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4257 // which we can always do even without fused FP ops since it returns the same
4258 // result as the separate operations and since it is always full
4259 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4260 // however does not support denormals, so we do report fma as faster if we have
4261 // a fast fma device and require denormals.
4262 //
4263 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4264                                                   EVT VT) const {
4265   VT = VT.getScalarType();
4266 
4267   switch (VT.getSimpleVT().SimpleTy) {
4268   case MVT::f32: {
4269     // This is as fast on some subtargets. However, we always have full rate f32
4270     // mad available which returns the same result as the separate operations
4271     // which we should prefer over fma. We can't use this if we want to support
4272     // denormals, so only report this in these cases.
4273     if (hasFP32Denormals(MF))
4274       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4275 
4276     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4277     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4278   }
4279   case MVT::f64:
4280     return true;
4281   case MVT::f16:
4282     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4283   default:
4284     break;
4285   }
4286 
4287   return false;
4288 }
4289 
4290 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4291                                    const SDNode *N) const {
4292   // TODO: Check future ftz flag
4293   // v_mad_f32/v_mac_f32 do not support denormals.
4294   EVT VT = N->getValueType(0);
4295   if (VT == MVT::f32)
4296     return Subtarget->hasMadMacF32Insts() &&
4297            !hasFP32Denormals(DAG.getMachineFunction());
4298   if (VT == MVT::f16) {
4299     return Subtarget->hasMadF16() &&
4300            !hasFP64FP16Denormals(DAG.getMachineFunction());
4301   }
4302 
4303   return false;
4304 }
4305 
4306 //===----------------------------------------------------------------------===//
4307 // Custom DAG Lowering Operations
4308 //===----------------------------------------------------------------------===//
4309 
4310 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4311 // wider vector type is legal.
4312 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4313                                              SelectionDAG &DAG) const {
4314   unsigned Opc = Op.getOpcode();
4315   EVT VT = Op.getValueType();
4316   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4317 
4318   SDValue Lo, Hi;
4319   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4320 
4321   SDLoc SL(Op);
4322   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4323                              Op->getFlags());
4324   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4325                              Op->getFlags());
4326 
4327   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4328 }
4329 
4330 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4331 // wider vector type is legal.
4332 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4333                                               SelectionDAG &DAG) const {
4334   unsigned Opc = Op.getOpcode();
4335   EVT VT = Op.getValueType();
4336   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4337 
4338   SDValue Lo0, Hi0;
4339   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4340   SDValue Lo1, Hi1;
4341   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4342 
4343   SDLoc SL(Op);
4344 
4345   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4346                              Op->getFlags());
4347   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4348                              Op->getFlags());
4349 
4350   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4351 }
4352 
4353 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4354                                               SelectionDAG &DAG) const {
4355   unsigned Opc = Op.getOpcode();
4356   EVT VT = Op.getValueType();
4357   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4358 
4359   SDValue Lo0, Hi0;
4360   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4361   SDValue Lo1, Hi1;
4362   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4363   SDValue Lo2, Hi2;
4364   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4365 
4366   SDLoc SL(Op);
4367 
4368   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4369                              Op->getFlags());
4370   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4371                              Op->getFlags());
4372 
4373   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4374 }
4375 
4376 
4377 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4378   switch (Op.getOpcode()) {
4379   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4380   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4381   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4382   case ISD::LOAD: {
4383     SDValue Result = LowerLOAD(Op, DAG);
4384     assert((!Result.getNode() ||
4385             Result.getNode()->getNumValues() == 2) &&
4386            "Load should return a value and a chain");
4387     return Result;
4388   }
4389 
4390   case ISD::FSIN:
4391   case ISD::FCOS:
4392     return LowerTrig(Op, DAG);
4393   case ISD::SELECT: return LowerSELECT(Op, DAG);
4394   case ISD::FDIV: return LowerFDIV(Op, DAG);
4395   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4396   case ISD::STORE: return LowerSTORE(Op, DAG);
4397   case ISD::GlobalAddress: {
4398     MachineFunction &MF = DAG.getMachineFunction();
4399     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4400     return LowerGlobalAddress(MFI, Op, DAG);
4401   }
4402   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4403   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4404   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4405   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4406   case ISD::INSERT_SUBVECTOR:
4407     return lowerINSERT_SUBVECTOR(Op, DAG);
4408   case ISD::INSERT_VECTOR_ELT:
4409     return lowerINSERT_VECTOR_ELT(Op, DAG);
4410   case ISD::EXTRACT_VECTOR_ELT:
4411     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4412   case ISD::VECTOR_SHUFFLE:
4413     return lowerVECTOR_SHUFFLE(Op, DAG);
4414   case ISD::BUILD_VECTOR:
4415     return lowerBUILD_VECTOR(Op, DAG);
4416   case ISD::FP_ROUND:
4417     return lowerFP_ROUND(Op, DAG);
4418   case ISD::TRAP:
4419     return lowerTRAP(Op, DAG);
4420   case ISD::DEBUGTRAP:
4421     return lowerDEBUGTRAP(Op, DAG);
4422   case ISD::FABS:
4423   case ISD::FNEG:
4424   case ISD::FCANONICALIZE:
4425   case ISD::BSWAP:
4426     return splitUnaryVectorOp(Op, DAG);
4427   case ISD::FMINNUM:
4428   case ISD::FMAXNUM:
4429     return lowerFMINNUM_FMAXNUM(Op, DAG);
4430   case ISD::FMA:
4431     return splitTernaryVectorOp(Op, DAG);
4432   case ISD::SHL:
4433   case ISD::SRA:
4434   case ISD::SRL:
4435   case ISD::ADD:
4436   case ISD::SUB:
4437   case ISD::MUL:
4438   case ISD::SMIN:
4439   case ISD::SMAX:
4440   case ISD::UMIN:
4441   case ISD::UMAX:
4442   case ISD::FADD:
4443   case ISD::FMUL:
4444   case ISD::FMINNUM_IEEE:
4445   case ISD::FMAXNUM_IEEE:
4446     return splitBinaryVectorOp(Op, DAG);
4447   case ISD::SMULO:
4448   case ISD::UMULO:
4449     return lowerXMULO(Op, DAG);
4450   case ISD::DYNAMIC_STACKALLOC:
4451     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4452   }
4453   return SDValue();
4454 }
4455 
4456 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4457                                        const SDLoc &DL,
4458                                        SelectionDAG &DAG, bool Unpacked) {
4459   if (!LoadVT.isVector())
4460     return Result;
4461 
4462   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4463     // Truncate to v2i16/v4i16.
4464     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4465 
4466     // Workaround legalizer not scalarizing truncate after vector op
4467     // legalization byt not creating intermediate vector trunc.
4468     SmallVector<SDValue, 4> Elts;
4469     DAG.ExtractVectorElements(Result, Elts);
4470     for (SDValue &Elt : Elts)
4471       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4472 
4473     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4474 
4475     // Bitcast to original type (v2f16/v4f16).
4476     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4477   }
4478 
4479   // Cast back to the original packed type.
4480   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4481 }
4482 
4483 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4484                                               MemSDNode *M,
4485                                               SelectionDAG &DAG,
4486                                               ArrayRef<SDValue> Ops,
4487                                               bool IsIntrinsic) const {
4488   SDLoc DL(M);
4489 
4490   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4491   EVT LoadVT = M->getValueType(0);
4492 
4493   EVT EquivLoadVT = LoadVT;
4494   if (Unpacked && LoadVT.isVector()) {
4495     EquivLoadVT = LoadVT.isVector() ?
4496       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4497                        LoadVT.getVectorNumElements()) : LoadVT;
4498   }
4499 
4500   // Change from v4f16/v2f16 to EquivLoadVT.
4501   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4502 
4503   SDValue Load
4504     = DAG.getMemIntrinsicNode(
4505       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4506       VTList, Ops, M->getMemoryVT(),
4507       M->getMemOperand());
4508   if (!Unpacked) // Just adjusted the opcode.
4509     return Load;
4510 
4511   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4512 
4513   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4514 }
4515 
4516 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4517                                              SelectionDAG &DAG,
4518                                              ArrayRef<SDValue> Ops) const {
4519   SDLoc DL(M);
4520   EVT LoadVT = M->getValueType(0);
4521   EVT EltType = LoadVT.getScalarType();
4522   EVT IntVT = LoadVT.changeTypeToInteger();
4523 
4524   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4525 
4526   unsigned Opc =
4527       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4528 
4529   if (IsD16) {
4530     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4531   }
4532 
4533   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4534   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4535     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4536 
4537   if (isTypeLegal(LoadVT)) {
4538     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4539                                M->getMemOperand(), DAG);
4540   }
4541 
4542   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4543   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4544   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4545                                         M->getMemOperand(), DAG);
4546   return DAG.getMergeValues(
4547       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4548       DL);
4549 }
4550 
4551 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4552                                   SDNode *N, SelectionDAG &DAG) {
4553   EVT VT = N->getValueType(0);
4554   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4555   int CondCode = CD->getSExtValue();
4556   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4557       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4558     return DAG.getUNDEF(VT);
4559 
4560   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4561 
4562   SDValue LHS = N->getOperand(1);
4563   SDValue RHS = N->getOperand(2);
4564 
4565   SDLoc DL(N);
4566 
4567   EVT CmpVT = LHS.getValueType();
4568   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4569     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4570       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4571     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4572     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4573   }
4574 
4575   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4576 
4577   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4578   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4579 
4580   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4581                               DAG.getCondCode(CCOpcode));
4582   if (VT.bitsEq(CCVT))
4583     return SetCC;
4584   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4585 }
4586 
4587 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4588                                   SDNode *N, SelectionDAG &DAG) {
4589   EVT VT = N->getValueType(0);
4590   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4591 
4592   int CondCode = CD->getSExtValue();
4593   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4594       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4595     return DAG.getUNDEF(VT);
4596   }
4597 
4598   SDValue Src0 = N->getOperand(1);
4599   SDValue Src1 = N->getOperand(2);
4600   EVT CmpVT = Src0.getValueType();
4601   SDLoc SL(N);
4602 
4603   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4604     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4605     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4606   }
4607 
4608   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4609   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4610   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4611   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4612   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4613                               Src1, DAG.getCondCode(CCOpcode));
4614   if (VT.bitsEq(CCVT))
4615     return SetCC;
4616   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4617 }
4618 
4619 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4620                                     SelectionDAG &DAG) {
4621   EVT VT = N->getValueType(0);
4622   SDValue Src = N->getOperand(1);
4623   SDLoc SL(N);
4624 
4625   if (Src.getOpcode() == ISD::SETCC) {
4626     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4627     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4628                        Src.getOperand(1), Src.getOperand(2));
4629   }
4630   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4631     // (ballot 0) -> 0
4632     if (Arg->isNullValue())
4633       return DAG.getConstant(0, SL, VT);
4634 
4635     // (ballot 1) -> EXEC/EXEC_LO
4636     if (Arg->isOne()) {
4637       Register Exec;
4638       if (VT.getScalarSizeInBits() == 32)
4639         Exec = AMDGPU::EXEC_LO;
4640       else if (VT.getScalarSizeInBits() == 64)
4641         Exec = AMDGPU::EXEC;
4642       else
4643         return SDValue();
4644 
4645       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4646     }
4647   }
4648 
4649   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4650   // ISD::SETNE)
4651   return DAG.getNode(
4652       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4653       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4654 }
4655 
4656 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4657                                           SmallVectorImpl<SDValue> &Results,
4658                                           SelectionDAG &DAG) const {
4659   switch (N->getOpcode()) {
4660   case ISD::INSERT_VECTOR_ELT: {
4661     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4662       Results.push_back(Res);
4663     return;
4664   }
4665   case ISD::EXTRACT_VECTOR_ELT: {
4666     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4667       Results.push_back(Res);
4668     return;
4669   }
4670   case ISD::INTRINSIC_WO_CHAIN: {
4671     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4672     switch (IID) {
4673     case Intrinsic::amdgcn_cvt_pkrtz: {
4674       SDValue Src0 = N->getOperand(1);
4675       SDValue Src1 = N->getOperand(2);
4676       SDLoc SL(N);
4677       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4678                                 Src0, Src1);
4679       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4680       return;
4681     }
4682     case Intrinsic::amdgcn_cvt_pknorm_i16:
4683     case Intrinsic::amdgcn_cvt_pknorm_u16:
4684     case Intrinsic::amdgcn_cvt_pk_i16:
4685     case Intrinsic::amdgcn_cvt_pk_u16: {
4686       SDValue Src0 = N->getOperand(1);
4687       SDValue Src1 = N->getOperand(2);
4688       SDLoc SL(N);
4689       unsigned Opcode;
4690 
4691       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4692         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4693       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4694         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4695       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4696         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4697       else
4698         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4699 
4700       EVT VT = N->getValueType(0);
4701       if (isTypeLegal(VT))
4702         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4703       else {
4704         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4705         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4706       }
4707       return;
4708     }
4709     }
4710     break;
4711   }
4712   case ISD::INTRINSIC_W_CHAIN: {
4713     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4714       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4715         // FIXME: Hacky
4716         Results.push_back(Res.getOperand(0));
4717         Results.push_back(Res.getOperand(1));
4718       } else {
4719         Results.push_back(Res);
4720         Results.push_back(Res.getValue(1));
4721       }
4722       return;
4723     }
4724 
4725     break;
4726   }
4727   case ISD::SELECT: {
4728     SDLoc SL(N);
4729     EVT VT = N->getValueType(0);
4730     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4731     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4732     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4733 
4734     EVT SelectVT = NewVT;
4735     if (NewVT.bitsLT(MVT::i32)) {
4736       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4737       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4738       SelectVT = MVT::i32;
4739     }
4740 
4741     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4742                                     N->getOperand(0), LHS, RHS);
4743 
4744     if (NewVT != SelectVT)
4745       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4746     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4747     return;
4748   }
4749   case ISD::FNEG: {
4750     if (N->getValueType(0) != MVT::v2f16)
4751       break;
4752 
4753     SDLoc SL(N);
4754     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4755 
4756     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4757                              BC,
4758                              DAG.getConstant(0x80008000, SL, MVT::i32));
4759     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4760     return;
4761   }
4762   case ISD::FABS: {
4763     if (N->getValueType(0) != MVT::v2f16)
4764       break;
4765 
4766     SDLoc SL(N);
4767     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4768 
4769     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4770                              BC,
4771                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4772     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4773     return;
4774   }
4775   default:
4776     break;
4777   }
4778 }
4779 
4780 /// Helper function for LowerBRCOND
4781 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4782 
4783   SDNode *Parent = Value.getNode();
4784   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4785        I != E; ++I) {
4786 
4787     if (I.getUse().get() != Value)
4788       continue;
4789 
4790     if (I->getOpcode() == Opcode)
4791       return *I;
4792   }
4793   return nullptr;
4794 }
4795 
4796 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4797   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4798     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4799     case Intrinsic::amdgcn_if:
4800       return AMDGPUISD::IF;
4801     case Intrinsic::amdgcn_else:
4802       return AMDGPUISD::ELSE;
4803     case Intrinsic::amdgcn_loop:
4804       return AMDGPUISD::LOOP;
4805     case Intrinsic::amdgcn_end_cf:
4806       llvm_unreachable("should not occur");
4807     default:
4808       return 0;
4809     }
4810   }
4811 
4812   // break, if_break, else_break are all only used as inputs to loop, not
4813   // directly as branch conditions.
4814   return 0;
4815 }
4816 
4817 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4818   const Triple &TT = getTargetMachine().getTargetTriple();
4819   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4820           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4821          AMDGPU::shouldEmitConstantsToTextSection(TT);
4822 }
4823 
4824 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4825   // FIXME: Either avoid relying on address space here or change the default
4826   // address space for functions to avoid the explicit check.
4827   return (GV->getValueType()->isFunctionTy() ||
4828           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4829          !shouldEmitFixup(GV) &&
4830          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4831 }
4832 
4833 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4834   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4835 }
4836 
4837 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4838   if (!GV->hasExternalLinkage())
4839     return true;
4840 
4841   const auto OS = getTargetMachine().getTargetTriple().getOS();
4842   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4843 }
4844 
4845 /// This transforms the control flow intrinsics to get the branch destination as
4846 /// last parameter, also switches branch target with BR if the need arise
4847 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4848                                       SelectionDAG &DAG) const {
4849   SDLoc DL(BRCOND);
4850 
4851   SDNode *Intr = BRCOND.getOperand(1).getNode();
4852   SDValue Target = BRCOND.getOperand(2);
4853   SDNode *BR = nullptr;
4854   SDNode *SetCC = nullptr;
4855 
4856   if (Intr->getOpcode() == ISD::SETCC) {
4857     // As long as we negate the condition everything is fine
4858     SetCC = Intr;
4859     Intr = SetCC->getOperand(0).getNode();
4860 
4861   } else {
4862     // Get the target from BR if we don't negate the condition
4863     BR = findUser(BRCOND, ISD::BR);
4864     assert(BR && "brcond missing unconditional branch user");
4865     Target = BR->getOperand(1);
4866   }
4867 
4868   unsigned CFNode = isCFIntrinsic(Intr);
4869   if (CFNode == 0) {
4870     // This is a uniform branch so we don't need to legalize.
4871     return BRCOND;
4872   }
4873 
4874   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4875                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4876 
4877   assert(!SetCC ||
4878         (SetCC->getConstantOperandVal(1) == 1 &&
4879          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4880                                                              ISD::SETNE));
4881 
4882   // operands of the new intrinsic call
4883   SmallVector<SDValue, 4> Ops;
4884   if (HaveChain)
4885     Ops.push_back(BRCOND.getOperand(0));
4886 
4887   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4888   Ops.push_back(Target);
4889 
4890   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4891 
4892   // build the new intrinsic call
4893   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4894 
4895   if (!HaveChain) {
4896     SDValue Ops[] =  {
4897       SDValue(Result, 0),
4898       BRCOND.getOperand(0)
4899     };
4900 
4901     Result = DAG.getMergeValues(Ops, DL).getNode();
4902   }
4903 
4904   if (BR) {
4905     // Give the branch instruction our target
4906     SDValue Ops[] = {
4907       BR->getOperand(0),
4908       BRCOND.getOperand(2)
4909     };
4910     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4911     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4912   }
4913 
4914   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4915 
4916   // Copy the intrinsic results to registers
4917   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4918     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4919     if (!CopyToReg)
4920       continue;
4921 
4922     Chain = DAG.getCopyToReg(
4923       Chain, DL,
4924       CopyToReg->getOperand(1),
4925       SDValue(Result, i - 1),
4926       SDValue());
4927 
4928     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4929   }
4930 
4931   // Remove the old intrinsic from the chain
4932   DAG.ReplaceAllUsesOfValueWith(
4933     SDValue(Intr, Intr->getNumValues() - 1),
4934     Intr->getOperand(0));
4935 
4936   return Chain;
4937 }
4938 
4939 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4940                                           SelectionDAG &DAG) const {
4941   MVT VT = Op.getSimpleValueType();
4942   SDLoc DL(Op);
4943   // Checking the depth
4944   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4945     return DAG.getConstant(0, DL, VT);
4946 
4947   MachineFunction &MF = DAG.getMachineFunction();
4948   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4949   // Check for kernel and shader functions
4950   if (Info->isEntryFunction())
4951     return DAG.getConstant(0, DL, VT);
4952 
4953   MachineFrameInfo &MFI = MF.getFrameInfo();
4954   // There is a call to @llvm.returnaddress in this function
4955   MFI.setReturnAddressIsTaken(true);
4956 
4957   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4958   // Get the return address reg and mark it as an implicit live-in
4959   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4960 
4961   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4962 }
4963 
4964 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4965                                             SDValue Op,
4966                                             const SDLoc &DL,
4967                                             EVT VT) const {
4968   return Op.getValueType().bitsLE(VT) ?
4969       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4970     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4971                 DAG.getTargetConstant(0, DL, MVT::i32));
4972 }
4973 
4974 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4975   assert(Op.getValueType() == MVT::f16 &&
4976          "Do not know how to custom lower FP_ROUND for non-f16 type");
4977 
4978   SDValue Src = Op.getOperand(0);
4979   EVT SrcVT = Src.getValueType();
4980   if (SrcVT != MVT::f64)
4981     return Op;
4982 
4983   SDLoc DL(Op);
4984 
4985   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4986   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4987   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4988 }
4989 
4990 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4991                                                SelectionDAG &DAG) const {
4992   EVT VT = Op.getValueType();
4993   const MachineFunction &MF = DAG.getMachineFunction();
4994   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4995   bool IsIEEEMode = Info->getMode().IEEE;
4996 
4997   // FIXME: Assert during selection that this is only selected for
4998   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4999   // mode functions, but this happens to be OK since it's only done in cases
5000   // where there is known no sNaN.
5001   if (IsIEEEMode)
5002     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5003 
5004   if (VT == MVT::v4f16)
5005     return splitBinaryVectorOp(Op, DAG);
5006   return Op;
5007 }
5008 
5009 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5010   EVT VT = Op.getValueType();
5011   SDLoc SL(Op);
5012   SDValue LHS = Op.getOperand(0);
5013   SDValue RHS = Op.getOperand(1);
5014   bool isSigned = Op.getOpcode() == ISD::SMULO;
5015 
5016   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5017     const APInt &C = RHSC->getAPIntValue();
5018     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5019     if (C.isPowerOf2()) {
5020       // smulo(x, signed_min) is same as umulo(x, signed_min).
5021       bool UseArithShift = isSigned && !C.isMinSignedValue();
5022       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5023       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5024       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5025           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5026                       SL, VT, Result, ShiftAmt),
5027           LHS, ISD::SETNE);
5028       return DAG.getMergeValues({ Result, Overflow }, SL);
5029     }
5030   }
5031 
5032   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5033   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5034                             SL, VT, LHS, RHS);
5035 
5036   SDValue Sign = isSigned
5037     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5038                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5039     : DAG.getConstant(0, SL, VT);
5040   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5041 
5042   return DAG.getMergeValues({ Result, Overflow }, SL);
5043 }
5044 
5045 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5046   SDLoc SL(Op);
5047   SDValue Chain = Op.getOperand(0);
5048 
5049   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5050       !Subtarget->isTrapHandlerEnabled())
5051     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5052 
5053   MachineFunction &MF = DAG.getMachineFunction();
5054   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5055   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
5056   assert(UserSGPR != AMDGPU::NoRegister);
5057   SDValue QueuePtr = CreateLiveInRegister(
5058     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5059   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5060   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5061                                    QueuePtr, SDValue());
5062   SDValue Ops[] = {
5063     ToReg,
5064     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5065     SGPR01,
5066     ToReg.getValue(1)
5067   };
5068   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5069 }
5070 
5071 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5072   SDLoc SL(Op);
5073   SDValue Chain = Op.getOperand(0);
5074   MachineFunction &MF = DAG.getMachineFunction();
5075 
5076   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5077       !Subtarget->isTrapHandlerEnabled()) {
5078     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5079                                      "debugtrap handler not supported",
5080                                      Op.getDebugLoc(),
5081                                      DS_Warning);
5082     LLVMContext &Ctx = MF.getFunction().getContext();
5083     Ctx.diagnose(NoTrap);
5084     return Chain;
5085   }
5086 
5087   SDValue Ops[] = {
5088     Chain,
5089     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5090   };
5091   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5092 }
5093 
5094 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5095                                              SelectionDAG &DAG) const {
5096   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5097   if (Subtarget->hasApertureRegs()) {
5098     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5099         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5100         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5101     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5102         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5103         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5104     unsigned Encoding =
5105         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5106         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5107         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5108 
5109     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5110     SDValue ApertureReg = SDValue(
5111         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5112     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5113     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5114   }
5115 
5116   MachineFunction &MF = DAG.getMachineFunction();
5117   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5118   Register UserSGPR = Info->getQueuePtrUserSGPR();
5119   assert(UserSGPR != AMDGPU::NoRegister);
5120 
5121   SDValue QueuePtr = CreateLiveInRegister(
5122     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5123 
5124   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5125   // private_segment_aperture_base_hi.
5126   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5127 
5128   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
5129 
5130   // TODO: Use custom target PseudoSourceValue.
5131   // TODO: We should use the value from the IR intrinsic call, but it might not
5132   // be available and how do we get it?
5133   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5134   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5135                      MinAlign(64, StructOffset),
5136                      MachineMemOperand::MODereferenceable |
5137                          MachineMemOperand::MOInvariant);
5138 }
5139 
5140 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5141                                              SelectionDAG &DAG) const {
5142   SDLoc SL(Op);
5143   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5144 
5145   SDValue Src = ASC->getOperand(0);
5146   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5147 
5148   const AMDGPUTargetMachine &TM =
5149     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5150 
5151   // flat -> local/private
5152   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5153     unsigned DestAS = ASC->getDestAddressSpace();
5154 
5155     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5156         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5157       unsigned NullVal = TM.getNullPointerValue(DestAS);
5158       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5159       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5160       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5161 
5162       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5163                          NonNull, Ptr, SegmentNullPtr);
5164     }
5165   }
5166 
5167   // local/private -> flat
5168   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5169     unsigned SrcAS = ASC->getSrcAddressSpace();
5170 
5171     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5172         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5173       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5174       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5175 
5176       SDValue NonNull
5177         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5178 
5179       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5180       SDValue CvtPtr
5181         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5182 
5183       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5184                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5185                          FlatNullPtr);
5186     }
5187   }
5188 
5189   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5190       Src.getValueType() == MVT::i64)
5191     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5192 
5193   // global <-> flat are no-ops and never emitted.
5194 
5195   const MachineFunction &MF = DAG.getMachineFunction();
5196   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5197     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5198   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5199 
5200   return DAG.getUNDEF(ASC->getValueType(0));
5201 }
5202 
5203 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5204 // the small vector and inserting them into the big vector. That is better than
5205 // the default expansion of doing it via a stack slot. Even though the use of
5206 // the stack slot would be optimized away afterwards, the stack slot itself
5207 // remains.
5208 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5209                                                 SelectionDAG &DAG) const {
5210   SDValue Vec = Op.getOperand(0);
5211   SDValue Ins = Op.getOperand(1);
5212   SDValue Idx = Op.getOperand(2);
5213   EVT VecVT = Vec.getValueType();
5214   EVT InsVT = Ins.getValueType();
5215   EVT EltVT = VecVT.getVectorElementType();
5216   unsigned InsNumElts = InsVT.getVectorNumElements();
5217   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5218   SDLoc SL(Op);
5219 
5220   for (unsigned I = 0; I != InsNumElts; ++I) {
5221     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5222                               DAG.getConstant(I, SL, MVT::i32));
5223     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5224                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5225   }
5226   return Vec;
5227 }
5228 
5229 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5230                                                  SelectionDAG &DAG) const {
5231   SDValue Vec = Op.getOperand(0);
5232   SDValue InsVal = Op.getOperand(1);
5233   SDValue Idx = Op.getOperand(2);
5234   EVT VecVT = Vec.getValueType();
5235   EVT EltVT = VecVT.getVectorElementType();
5236   unsigned VecSize = VecVT.getSizeInBits();
5237   unsigned EltSize = EltVT.getSizeInBits();
5238 
5239 
5240   assert(VecSize <= 64);
5241 
5242   unsigned NumElts = VecVT.getVectorNumElements();
5243   SDLoc SL(Op);
5244   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5245 
5246   if (NumElts == 4 && EltSize == 16 && KIdx) {
5247     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5248 
5249     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5250                                  DAG.getConstant(0, SL, MVT::i32));
5251     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5252                                  DAG.getConstant(1, SL, MVT::i32));
5253 
5254     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5255     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5256 
5257     unsigned Idx = KIdx->getZExtValue();
5258     bool InsertLo = Idx < 2;
5259     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5260       InsertLo ? LoVec : HiVec,
5261       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5262       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5263 
5264     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5265 
5266     SDValue Concat = InsertLo ?
5267       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5268       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5269 
5270     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5271   }
5272 
5273   if (isa<ConstantSDNode>(Idx))
5274     return SDValue();
5275 
5276   MVT IntVT = MVT::getIntegerVT(VecSize);
5277 
5278   // Avoid stack access for dynamic indexing.
5279   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5280 
5281   // Create a congruent vector with the target value in each element so that
5282   // the required element can be masked and ORed into the target vector.
5283   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5284                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5285 
5286   assert(isPowerOf2_32(EltSize));
5287   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5288 
5289   // Convert vector index to bit-index.
5290   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5291 
5292   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5293   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5294                             DAG.getConstant(0xffff, SL, IntVT),
5295                             ScaledIdx);
5296 
5297   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5298   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5299                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5300 
5301   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5302   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5303 }
5304 
5305 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5306                                                   SelectionDAG &DAG) const {
5307   SDLoc SL(Op);
5308 
5309   EVT ResultVT = Op.getValueType();
5310   SDValue Vec = Op.getOperand(0);
5311   SDValue Idx = Op.getOperand(1);
5312   EVT VecVT = Vec.getValueType();
5313   unsigned VecSize = VecVT.getSizeInBits();
5314   EVT EltVT = VecVT.getVectorElementType();
5315   assert(VecSize <= 64);
5316 
5317   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5318 
5319   // Make sure we do any optimizations that will make it easier to fold
5320   // source modifiers before obscuring it with bit operations.
5321 
5322   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5323   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5324     return Combined;
5325 
5326   unsigned EltSize = EltVT.getSizeInBits();
5327   assert(isPowerOf2_32(EltSize));
5328 
5329   MVT IntVT = MVT::getIntegerVT(VecSize);
5330   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5331 
5332   // Convert vector index to bit-index (* EltSize)
5333   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5334 
5335   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5336   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5337 
5338   if (ResultVT == MVT::f16) {
5339     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5340     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5341   }
5342 
5343   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5344 }
5345 
5346 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5347   assert(Elt % 2 == 0);
5348   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5349 }
5350 
5351 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5352                                               SelectionDAG &DAG) const {
5353   SDLoc SL(Op);
5354   EVT ResultVT = Op.getValueType();
5355   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5356 
5357   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5358   EVT EltVT = PackVT.getVectorElementType();
5359   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5360 
5361   // vector_shuffle <0,1,6,7> lhs, rhs
5362   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5363   //
5364   // vector_shuffle <6,7,2,3> lhs, rhs
5365   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5366   //
5367   // vector_shuffle <6,7,0,1> lhs, rhs
5368   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5369 
5370   // Avoid scalarizing when both halves are reading from consecutive elements.
5371   SmallVector<SDValue, 4> Pieces;
5372   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5373     if (elementPairIsContiguous(SVN->getMask(), I)) {
5374       const int Idx = SVN->getMaskElt(I);
5375       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5376       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5377       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5378                                     PackVT, SVN->getOperand(VecIdx),
5379                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5380       Pieces.push_back(SubVec);
5381     } else {
5382       const int Idx0 = SVN->getMaskElt(I);
5383       const int Idx1 = SVN->getMaskElt(I + 1);
5384       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5385       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5386       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5387       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5388 
5389       SDValue Vec0 = SVN->getOperand(VecIdx0);
5390       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5391                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5392 
5393       SDValue Vec1 = SVN->getOperand(VecIdx1);
5394       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5395                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5396       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5397     }
5398   }
5399 
5400   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5401 }
5402 
5403 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5404                                             SelectionDAG &DAG) const {
5405   SDLoc SL(Op);
5406   EVT VT = Op.getValueType();
5407 
5408   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5409     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5410 
5411     // Turn into pair of packed build_vectors.
5412     // TODO: Special case for constants that can be materialized with s_mov_b64.
5413     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5414                                     { Op.getOperand(0), Op.getOperand(1) });
5415     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5416                                     { Op.getOperand(2), Op.getOperand(3) });
5417 
5418     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5419     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5420 
5421     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5422     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5423   }
5424 
5425   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5426   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5427 
5428   SDValue Lo = Op.getOperand(0);
5429   SDValue Hi = Op.getOperand(1);
5430 
5431   // Avoid adding defined bits with the zero_extend.
5432   if (Hi.isUndef()) {
5433     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5434     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5435     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5436   }
5437 
5438   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5439   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5440 
5441   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5442                               DAG.getConstant(16, SL, MVT::i32));
5443   if (Lo.isUndef())
5444     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5445 
5446   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5447   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5448 
5449   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5450   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5451 }
5452 
5453 bool
5454 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5455   // We can fold offsets for anything that doesn't require a GOT relocation.
5456   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5457           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5458           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5459          !shouldEmitGOTReloc(GA->getGlobal());
5460 }
5461 
5462 static SDValue
5463 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5464                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5465                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5466   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5467   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5468   // lowered to the following code sequence:
5469   //
5470   // For constant address space:
5471   //   s_getpc_b64 s[0:1]
5472   //   s_add_u32 s0, s0, $symbol
5473   //   s_addc_u32 s1, s1, 0
5474   //
5475   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5476   //   a fixup or relocation is emitted to replace $symbol with a literal
5477   //   constant, which is a pc-relative offset from the encoding of the $symbol
5478   //   operand to the global variable.
5479   //
5480   // For global address space:
5481   //   s_getpc_b64 s[0:1]
5482   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5483   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5484   //
5485   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5486   //   fixups or relocations are emitted to replace $symbol@*@lo and
5487   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5488   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5489   //   operand to the global variable.
5490   //
5491   // What we want here is an offset from the value returned by s_getpc
5492   // (which is the address of the s_add_u32 instruction) to the global
5493   // variable, but since the encoding of $symbol starts 4 bytes after the start
5494   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5495   // small. This requires us to add 4 to the global variable offset in order to
5496   // compute the correct address.
5497   SDValue PtrLo =
5498       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5499   SDValue PtrHi;
5500   if (GAFlags == SIInstrInfo::MO_NONE) {
5501     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5502   } else {
5503     PtrHi =
5504         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5505   }
5506   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5507 }
5508 
5509 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5510                                              SDValue Op,
5511                                              SelectionDAG &DAG) const {
5512   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5513   const GlobalValue *GV = GSD->getGlobal();
5514   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5515        shouldUseLDSConstAddress(GV)) ||
5516       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5517       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5518     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5519 
5520   SDLoc DL(GSD);
5521   EVT PtrVT = Op.getValueType();
5522 
5523   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5524     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5525                                             SIInstrInfo::MO_ABS32_LO);
5526     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5527   }
5528 
5529   if (shouldEmitFixup(GV))
5530     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5531   else if (shouldEmitPCReloc(GV))
5532     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5533                                    SIInstrInfo::MO_REL32);
5534 
5535   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5536                                             SIInstrInfo::MO_GOTPCREL32);
5537 
5538   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5539   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5540   const DataLayout &DataLayout = DAG.getDataLayout();
5541   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5542   MachinePointerInfo PtrInfo
5543     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5544 
5545   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5546                      MachineMemOperand::MODereferenceable |
5547                          MachineMemOperand::MOInvariant);
5548 }
5549 
5550 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5551                                    const SDLoc &DL, SDValue V) const {
5552   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5553   // the destination register.
5554   //
5555   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5556   // so we will end up with redundant moves to m0.
5557   //
5558   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5559 
5560   // A Null SDValue creates a glue result.
5561   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5562                                   V, Chain);
5563   return SDValue(M0, 0);
5564 }
5565 
5566 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5567                                                  SDValue Op,
5568                                                  MVT VT,
5569                                                  unsigned Offset) const {
5570   SDLoc SL(Op);
5571   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5572                                            DAG.getEntryNode(), Offset, 4, false);
5573   // The local size values will have the hi 16-bits as zero.
5574   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5575                      DAG.getValueType(VT));
5576 }
5577 
5578 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5579                                         EVT VT) {
5580   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5581                                       "non-hsa intrinsic with hsa target",
5582                                       DL.getDebugLoc());
5583   DAG.getContext()->diagnose(BadIntrin);
5584   return DAG.getUNDEF(VT);
5585 }
5586 
5587 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5588                                          EVT VT) {
5589   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5590                                       "intrinsic not supported on subtarget",
5591                                       DL.getDebugLoc());
5592   DAG.getContext()->diagnose(BadIntrin);
5593   return DAG.getUNDEF(VT);
5594 }
5595 
5596 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5597                                     ArrayRef<SDValue> Elts) {
5598   assert(!Elts.empty());
5599   MVT Type;
5600   unsigned NumElts;
5601 
5602   if (Elts.size() == 1) {
5603     Type = MVT::f32;
5604     NumElts = 1;
5605   } else if (Elts.size() == 2) {
5606     Type = MVT::v2f32;
5607     NumElts = 2;
5608   } else if (Elts.size() == 3) {
5609     Type = MVT::v3f32;
5610     NumElts = 3;
5611   } else if (Elts.size() <= 4) {
5612     Type = MVT::v4f32;
5613     NumElts = 4;
5614   } else if (Elts.size() <= 8) {
5615     Type = MVT::v8f32;
5616     NumElts = 8;
5617   } else {
5618     assert(Elts.size() <= 16);
5619     Type = MVT::v16f32;
5620     NumElts = 16;
5621   }
5622 
5623   SmallVector<SDValue, 16> VecElts(NumElts);
5624   for (unsigned i = 0; i < Elts.size(); ++i) {
5625     SDValue Elt = Elts[i];
5626     if (Elt.getValueType() != MVT::f32)
5627       Elt = DAG.getBitcast(MVT::f32, Elt);
5628     VecElts[i] = Elt;
5629   }
5630   for (unsigned i = Elts.size(); i < NumElts; ++i)
5631     VecElts[i] = DAG.getUNDEF(MVT::f32);
5632 
5633   if (NumElts == 1)
5634     return VecElts[0];
5635   return DAG.getBuildVector(Type, DL, VecElts);
5636 }
5637 
5638 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5639                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5640   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5641 
5642   uint64_t Value = CachePolicyConst->getZExtValue();
5643   SDLoc DL(CachePolicy);
5644   if (GLC) {
5645     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5646     Value &= ~(uint64_t)0x1;
5647   }
5648   if (SLC) {
5649     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5650     Value &= ~(uint64_t)0x2;
5651   }
5652   if (DLC) {
5653     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5654     Value &= ~(uint64_t)0x4;
5655   }
5656 
5657   return Value == 0;
5658 }
5659 
5660 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5661                               SDValue Src, int ExtraElts) {
5662   EVT SrcVT = Src.getValueType();
5663 
5664   SmallVector<SDValue, 8> Elts;
5665 
5666   if (SrcVT.isVector())
5667     DAG.ExtractVectorElements(Src, Elts);
5668   else
5669     Elts.push_back(Src);
5670 
5671   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5672   while (ExtraElts--)
5673     Elts.push_back(Undef);
5674 
5675   return DAG.getBuildVector(CastVT, DL, Elts);
5676 }
5677 
5678 // Re-construct the required return value for a image load intrinsic.
5679 // This is more complicated due to the optional use TexFailCtrl which means the required
5680 // return type is an aggregate
5681 static SDValue constructRetValue(SelectionDAG &DAG,
5682                                  MachineSDNode *Result,
5683                                  ArrayRef<EVT> ResultTypes,
5684                                  bool IsTexFail, bool Unpacked, bool IsD16,
5685                                  int DMaskPop, int NumVDataDwords,
5686                                  const SDLoc &DL, LLVMContext &Context) {
5687   // Determine the required return type. This is the same regardless of IsTexFail flag
5688   EVT ReqRetVT = ResultTypes[0];
5689   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5690   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5691     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5692 
5693   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5694     DMaskPop : (DMaskPop + 1) / 2;
5695 
5696   MVT DataDwordVT = NumDataDwords == 1 ?
5697     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5698 
5699   MVT MaskPopVT = MaskPopDwords == 1 ?
5700     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5701 
5702   SDValue Data(Result, 0);
5703   SDValue TexFail;
5704 
5705   if (IsTexFail) {
5706     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5707     if (MaskPopVT.isVector()) {
5708       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5709                          SDValue(Result, 0), ZeroIdx);
5710     } else {
5711       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5712                          SDValue(Result, 0), ZeroIdx);
5713     }
5714 
5715     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5716                           SDValue(Result, 0),
5717                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5718   }
5719 
5720   if (DataDwordVT.isVector())
5721     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5722                           NumDataDwords - MaskPopDwords);
5723 
5724   if (IsD16)
5725     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5726 
5727   if (!ReqRetVT.isVector())
5728     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5729 
5730   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5731 
5732   if (TexFail)
5733     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5734 
5735   if (Result->getNumValues() == 1)
5736     return Data;
5737 
5738   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5739 }
5740 
5741 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5742                          SDValue *LWE, bool &IsTexFail) {
5743   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5744 
5745   uint64_t Value = TexFailCtrlConst->getZExtValue();
5746   if (Value) {
5747     IsTexFail = true;
5748   }
5749 
5750   SDLoc DL(TexFailCtrlConst);
5751   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5752   Value &= ~(uint64_t)0x1;
5753   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5754   Value &= ~(uint64_t)0x2;
5755 
5756   return Value == 0;
5757 }
5758 
5759 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5760                                         MVT PackVectorVT,
5761                                         SmallVectorImpl<SDValue> &PackedAddrs,
5762                                         unsigned DimIdx, unsigned EndIdx,
5763                                         unsigned NumGradients) {
5764   SDLoc DL(Op);
5765   for (unsigned I = DimIdx; I < EndIdx; I++) {
5766     SDValue Addr = Op.getOperand(I);
5767 
5768     // Gradients are packed with undef for each coordinate.
5769     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5770     // 1D: undef,dx/dh; undef,dx/dv
5771     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5772     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5773     if (((I + 1) >= EndIdx) ||
5774         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5775                                          I == DimIdx + NumGradients - 1))) {
5776       if (Addr.getValueType() != MVT::i16)
5777         Addr = DAG.getBitcast(MVT::i16, Addr);
5778       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5779     } else {
5780       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5781       I++;
5782     }
5783     Addr = DAG.getBitcast(MVT::f32, Addr);
5784     PackedAddrs.push_back(Addr);
5785   }
5786 }
5787 
5788 SDValue SITargetLowering::lowerImage(SDValue Op,
5789                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5790                                      SelectionDAG &DAG) const {
5791   SDLoc DL(Op);
5792   MachineFunction &MF = DAG.getMachineFunction();
5793   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5794   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5795       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5796   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5797   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5798       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5799   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5800       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5801   unsigned IntrOpcode = Intr->BaseOpcode;
5802   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5803 
5804   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5805   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5806   bool IsD16 = false;
5807   bool IsG16 = false;
5808   bool IsA16 = false;
5809   SDValue VData;
5810   int NumVDataDwords;
5811   bool AdjustRetType = false;
5812 
5813   unsigned AddrIdx; // Index of first address argument
5814   unsigned DMask;
5815   unsigned DMaskLanes = 0;
5816 
5817   if (BaseOpcode->Atomic) {
5818     VData = Op.getOperand(2);
5819 
5820     bool Is64Bit = VData.getValueType() == MVT::i64;
5821     if (BaseOpcode->AtomicX2) {
5822       SDValue VData2 = Op.getOperand(3);
5823       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5824                                  {VData, VData2});
5825       if (Is64Bit)
5826         VData = DAG.getBitcast(MVT::v4i32, VData);
5827 
5828       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5829       DMask = Is64Bit ? 0xf : 0x3;
5830       NumVDataDwords = Is64Bit ? 4 : 2;
5831       AddrIdx = 4;
5832     } else {
5833       DMask = Is64Bit ? 0x3 : 0x1;
5834       NumVDataDwords = Is64Bit ? 2 : 1;
5835       AddrIdx = 3;
5836     }
5837   } else {
5838     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5839     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5840     DMask = DMaskConst->getZExtValue();
5841     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5842 
5843     if (BaseOpcode->Store) {
5844       VData = Op.getOperand(2);
5845 
5846       MVT StoreVT = VData.getSimpleValueType();
5847       if (StoreVT.getScalarType() == MVT::f16) {
5848         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5849           return Op; // D16 is unsupported for this instruction
5850 
5851         IsD16 = true;
5852         VData = handleD16VData(VData, DAG);
5853       }
5854 
5855       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5856     } else {
5857       // Work out the num dwords based on the dmask popcount and underlying type
5858       // and whether packing is supported.
5859       MVT LoadVT = ResultTypes[0].getSimpleVT();
5860       if (LoadVT.getScalarType() == MVT::f16) {
5861         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5862           return Op; // D16 is unsupported for this instruction
5863 
5864         IsD16 = true;
5865       }
5866 
5867       // Confirm that the return type is large enough for the dmask specified
5868       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5869           (!LoadVT.isVector() && DMaskLanes > 1))
5870           return Op;
5871 
5872       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5873         NumVDataDwords = (DMaskLanes + 1) / 2;
5874       else
5875         NumVDataDwords = DMaskLanes;
5876 
5877       AdjustRetType = true;
5878     }
5879 
5880     AddrIdx = DMaskIdx + 1;
5881   }
5882 
5883   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5884   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5885   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5886   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5887                        NumCoords + NumLCM;
5888   unsigned NumMIVAddrs = NumVAddrs;
5889 
5890   SmallVector<SDValue, 4> VAddrs;
5891 
5892   // Optimize _L to _LZ when _L is zero
5893   if (LZMappingInfo) {
5894     if (auto ConstantLod =
5895          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5896       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5897         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5898         NumMIVAddrs--;               // remove 'lod'
5899       }
5900     }
5901   }
5902 
5903   // Optimize _mip away, when 'lod' is zero
5904   if (MIPMappingInfo) {
5905     if (auto ConstantLod =
5906          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5907       if (ConstantLod->isNullValue()) {
5908         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5909         NumMIVAddrs--;               // remove 'lod'
5910       }
5911     }
5912   }
5913 
5914   // Push back extra arguments.
5915   for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++)
5916     VAddrs.push_back(Op.getOperand(AddrIdx + I));
5917 
5918   // Check for 16 bit addresses or derivatives and pack if true.
5919   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5920   unsigned CoordIdx = DimIdx + NumGradients;
5921   unsigned CoordsEnd = AddrIdx + NumMIVAddrs;
5922 
5923   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5924   MVT VAddrScalarVT = VAddrVT.getScalarType();
5925   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5926   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
5927 
5928   VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType();
5929   VAddrScalarVT = VAddrVT.getScalarType();
5930   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
5931   if (IsA16 || IsG16) {
5932     if (IsA16) {
5933       if (!ST->hasA16()) {
5934         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
5935                              "support 16 bit addresses\n");
5936         return Op;
5937       }
5938       if (!IsG16) {
5939         LLVM_DEBUG(
5940             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
5941                       "need 16 bit derivatives but got 32 bit derivatives\n");
5942         return Op;
5943       }
5944     } else if (!ST->hasG16()) {
5945       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
5946                            "support 16 bit derivatives\n");
5947       return Op;
5948     }
5949 
5950     if (BaseOpcode->Gradients && !IsA16) {
5951       if (!ST->hasG16()) {
5952         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
5953                              "support 16 bit derivatives\n");
5954         return Op;
5955       }
5956       // Activate g16
5957       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
5958           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
5959       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
5960     }
5961 
5962     // Don't compress addresses for G16
5963     const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx;
5964     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx,
5965                                 PackEndIdx, NumGradients);
5966 
5967     if (!IsA16) {
5968       // Add uncompressed address
5969       for (unsigned I = CoordIdx; I < CoordsEnd; I++)
5970         VAddrs.push_back(Op.getOperand(I));
5971     }
5972   } else {
5973     for (unsigned I = DimIdx; I < CoordsEnd; I++)
5974       VAddrs.push_back(Op.getOperand(I));
5975   }
5976 
5977   // If the register allocator cannot place the address registers contiguously
5978   // without introducing moves, then using the non-sequential address encoding
5979   // is always preferable, since it saves VALU instructions and is usually a
5980   // wash in terms of code size or even better.
5981   //
5982   // However, we currently have no way of hinting to the register allocator that
5983   // MIMG addresses should be placed contiguously when it is possible to do so,
5984   // so force non-NSA for the common 2-address case as a heuristic.
5985   //
5986   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5987   // allocation when possible.
5988   bool UseNSA =
5989       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5990   SDValue VAddr;
5991   if (!UseNSA)
5992     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5993 
5994   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5995   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5996   unsigned CtrlIdx; // Index of texfailctrl argument
5997   SDValue Unorm;
5998   if (!BaseOpcode->Sampler) {
5999     Unorm = True;
6000     CtrlIdx = AddrIdx + NumVAddrs + 1;
6001   } else {
6002     auto UnormConst =
6003         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
6004 
6005     Unorm = UnormConst->getZExtValue() ? True : False;
6006     CtrlIdx = AddrIdx + NumVAddrs + 3;
6007   }
6008 
6009   SDValue TFE;
6010   SDValue LWE;
6011   SDValue TexFail = Op.getOperand(CtrlIdx);
6012   bool IsTexFail = false;
6013   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6014     return Op;
6015 
6016   if (IsTexFail) {
6017     if (!DMaskLanes) {
6018       // Expecting to get an error flag since TFC is on - and dmask is 0
6019       // Force dmask to be at least 1 otherwise the instruction will fail
6020       DMask = 0x1;
6021       DMaskLanes = 1;
6022       NumVDataDwords = 1;
6023     }
6024     NumVDataDwords += 1;
6025     AdjustRetType = true;
6026   }
6027 
6028   // Has something earlier tagged that the return type needs adjusting
6029   // This happens if the instruction is a load or has set TexFailCtrl flags
6030   if (AdjustRetType) {
6031     // NumVDataDwords reflects the true number of dwords required in the return type
6032     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6033       // This is a no-op load. This can be eliminated
6034       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6035       if (isa<MemSDNode>(Op))
6036         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6037       return Undef;
6038     }
6039 
6040     EVT NewVT = NumVDataDwords > 1 ?
6041                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6042                 : MVT::i32;
6043 
6044     ResultTypes[0] = NewVT;
6045     if (ResultTypes.size() == 3) {
6046       // Original result was aggregate type used for TexFailCtrl results
6047       // The actual instruction returns as a vector type which has now been
6048       // created. Remove the aggregate result.
6049       ResultTypes.erase(&ResultTypes[1]);
6050     }
6051   }
6052 
6053   SDValue GLC;
6054   SDValue SLC;
6055   SDValue DLC;
6056   if (BaseOpcode->Atomic) {
6057     GLC = True; // TODO no-return optimization
6058     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
6059                           IsGFX10 ? &DLC : nullptr))
6060       return Op;
6061   } else {
6062     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
6063                           IsGFX10 ? &DLC : nullptr))
6064       return Op;
6065   }
6066 
6067   SmallVector<SDValue, 26> Ops;
6068   if (BaseOpcode->Store || BaseOpcode->Atomic)
6069     Ops.push_back(VData); // vdata
6070   if (UseNSA) {
6071     for (const SDValue &Addr : VAddrs)
6072       Ops.push_back(Addr);
6073   } else {
6074     Ops.push_back(VAddr);
6075   }
6076   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
6077   if (BaseOpcode->Sampler)
6078     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
6079   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6080   if (IsGFX10)
6081     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6082   Ops.push_back(Unorm);
6083   if (IsGFX10)
6084     Ops.push_back(DLC);
6085   Ops.push_back(GLC);
6086   Ops.push_back(SLC);
6087   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6088                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6089   if (IsGFX10)
6090     Ops.push_back(IsA16 ? True : False);
6091   Ops.push_back(TFE);
6092   Ops.push_back(LWE);
6093   if (!IsGFX10)
6094     Ops.push_back(DimInfo->DA ? True : False);
6095   if (BaseOpcode->HasD16)
6096     Ops.push_back(IsD16 ? True : False);
6097   if (isa<MemSDNode>(Op))
6098     Ops.push_back(Op.getOperand(0)); // chain
6099 
6100   int NumVAddrDwords =
6101       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6102   int Opcode = -1;
6103 
6104   if (IsGFX10) {
6105     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6106                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6107                                           : AMDGPU::MIMGEncGfx10Default,
6108                                    NumVDataDwords, NumVAddrDwords);
6109   } else {
6110     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6111       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6112                                      NumVDataDwords, NumVAddrDwords);
6113     if (Opcode == -1)
6114       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6115                                      NumVDataDwords, NumVAddrDwords);
6116   }
6117   assert(Opcode != -1);
6118 
6119   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6120   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6121     MachineMemOperand *MemRef = MemOp->getMemOperand();
6122     DAG.setNodeMemRefs(NewNode, {MemRef});
6123   }
6124 
6125   if (BaseOpcode->AtomicX2) {
6126     SmallVector<SDValue, 1> Elt;
6127     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6128     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6129   } else if (!BaseOpcode->Store) {
6130     return constructRetValue(DAG, NewNode,
6131                              OrigResultTypes, IsTexFail,
6132                              Subtarget->hasUnpackedD16VMem(), IsD16,
6133                              DMaskLanes, NumVDataDwords, DL,
6134                              *DAG.getContext());
6135   }
6136 
6137   return SDValue(NewNode, 0);
6138 }
6139 
6140 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6141                                        SDValue Offset, SDValue CachePolicy,
6142                                        SelectionDAG &DAG) const {
6143   MachineFunction &MF = DAG.getMachineFunction();
6144 
6145   const DataLayout &DataLayout = DAG.getDataLayout();
6146   Align Alignment =
6147       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6148 
6149   MachineMemOperand *MMO = MF.getMachineMemOperand(
6150       MachinePointerInfo(),
6151       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6152           MachineMemOperand::MOInvariant,
6153       VT.getStoreSize(), Alignment);
6154 
6155   if (!Offset->isDivergent()) {
6156     SDValue Ops[] = {
6157         Rsrc,
6158         Offset, // Offset
6159         CachePolicy
6160     };
6161 
6162     // Widen vec3 load to vec4.
6163     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6164       EVT WidenedVT =
6165           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6166       auto WidenedOp = DAG.getMemIntrinsicNode(
6167           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6168           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6169       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6170                                    DAG.getVectorIdxConstant(0, DL));
6171       return Subvector;
6172     }
6173 
6174     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6175                                    DAG.getVTList(VT), Ops, VT, MMO);
6176   }
6177 
6178   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6179   // assume that the buffer is unswizzled.
6180   SmallVector<SDValue, 4> Loads;
6181   unsigned NumLoads = 1;
6182   MVT LoadVT = VT.getSimpleVT();
6183   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6184   assert((LoadVT.getScalarType() == MVT::i32 ||
6185           LoadVT.getScalarType() == MVT::f32));
6186 
6187   if (NumElts == 8 || NumElts == 16) {
6188     NumLoads = NumElts / 4;
6189     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6190   }
6191 
6192   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6193   SDValue Ops[] = {
6194       DAG.getEntryNode(),                               // Chain
6195       Rsrc,                                             // rsrc
6196       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6197       {},                                               // voffset
6198       {},                                               // soffset
6199       {},                                               // offset
6200       CachePolicy,                                      // cachepolicy
6201       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6202   };
6203 
6204   // Use the alignment to ensure that the required offsets will fit into the
6205   // immediate offsets.
6206   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
6207 
6208   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6209   for (unsigned i = 0; i < NumLoads; ++i) {
6210     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6211     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6212                                         LoadVT, MMO, DAG));
6213   }
6214 
6215   if (NumElts == 8 || NumElts == 16)
6216     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6217 
6218   return Loads[0];
6219 }
6220 
6221 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6222                                                   SelectionDAG &DAG) const {
6223   MachineFunction &MF = DAG.getMachineFunction();
6224   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6225 
6226   EVT VT = Op.getValueType();
6227   SDLoc DL(Op);
6228   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6229 
6230   // TODO: Should this propagate fast-math-flags?
6231 
6232   switch (IntrinsicID) {
6233   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6234     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6235       return emitNonHSAIntrinsicError(DAG, DL, VT);
6236     return getPreloadedValue(DAG, *MFI, VT,
6237                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6238   }
6239   case Intrinsic::amdgcn_dispatch_ptr:
6240   case Intrinsic::amdgcn_queue_ptr: {
6241     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6242       DiagnosticInfoUnsupported BadIntrin(
6243           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6244           DL.getDebugLoc());
6245       DAG.getContext()->diagnose(BadIntrin);
6246       return DAG.getUNDEF(VT);
6247     }
6248 
6249     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6250       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6251     return getPreloadedValue(DAG, *MFI, VT, RegID);
6252   }
6253   case Intrinsic::amdgcn_implicitarg_ptr: {
6254     if (MFI->isEntryFunction())
6255       return getImplicitArgPtr(DAG, DL);
6256     return getPreloadedValue(DAG, *MFI, VT,
6257                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6258   }
6259   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6260     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6261       // This only makes sense to call in a kernel, so just lower to null.
6262       return DAG.getConstant(0, DL, VT);
6263     }
6264 
6265     return getPreloadedValue(DAG, *MFI, VT,
6266                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6267   }
6268   case Intrinsic::amdgcn_dispatch_id: {
6269     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6270   }
6271   case Intrinsic::amdgcn_rcp:
6272     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6273   case Intrinsic::amdgcn_rsq:
6274     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6275   case Intrinsic::amdgcn_rsq_legacy:
6276     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6277       return emitRemovedIntrinsicError(DAG, DL, VT);
6278     return SDValue();
6279   case Intrinsic::amdgcn_rcp_legacy:
6280     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6281       return emitRemovedIntrinsicError(DAG, DL, VT);
6282     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6283   case Intrinsic::amdgcn_rsq_clamp: {
6284     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6285       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6286 
6287     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6288     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6289     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6290 
6291     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6292     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6293                               DAG.getConstantFP(Max, DL, VT));
6294     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6295                        DAG.getConstantFP(Min, DL, VT));
6296   }
6297   case Intrinsic::r600_read_ngroups_x:
6298     if (Subtarget->isAmdHsaOS())
6299       return emitNonHSAIntrinsicError(DAG, DL, VT);
6300 
6301     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6302                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
6303   case Intrinsic::r600_read_ngroups_y:
6304     if (Subtarget->isAmdHsaOS())
6305       return emitNonHSAIntrinsicError(DAG, DL, VT);
6306 
6307     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6308                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
6309   case Intrinsic::r600_read_ngroups_z:
6310     if (Subtarget->isAmdHsaOS())
6311       return emitNonHSAIntrinsicError(DAG, DL, VT);
6312 
6313     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6314                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
6315   case Intrinsic::r600_read_global_size_x:
6316     if (Subtarget->isAmdHsaOS())
6317       return emitNonHSAIntrinsicError(DAG, DL, VT);
6318 
6319     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6320                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
6321   case Intrinsic::r600_read_global_size_y:
6322     if (Subtarget->isAmdHsaOS())
6323       return emitNonHSAIntrinsicError(DAG, DL, VT);
6324 
6325     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6326                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
6327   case Intrinsic::r600_read_global_size_z:
6328     if (Subtarget->isAmdHsaOS())
6329       return emitNonHSAIntrinsicError(DAG, DL, VT);
6330 
6331     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6332                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
6333   case Intrinsic::r600_read_local_size_x:
6334     if (Subtarget->isAmdHsaOS())
6335       return emitNonHSAIntrinsicError(DAG, DL, VT);
6336 
6337     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6338                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6339   case Intrinsic::r600_read_local_size_y:
6340     if (Subtarget->isAmdHsaOS())
6341       return emitNonHSAIntrinsicError(DAG, DL, VT);
6342 
6343     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6344                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6345   case Intrinsic::r600_read_local_size_z:
6346     if (Subtarget->isAmdHsaOS())
6347       return emitNonHSAIntrinsicError(DAG, DL, VT);
6348 
6349     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6350                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6351   case Intrinsic::amdgcn_workgroup_id_x:
6352     return getPreloadedValue(DAG, *MFI, VT,
6353                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6354   case Intrinsic::amdgcn_workgroup_id_y:
6355     return getPreloadedValue(DAG, *MFI, VT,
6356                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6357   case Intrinsic::amdgcn_workgroup_id_z:
6358     return getPreloadedValue(DAG, *MFI, VT,
6359                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6360   case Intrinsic::amdgcn_workitem_id_x:
6361     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6362                           SDLoc(DAG.getEntryNode()),
6363                           MFI->getArgInfo().WorkItemIDX);
6364   case Intrinsic::amdgcn_workitem_id_y:
6365     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6366                           SDLoc(DAG.getEntryNode()),
6367                           MFI->getArgInfo().WorkItemIDY);
6368   case Intrinsic::amdgcn_workitem_id_z:
6369     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6370                           SDLoc(DAG.getEntryNode()),
6371                           MFI->getArgInfo().WorkItemIDZ);
6372   case Intrinsic::amdgcn_wavefrontsize:
6373     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6374                            SDLoc(Op), MVT::i32);
6375   case Intrinsic::amdgcn_s_buffer_load: {
6376     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6377     SDValue GLC;
6378     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6379     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6380                           IsGFX10 ? &DLC : nullptr))
6381       return Op;
6382     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6383                         DAG);
6384   }
6385   case Intrinsic::amdgcn_fdiv_fast:
6386     return lowerFDIV_FAST(Op, DAG);
6387   case Intrinsic::amdgcn_sin:
6388     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6389 
6390   case Intrinsic::amdgcn_cos:
6391     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6392 
6393   case Intrinsic::amdgcn_mul_u24:
6394     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6395   case Intrinsic::amdgcn_mul_i24:
6396     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6397 
6398   case Intrinsic::amdgcn_log_clamp: {
6399     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6400       return SDValue();
6401 
6402     DiagnosticInfoUnsupported BadIntrin(
6403       MF.getFunction(), "intrinsic not supported on subtarget",
6404       DL.getDebugLoc());
6405       DAG.getContext()->diagnose(BadIntrin);
6406       return DAG.getUNDEF(VT);
6407   }
6408   case Intrinsic::amdgcn_ldexp:
6409     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6410                        Op.getOperand(1), Op.getOperand(2));
6411 
6412   case Intrinsic::amdgcn_fract:
6413     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6414 
6415   case Intrinsic::amdgcn_class:
6416     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6417                        Op.getOperand(1), Op.getOperand(2));
6418   case Intrinsic::amdgcn_div_fmas:
6419     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6420                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6421                        Op.getOperand(4));
6422 
6423   case Intrinsic::amdgcn_div_fixup:
6424     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6425                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6426 
6427   case Intrinsic::amdgcn_div_scale: {
6428     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6429 
6430     // Translate to the operands expected by the machine instruction. The
6431     // first parameter must be the same as the first instruction.
6432     SDValue Numerator = Op.getOperand(1);
6433     SDValue Denominator = Op.getOperand(2);
6434 
6435     // Note this order is opposite of the machine instruction's operations,
6436     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6437     // intrinsic has the numerator as the first operand to match a normal
6438     // division operation.
6439 
6440     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6441 
6442     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6443                        Denominator, Numerator);
6444   }
6445   case Intrinsic::amdgcn_icmp: {
6446     // There is a Pat that handles this variant, so return it as-is.
6447     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6448         Op.getConstantOperandVal(2) == 0 &&
6449         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6450       return Op;
6451     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6452   }
6453   case Intrinsic::amdgcn_fcmp: {
6454     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6455   }
6456   case Intrinsic::amdgcn_ballot:
6457     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6458   case Intrinsic::amdgcn_fmed3:
6459     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6460                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6461   case Intrinsic::amdgcn_fdot2:
6462     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6463                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6464                        Op.getOperand(4));
6465   case Intrinsic::amdgcn_fmul_legacy:
6466     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6467                        Op.getOperand(1), Op.getOperand(2));
6468   case Intrinsic::amdgcn_sffbh:
6469     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6470   case Intrinsic::amdgcn_sbfe:
6471     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6472                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6473   case Intrinsic::amdgcn_ubfe:
6474     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6475                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6476   case Intrinsic::amdgcn_cvt_pkrtz:
6477   case Intrinsic::amdgcn_cvt_pknorm_i16:
6478   case Intrinsic::amdgcn_cvt_pknorm_u16:
6479   case Intrinsic::amdgcn_cvt_pk_i16:
6480   case Intrinsic::amdgcn_cvt_pk_u16: {
6481     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6482     EVT VT = Op.getValueType();
6483     unsigned Opcode;
6484 
6485     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6486       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6487     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6488       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6489     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6490       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6491     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6492       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6493     else
6494       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6495 
6496     if (isTypeLegal(VT))
6497       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6498 
6499     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6500                                Op.getOperand(1), Op.getOperand(2));
6501     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6502   }
6503   case Intrinsic::amdgcn_fmad_ftz:
6504     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6505                        Op.getOperand(2), Op.getOperand(3));
6506 
6507   case Intrinsic::amdgcn_if_break:
6508     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6509                                       Op->getOperand(1), Op->getOperand(2)), 0);
6510 
6511   case Intrinsic::amdgcn_groupstaticsize: {
6512     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6513     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6514       return Op;
6515 
6516     const Module *M = MF.getFunction().getParent();
6517     const GlobalValue *GV =
6518         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6519     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6520                                             SIInstrInfo::MO_ABS32_LO);
6521     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6522   }
6523   case Intrinsic::amdgcn_is_shared:
6524   case Intrinsic::amdgcn_is_private: {
6525     SDLoc SL(Op);
6526     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6527       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6528     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6529     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6530                                  Op.getOperand(1));
6531 
6532     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6533                                 DAG.getConstant(1, SL, MVT::i32));
6534     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6535   }
6536   case Intrinsic::amdgcn_alignbit:
6537     return DAG.getNode(ISD::FSHR, DL, VT,
6538                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6539   case Intrinsic::amdgcn_reloc_constant: {
6540     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6541     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6542     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6543     auto RelocSymbol = cast<GlobalVariable>(
6544         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6545     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6546                                             SIInstrInfo::MO_ABS32_LO);
6547     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6548   }
6549   default:
6550     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6551             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6552       return lowerImage(Op, ImageDimIntr, DAG);
6553 
6554     return Op;
6555   }
6556 }
6557 
6558 // This function computes an appropriate offset to pass to
6559 // MachineMemOperand::setOffset() based on the offset inputs to
6560 // an intrinsic.  If any of the offsets are non-contstant or
6561 // if VIndex is non-zero then this function returns 0.  Otherwise,
6562 // it returns the sum of VOffset, SOffset, and Offset.
6563 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6564                                       SDValue SOffset,
6565                                       SDValue Offset,
6566                                       SDValue VIndex = SDValue()) {
6567 
6568   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6569       !isa<ConstantSDNode>(Offset))
6570     return 0;
6571 
6572   if (VIndex) {
6573     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6574       return 0;
6575   }
6576 
6577   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6578          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6579          cast<ConstantSDNode>(Offset)->getSExtValue();
6580 }
6581 
6582 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6583   switch (MF.getFunction().getCallingConv()) {
6584   case CallingConv::AMDGPU_PS:
6585     return 1;
6586   case CallingConv::AMDGPU_VS:
6587     return 2;
6588   case CallingConv::AMDGPU_GS:
6589     return 3;
6590   case CallingConv::AMDGPU_HS:
6591   case CallingConv::AMDGPU_LS:
6592   case CallingConv::AMDGPU_ES:
6593     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6594   case CallingConv::AMDGPU_CS:
6595   case CallingConv::AMDGPU_KERNEL:
6596   case CallingConv::C:
6597   case CallingConv::Fast:
6598   default:
6599     // Assume other calling conventions are various compute callable functions
6600     return 0;
6601   }
6602 }
6603 
6604 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6605                                                  SelectionDAG &DAG) const {
6606   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6607   SDLoc DL(Op);
6608 
6609   switch (IntrID) {
6610   case Intrinsic::amdgcn_ds_ordered_add:
6611   case Intrinsic::amdgcn_ds_ordered_swap: {
6612     MemSDNode *M = cast<MemSDNode>(Op);
6613     SDValue Chain = M->getOperand(0);
6614     SDValue M0 = M->getOperand(2);
6615     SDValue Value = M->getOperand(3);
6616     unsigned IndexOperand = M->getConstantOperandVal(7);
6617     unsigned WaveRelease = M->getConstantOperandVal(8);
6618     unsigned WaveDone = M->getConstantOperandVal(9);
6619 
6620     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6621     IndexOperand &= ~0x3f;
6622     unsigned CountDw = 0;
6623 
6624     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6625       CountDw = (IndexOperand >> 24) & 0xf;
6626       IndexOperand &= ~(0xf << 24);
6627 
6628       if (CountDw < 1 || CountDw > 4) {
6629         report_fatal_error(
6630             "ds_ordered_count: dword count must be between 1 and 4");
6631       }
6632     }
6633 
6634     if (IndexOperand)
6635       report_fatal_error("ds_ordered_count: bad index operand");
6636 
6637     if (WaveDone && !WaveRelease)
6638       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6639 
6640     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6641     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6642     unsigned Offset0 = OrderedCountIndex << 2;
6643     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6644                        (Instruction << 4);
6645 
6646     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6647       Offset1 |= (CountDw - 1) << 6;
6648 
6649     unsigned Offset = Offset0 | (Offset1 << 8);
6650 
6651     SDValue Ops[] = {
6652       Chain,
6653       Value,
6654       DAG.getTargetConstant(Offset, DL, MVT::i16),
6655       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6656     };
6657     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6658                                    M->getVTList(), Ops, M->getMemoryVT(),
6659                                    M->getMemOperand());
6660   }
6661   case Intrinsic::amdgcn_ds_fadd: {
6662     MemSDNode *M = cast<MemSDNode>(Op);
6663     unsigned Opc;
6664     switch (IntrID) {
6665     case Intrinsic::amdgcn_ds_fadd:
6666       Opc = ISD::ATOMIC_LOAD_FADD;
6667       break;
6668     }
6669 
6670     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6671                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6672                          M->getMemOperand());
6673   }
6674   case Intrinsic::amdgcn_atomic_inc:
6675   case Intrinsic::amdgcn_atomic_dec:
6676   case Intrinsic::amdgcn_ds_fmin:
6677   case Intrinsic::amdgcn_ds_fmax: {
6678     MemSDNode *M = cast<MemSDNode>(Op);
6679     unsigned Opc;
6680     switch (IntrID) {
6681     case Intrinsic::amdgcn_atomic_inc:
6682       Opc = AMDGPUISD::ATOMIC_INC;
6683       break;
6684     case Intrinsic::amdgcn_atomic_dec:
6685       Opc = AMDGPUISD::ATOMIC_DEC;
6686       break;
6687     case Intrinsic::amdgcn_ds_fmin:
6688       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6689       break;
6690     case Intrinsic::amdgcn_ds_fmax:
6691       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6692       break;
6693     default:
6694       llvm_unreachable("Unknown intrinsic!");
6695     }
6696     SDValue Ops[] = {
6697       M->getOperand(0), // Chain
6698       M->getOperand(2), // Ptr
6699       M->getOperand(3)  // Value
6700     };
6701 
6702     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6703                                    M->getMemoryVT(), M->getMemOperand());
6704   }
6705   case Intrinsic::amdgcn_buffer_load:
6706   case Intrinsic::amdgcn_buffer_load_format: {
6707     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6708     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6709     unsigned IdxEn = 1;
6710     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6711       IdxEn = Idx->getZExtValue() != 0;
6712     SDValue Ops[] = {
6713       Op.getOperand(0), // Chain
6714       Op.getOperand(2), // rsrc
6715       Op.getOperand(3), // vindex
6716       SDValue(),        // voffset -- will be set by setBufferOffsets
6717       SDValue(),        // soffset -- will be set by setBufferOffsets
6718       SDValue(),        // offset -- will be set by setBufferOffsets
6719       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6720       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6721     };
6722 
6723     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6724     // We don't know the offset if vindex is non-zero, so clear it.
6725     if (IdxEn)
6726       Offset = 0;
6727 
6728     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6729         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6730 
6731     EVT VT = Op.getValueType();
6732     EVT IntVT = VT.changeTypeToInteger();
6733     auto *M = cast<MemSDNode>(Op);
6734     M->getMemOperand()->setOffset(Offset);
6735     EVT LoadVT = Op.getValueType();
6736 
6737     if (LoadVT.getScalarType() == MVT::f16)
6738       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6739                                  M, DAG, Ops);
6740 
6741     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6742     if (LoadVT.getScalarType() == MVT::i8 ||
6743         LoadVT.getScalarType() == MVT::i16)
6744       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6745 
6746     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6747                                M->getMemOperand(), DAG);
6748   }
6749   case Intrinsic::amdgcn_raw_buffer_load:
6750   case Intrinsic::amdgcn_raw_buffer_load_format: {
6751     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6752 
6753     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6754     SDValue Ops[] = {
6755       Op.getOperand(0), // Chain
6756       Op.getOperand(2), // rsrc
6757       DAG.getConstant(0, DL, MVT::i32), // vindex
6758       Offsets.first,    // voffset
6759       Op.getOperand(4), // soffset
6760       Offsets.second,   // offset
6761       Op.getOperand(5), // cachepolicy, swizzled buffer
6762       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6763     };
6764 
6765     auto *M = cast<MemSDNode>(Op);
6766     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6767     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6768   }
6769   case Intrinsic::amdgcn_struct_buffer_load:
6770   case Intrinsic::amdgcn_struct_buffer_load_format: {
6771     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6772 
6773     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6774     SDValue Ops[] = {
6775       Op.getOperand(0), // Chain
6776       Op.getOperand(2), // rsrc
6777       Op.getOperand(3), // vindex
6778       Offsets.first,    // voffset
6779       Op.getOperand(5), // soffset
6780       Offsets.second,   // offset
6781       Op.getOperand(6), // cachepolicy, swizzled buffer
6782       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6783     };
6784 
6785     auto *M = cast<MemSDNode>(Op);
6786     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6787                                                         Ops[2]));
6788     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6789   }
6790   case Intrinsic::amdgcn_tbuffer_load: {
6791     MemSDNode *M = cast<MemSDNode>(Op);
6792     EVT LoadVT = Op.getValueType();
6793 
6794     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6795     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6796     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6797     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6798     unsigned IdxEn = 1;
6799     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6800       IdxEn = Idx->getZExtValue() != 0;
6801     SDValue Ops[] = {
6802       Op.getOperand(0),  // Chain
6803       Op.getOperand(2),  // rsrc
6804       Op.getOperand(3),  // vindex
6805       Op.getOperand(4),  // voffset
6806       Op.getOperand(5),  // soffset
6807       Op.getOperand(6),  // offset
6808       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6809       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6810       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6811     };
6812 
6813     if (LoadVT.getScalarType() == MVT::f16)
6814       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6815                                  M, DAG, Ops);
6816     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6817                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6818                                DAG);
6819   }
6820   case Intrinsic::amdgcn_raw_tbuffer_load: {
6821     MemSDNode *M = cast<MemSDNode>(Op);
6822     EVT LoadVT = Op.getValueType();
6823     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6824 
6825     SDValue Ops[] = {
6826       Op.getOperand(0),  // Chain
6827       Op.getOperand(2),  // rsrc
6828       DAG.getConstant(0, DL, MVT::i32), // vindex
6829       Offsets.first,     // voffset
6830       Op.getOperand(4),  // soffset
6831       Offsets.second,    // offset
6832       Op.getOperand(5),  // format
6833       Op.getOperand(6),  // cachepolicy, swizzled buffer
6834       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6835     };
6836 
6837     if (LoadVT.getScalarType() == MVT::f16)
6838       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6839                                  M, DAG, Ops);
6840     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6841                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6842                                DAG);
6843   }
6844   case Intrinsic::amdgcn_struct_tbuffer_load: {
6845     MemSDNode *M = cast<MemSDNode>(Op);
6846     EVT LoadVT = Op.getValueType();
6847     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6848 
6849     SDValue Ops[] = {
6850       Op.getOperand(0),  // Chain
6851       Op.getOperand(2),  // rsrc
6852       Op.getOperand(3),  // vindex
6853       Offsets.first,     // voffset
6854       Op.getOperand(5),  // soffset
6855       Offsets.second,    // offset
6856       Op.getOperand(6),  // format
6857       Op.getOperand(7),  // cachepolicy, swizzled buffer
6858       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6859     };
6860 
6861     if (LoadVT.getScalarType() == MVT::f16)
6862       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6863                                  M, DAG, Ops);
6864     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6865                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6866                                DAG);
6867   }
6868   case Intrinsic::amdgcn_buffer_atomic_swap:
6869   case Intrinsic::amdgcn_buffer_atomic_add:
6870   case Intrinsic::amdgcn_buffer_atomic_sub:
6871   case Intrinsic::amdgcn_buffer_atomic_csub:
6872   case Intrinsic::amdgcn_buffer_atomic_smin:
6873   case Intrinsic::amdgcn_buffer_atomic_umin:
6874   case Intrinsic::amdgcn_buffer_atomic_smax:
6875   case Intrinsic::amdgcn_buffer_atomic_umax:
6876   case Intrinsic::amdgcn_buffer_atomic_and:
6877   case Intrinsic::amdgcn_buffer_atomic_or:
6878   case Intrinsic::amdgcn_buffer_atomic_xor: {
6879     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6880     unsigned IdxEn = 1;
6881     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6882       IdxEn = Idx->getZExtValue() != 0;
6883     SDValue Ops[] = {
6884       Op.getOperand(0), // Chain
6885       Op.getOperand(2), // vdata
6886       Op.getOperand(3), // rsrc
6887       Op.getOperand(4), // vindex
6888       SDValue(),        // voffset -- will be set by setBufferOffsets
6889       SDValue(),        // soffset -- will be set by setBufferOffsets
6890       SDValue(),        // offset -- will be set by setBufferOffsets
6891       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6892       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6893     };
6894     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6895     // We don't know the offset if vindex is non-zero, so clear it.
6896     if (IdxEn)
6897       Offset = 0;
6898     EVT VT = Op.getValueType();
6899 
6900     auto *M = cast<MemSDNode>(Op);
6901     M->getMemOperand()->setOffset(Offset);
6902     unsigned Opcode = 0;
6903 
6904     switch (IntrID) {
6905     case Intrinsic::amdgcn_buffer_atomic_swap:
6906       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6907       break;
6908     case Intrinsic::amdgcn_buffer_atomic_add:
6909       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6910       break;
6911     case Intrinsic::amdgcn_buffer_atomic_sub:
6912       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6913       break;
6914     case Intrinsic::amdgcn_buffer_atomic_csub:
6915       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
6916       break;
6917     case Intrinsic::amdgcn_buffer_atomic_smin:
6918       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6919       break;
6920     case Intrinsic::amdgcn_buffer_atomic_umin:
6921       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6922       break;
6923     case Intrinsic::amdgcn_buffer_atomic_smax:
6924       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6925       break;
6926     case Intrinsic::amdgcn_buffer_atomic_umax:
6927       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6928       break;
6929     case Intrinsic::amdgcn_buffer_atomic_and:
6930       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6931       break;
6932     case Intrinsic::amdgcn_buffer_atomic_or:
6933       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6934       break;
6935     case Intrinsic::amdgcn_buffer_atomic_xor:
6936       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6937       break;
6938     default:
6939       llvm_unreachable("unhandled atomic opcode");
6940     }
6941 
6942     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6943                                    M->getMemOperand());
6944   }
6945   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6946   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6947   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6948   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6949   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6950   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6951   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6952   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6953   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6954   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6955   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6956   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6957     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6958     SDValue Ops[] = {
6959       Op.getOperand(0), // Chain
6960       Op.getOperand(2), // vdata
6961       Op.getOperand(3), // rsrc
6962       DAG.getConstant(0, DL, MVT::i32), // vindex
6963       Offsets.first,    // voffset
6964       Op.getOperand(5), // soffset
6965       Offsets.second,   // offset
6966       Op.getOperand(6), // cachepolicy
6967       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6968     };
6969     EVT VT = Op.getValueType();
6970 
6971     auto *M = cast<MemSDNode>(Op);
6972     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6973     unsigned Opcode = 0;
6974 
6975     switch (IntrID) {
6976     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6977       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6978       break;
6979     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6980       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6981       break;
6982     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6983       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6984       break;
6985     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6986       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6987       break;
6988     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6989       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6990       break;
6991     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6992       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6993       break;
6994     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6995       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6996       break;
6997     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6998       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6999       break;
7000     case Intrinsic::amdgcn_raw_buffer_atomic_or:
7001       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7002       break;
7003     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7004       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7005       break;
7006     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7007       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
7008       break;
7009     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7010       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
7011       break;
7012     default:
7013       llvm_unreachable("unhandled atomic opcode");
7014     }
7015 
7016     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7017                                    M->getMemOperand());
7018   }
7019   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7020   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7021   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7022   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7023   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7024   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7025   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7026   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7027   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7028   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7029   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7030   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
7031     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7032     SDValue Ops[] = {
7033       Op.getOperand(0), // Chain
7034       Op.getOperand(2), // vdata
7035       Op.getOperand(3), // rsrc
7036       Op.getOperand(4), // vindex
7037       Offsets.first,    // voffset
7038       Op.getOperand(6), // soffset
7039       Offsets.second,   // offset
7040       Op.getOperand(7), // cachepolicy
7041       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7042     };
7043     EVT VT = Op.getValueType();
7044 
7045     auto *M = cast<MemSDNode>(Op);
7046     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7047                                                         Ops[3]));
7048     unsigned Opcode = 0;
7049 
7050     switch (IntrID) {
7051     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7052       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7053       break;
7054     case Intrinsic::amdgcn_struct_buffer_atomic_add:
7055       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7056       break;
7057     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7058       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7059       break;
7060     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7061       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7062       break;
7063     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7064       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7065       break;
7066     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7067       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7068       break;
7069     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7070       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7071       break;
7072     case Intrinsic::amdgcn_struct_buffer_atomic_and:
7073       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7074       break;
7075     case Intrinsic::amdgcn_struct_buffer_atomic_or:
7076       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7077       break;
7078     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7079       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7080       break;
7081     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7082       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
7083       break;
7084     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7085       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
7086       break;
7087     default:
7088       llvm_unreachable("unhandled atomic opcode");
7089     }
7090 
7091     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7092                                    M->getMemOperand());
7093   }
7094   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7095     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7096     unsigned IdxEn = 1;
7097     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7098       IdxEn = Idx->getZExtValue() != 0;
7099     SDValue Ops[] = {
7100       Op.getOperand(0), // Chain
7101       Op.getOperand(2), // src
7102       Op.getOperand(3), // cmp
7103       Op.getOperand(4), // rsrc
7104       Op.getOperand(5), // vindex
7105       SDValue(),        // voffset -- will be set by setBufferOffsets
7106       SDValue(),        // soffset -- will be set by setBufferOffsets
7107       SDValue(),        // offset -- will be set by setBufferOffsets
7108       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7109       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7110     };
7111     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7112     // We don't know the offset if vindex is non-zero, so clear it.
7113     if (IdxEn)
7114       Offset = 0;
7115     EVT VT = Op.getValueType();
7116     auto *M = cast<MemSDNode>(Op);
7117     M->getMemOperand()->setOffset(Offset);
7118 
7119     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7120                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7121   }
7122   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7123     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7124     SDValue Ops[] = {
7125       Op.getOperand(0), // Chain
7126       Op.getOperand(2), // src
7127       Op.getOperand(3), // cmp
7128       Op.getOperand(4), // rsrc
7129       DAG.getConstant(0, DL, MVT::i32), // vindex
7130       Offsets.first,    // voffset
7131       Op.getOperand(6), // soffset
7132       Offsets.second,   // offset
7133       Op.getOperand(7), // cachepolicy
7134       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7135     };
7136     EVT VT = Op.getValueType();
7137     auto *M = cast<MemSDNode>(Op);
7138     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7139 
7140     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7141                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7142   }
7143   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7144     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7145     SDValue Ops[] = {
7146       Op.getOperand(0), // Chain
7147       Op.getOperand(2), // src
7148       Op.getOperand(3), // cmp
7149       Op.getOperand(4), // rsrc
7150       Op.getOperand(5), // vindex
7151       Offsets.first,    // voffset
7152       Op.getOperand(7), // soffset
7153       Offsets.second,   // offset
7154       Op.getOperand(8), // cachepolicy
7155       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7156     };
7157     EVT VT = Op.getValueType();
7158     auto *M = cast<MemSDNode>(Op);
7159     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7160                                                         Ops[4]));
7161 
7162     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7163                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7164   }
7165   case Intrinsic::amdgcn_global_atomic_csub: {
7166     MemSDNode *M = cast<MemSDNode>(Op);
7167     SDValue Ops[] = {
7168       M->getOperand(0), // Chain
7169       M->getOperand(2), // Ptr
7170       M->getOperand(3)  // Value
7171     };
7172 
7173     return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_LOAD_CSUB, SDLoc(Op),
7174                                    M->getVTList(), Ops, M->getMemoryVT(),
7175                                    M->getMemOperand());
7176   }
7177 
7178   default:
7179     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7180             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7181       return lowerImage(Op, ImageDimIntr, DAG);
7182 
7183     return SDValue();
7184   }
7185 }
7186 
7187 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7188 // dwordx4 if on SI.
7189 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7190                                               SDVTList VTList,
7191                                               ArrayRef<SDValue> Ops, EVT MemVT,
7192                                               MachineMemOperand *MMO,
7193                                               SelectionDAG &DAG) const {
7194   EVT VT = VTList.VTs[0];
7195   EVT WidenedVT = VT;
7196   EVT WidenedMemVT = MemVT;
7197   if (!Subtarget->hasDwordx3LoadStores() &&
7198       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7199     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7200                                  WidenedVT.getVectorElementType(), 4);
7201     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7202                                     WidenedMemVT.getVectorElementType(), 4);
7203     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7204   }
7205 
7206   assert(VTList.NumVTs == 2);
7207   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7208 
7209   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7210                                        WidenedMemVT, MMO);
7211   if (WidenedVT != VT) {
7212     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7213                                DAG.getVectorIdxConstant(0, DL));
7214     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7215   }
7216   return NewOp;
7217 }
7218 
7219 SDValue SITargetLowering::handleD16VData(SDValue VData,
7220                                          SelectionDAG &DAG) const {
7221   EVT StoreVT = VData.getValueType();
7222 
7223   // No change for f16 and legal vector D16 types.
7224   if (!StoreVT.isVector())
7225     return VData;
7226 
7227   SDLoc DL(VData);
7228   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
7229 
7230   if (Subtarget->hasUnpackedD16VMem()) {
7231     // We need to unpack the packed data to store.
7232     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7233     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7234 
7235     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
7236                                         StoreVT.getVectorNumElements());
7237     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7238     return DAG.UnrollVectorOp(ZExt.getNode());
7239   }
7240 
7241   assert(isTypeLegal(StoreVT));
7242   return VData;
7243 }
7244 
7245 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7246                                               SelectionDAG &DAG) const {
7247   SDLoc DL(Op);
7248   SDValue Chain = Op.getOperand(0);
7249   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7250   MachineFunction &MF = DAG.getMachineFunction();
7251 
7252   switch (IntrinsicID) {
7253   case Intrinsic::amdgcn_exp_compr: {
7254     SDValue Src0 = Op.getOperand(4);
7255     SDValue Src1 = Op.getOperand(5);
7256     // Hack around illegal type on SI by directly selecting it.
7257     if (isTypeLegal(Src0.getValueType()))
7258       return SDValue();
7259 
7260     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7261     SDValue Undef = DAG.getUNDEF(MVT::f32);
7262     const SDValue Ops[] = {
7263       Op.getOperand(2), // tgt
7264       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7265       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7266       Undef, // src2
7267       Undef, // src3
7268       Op.getOperand(7), // vm
7269       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7270       Op.getOperand(3), // en
7271       Op.getOperand(0) // Chain
7272     };
7273 
7274     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7275     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7276   }
7277   case Intrinsic::amdgcn_s_barrier: {
7278     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7279       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7280       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7281       if (WGSize <= ST.getWavefrontSize())
7282         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7283                                           Op.getOperand(0)), 0);
7284     }
7285     return SDValue();
7286   };
7287   case Intrinsic::amdgcn_tbuffer_store: {
7288     SDValue VData = Op.getOperand(2);
7289     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7290     if (IsD16)
7291       VData = handleD16VData(VData, DAG);
7292     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7293     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7294     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7295     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7296     unsigned IdxEn = 1;
7297     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7298       IdxEn = Idx->getZExtValue() != 0;
7299     SDValue Ops[] = {
7300       Chain,
7301       VData,             // vdata
7302       Op.getOperand(3),  // rsrc
7303       Op.getOperand(4),  // vindex
7304       Op.getOperand(5),  // voffset
7305       Op.getOperand(6),  // soffset
7306       Op.getOperand(7),  // offset
7307       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7308       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7309       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7310     };
7311     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7312                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7313     MemSDNode *M = cast<MemSDNode>(Op);
7314     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7315                                    M->getMemoryVT(), M->getMemOperand());
7316   }
7317 
7318   case Intrinsic::amdgcn_struct_tbuffer_store: {
7319     SDValue VData = Op.getOperand(2);
7320     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7321     if (IsD16)
7322       VData = handleD16VData(VData, DAG);
7323     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7324     SDValue Ops[] = {
7325       Chain,
7326       VData,             // vdata
7327       Op.getOperand(3),  // rsrc
7328       Op.getOperand(4),  // vindex
7329       Offsets.first,     // voffset
7330       Op.getOperand(6),  // soffset
7331       Offsets.second,    // offset
7332       Op.getOperand(7),  // format
7333       Op.getOperand(8),  // cachepolicy, swizzled buffer
7334       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7335     };
7336     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7337                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7338     MemSDNode *M = cast<MemSDNode>(Op);
7339     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7340                                    M->getMemoryVT(), M->getMemOperand());
7341   }
7342 
7343   case Intrinsic::amdgcn_raw_tbuffer_store: {
7344     SDValue VData = Op.getOperand(2);
7345     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7346     if (IsD16)
7347       VData = handleD16VData(VData, DAG);
7348     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7349     SDValue Ops[] = {
7350       Chain,
7351       VData,             // vdata
7352       Op.getOperand(3),  // rsrc
7353       DAG.getConstant(0, DL, MVT::i32), // vindex
7354       Offsets.first,     // voffset
7355       Op.getOperand(5),  // soffset
7356       Offsets.second,    // offset
7357       Op.getOperand(6),  // format
7358       Op.getOperand(7),  // cachepolicy, swizzled buffer
7359       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7360     };
7361     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7362                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7363     MemSDNode *M = cast<MemSDNode>(Op);
7364     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7365                                    M->getMemoryVT(), M->getMemOperand());
7366   }
7367 
7368   case Intrinsic::amdgcn_buffer_store:
7369   case Intrinsic::amdgcn_buffer_store_format: {
7370     SDValue VData = Op.getOperand(2);
7371     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7372     if (IsD16)
7373       VData = handleD16VData(VData, DAG);
7374     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7375     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7376     unsigned IdxEn = 1;
7377     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7378       IdxEn = Idx->getZExtValue() != 0;
7379     SDValue Ops[] = {
7380       Chain,
7381       VData,
7382       Op.getOperand(3), // rsrc
7383       Op.getOperand(4), // vindex
7384       SDValue(), // voffset -- will be set by setBufferOffsets
7385       SDValue(), // soffset -- will be set by setBufferOffsets
7386       SDValue(), // offset -- will be set by setBufferOffsets
7387       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7388       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7389     };
7390     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7391     // We don't know the offset if vindex is non-zero, so clear it.
7392     if (IdxEn)
7393       Offset = 0;
7394     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7395                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7396     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7397     MemSDNode *M = cast<MemSDNode>(Op);
7398     M->getMemOperand()->setOffset(Offset);
7399 
7400     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7401     EVT VDataType = VData.getValueType().getScalarType();
7402     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7403       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7404 
7405     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7406                                    M->getMemoryVT(), M->getMemOperand());
7407   }
7408 
7409   case Intrinsic::amdgcn_raw_buffer_store:
7410   case Intrinsic::amdgcn_raw_buffer_store_format: {
7411     const bool IsFormat =
7412         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7413 
7414     SDValue VData = Op.getOperand(2);
7415     EVT VDataVT = VData.getValueType();
7416     EVT EltType = VDataVT.getScalarType();
7417     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7418     if (IsD16)
7419       VData = handleD16VData(VData, DAG);
7420 
7421     if (!isTypeLegal(VDataVT)) {
7422       VData =
7423           DAG.getNode(ISD::BITCAST, DL,
7424                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7425     }
7426 
7427     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7428     SDValue Ops[] = {
7429       Chain,
7430       VData,
7431       Op.getOperand(3), // rsrc
7432       DAG.getConstant(0, DL, MVT::i32), // vindex
7433       Offsets.first,    // voffset
7434       Op.getOperand(5), // soffset
7435       Offsets.second,   // offset
7436       Op.getOperand(6), // cachepolicy, swizzled buffer
7437       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7438     };
7439     unsigned Opc =
7440         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7441     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7442     MemSDNode *M = cast<MemSDNode>(Op);
7443     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7444 
7445     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7446     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7447       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7448 
7449     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7450                                    M->getMemoryVT(), M->getMemOperand());
7451   }
7452 
7453   case Intrinsic::amdgcn_struct_buffer_store:
7454   case Intrinsic::amdgcn_struct_buffer_store_format: {
7455     const bool IsFormat =
7456         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7457 
7458     SDValue VData = Op.getOperand(2);
7459     EVT VDataVT = VData.getValueType();
7460     EVT EltType = VDataVT.getScalarType();
7461     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7462 
7463     if (IsD16)
7464       VData = handleD16VData(VData, DAG);
7465 
7466     if (!isTypeLegal(VDataVT)) {
7467       VData =
7468           DAG.getNode(ISD::BITCAST, DL,
7469                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7470     }
7471 
7472     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7473     SDValue Ops[] = {
7474       Chain,
7475       VData,
7476       Op.getOperand(3), // rsrc
7477       Op.getOperand(4), // vindex
7478       Offsets.first,    // voffset
7479       Op.getOperand(6), // soffset
7480       Offsets.second,   // offset
7481       Op.getOperand(7), // cachepolicy, swizzled buffer
7482       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7483     };
7484     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7485                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7486     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7487     MemSDNode *M = cast<MemSDNode>(Op);
7488     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7489                                                         Ops[3]));
7490 
7491     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7492     EVT VDataType = VData.getValueType().getScalarType();
7493     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7494       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7495 
7496     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7497                                    M->getMemoryVT(), M->getMemOperand());
7498   }
7499 
7500   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7501     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7502     unsigned IdxEn = 1;
7503     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7504       IdxEn = Idx->getZExtValue() != 0;
7505     SDValue Ops[] = {
7506       Chain,
7507       Op.getOperand(2), // vdata
7508       Op.getOperand(3), // rsrc
7509       Op.getOperand(4), // vindex
7510       SDValue(),        // voffset -- will be set by setBufferOffsets
7511       SDValue(),        // soffset -- will be set by setBufferOffsets
7512       SDValue(),        // offset -- will be set by setBufferOffsets
7513       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7514       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7515     };
7516     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7517     // We don't know the offset if vindex is non-zero, so clear it.
7518     if (IdxEn)
7519       Offset = 0;
7520     EVT VT = Op.getOperand(2).getValueType();
7521 
7522     auto *M = cast<MemSDNode>(Op);
7523     M->getMemOperand()->setOffset(Offset);
7524     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7525                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7526 
7527     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7528                                    M->getMemOperand());
7529   }
7530 
7531   case Intrinsic::amdgcn_global_atomic_fadd: {
7532     SDValue Ops[] = {
7533       Chain,
7534       Op.getOperand(2), // ptr
7535       Op.getOperand(3)  // vdata
7536     };
7537     EVT VT = Op.getOperand(3).getValueType();
7538 
7539     auto *M = cast<MemSDNode>(Op);
7540     if (VT.isVector()) {
7541       return DAG.getMemIntrinsicNode(
7542         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7543         M->getMemOperand());
7544     }
7545 
7546     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7547                          DAG.getVTList(VT, MVT::Other), Ops,
7548                          M->getMemOperand()).getValue(1);
7549   }
7550   case Intrinsic::amdgcn_end_cf:
7551     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7552                                       Op->getOperand(2), Chain), 0);
7553 
7554   default: {
7555     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7556             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7557       return lowerImage(Op, ImageDimIntr, DAG);
7558 
7559     return Op;
7560   }
7561   }
7562 }
7563 
7564 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7565 // offset (the offset that is included in bounds checking and swizzling, to be
7566 // split between the instruction's voffset and immoffset fields) and soffset
7567 // (the offset that is excluded from bounds checking and swizzling, to go in
7568 // the instruction's soffset field).  This function takes the first kind of
7569 // offset and figures out how to split it between voffset and immoffset.
7570 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7571     SDValue Offset, SelectionDAG &DAG) const {
7572   SDLoc DL(Offset);
7573   const unsigned MaxImm = 4095;
7574   SDValue N0 = Offset;
7575   ConstantSDNode *C1 = nullptr;
7576 
7577   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7578     N0 = SDValue();
7579   else if (DAG.isBaseWithConstantOffset(N0)) {
7580     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7581     N0 = N0.getOperand(0);
7582   }
7583 
7584   if (C1) {
7585     unsigned ImmOffset = C1->getZExtValue();
7586     // If the immediate value is too big for the immoffset field, put the value
7587     // and -4096 into the immoffset field so that the value that is copied/added
7588     // for the voffset field is a multiple of 4096, and it stands more chance
7589     // of being CSEd with the copy/add for another similar load/store.
7590     // However, do not do that rounding down to a multiple of 4096 if that is a
7591     // negative number, as it appears to be illegal to have a negative offset
7592     // in the vgpr, even if adding the immediate offset makes it positive.
7593     unsigned Overflow = ImmOffset & ~MaxImm;
7594     ImmOffset -= Overflow;
7595     if ((int32_t)Overflow < 0) {
7596       Overflow += ImmOffset;
7597       ImmOffset = 0;
7598     }
7599     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7600     if (Overflow) {
7601       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7602       if (!N0)
7603         N0 = OverflowVal;
7604       else {
7605         SDValue Ops[] = { N0, OverflowVal };
7606         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7607       }
7608     }
7609   }
7610   if (!N0)
7611     N0 = DAG.getConstant(0, DL, MVT::i32);
7612   if (!C1)
7613     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7614   return {N0, SDValue(C1, 0)};
7615 }
7616 
7617 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7618 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7619 // pointed to by Offsets.
7620 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7621                                         SelectionDAG &DAG, SDValue *Offsets,
7622                                         unsigned Align) const {
7623   SDLoc DL(CombinedOffset);
7624   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7625     uint32_t Imm = C->getZExtValue();
7626     uint32_t SOffset, ImmOffset;
7627     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7628       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7629       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7630       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7631       return SOffset + ImmOffset;
7632     }
7633   }
7634   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7635     SDValue N0 = CombinedOffset.getOperand(0);
7636     SDValue N1 = CombinedOffset.getOperand(1);
7637     uint32_t SOffset, ImmOffset;
7638     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7639     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7640                                                 Subtarget, Align)) {
7641       Offsets[0] = N0;
7642       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7643       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7644       return 0;
7645     }
7646   }
7647   Offsets[0] = CombinedOffset;
7648   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7649   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7650   return 0;
7651 }
7652 
7653 // Handle 8 bit and 16 bit buffer loads
7654 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7655                                                      EVT LoadVT, SDLoc DL,
7656                                                      ArrayRef<SDValue> Ops,
7657                                                      MemSDNode *M) const {
7658   EVT IntVT = LoadVT.changeTypeToInteger();
7659   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7660          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7661 
7662   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7663   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7664                                                Ops, IntVT,
7665                                                M->getMemOperand());
7666   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7667   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7668 
7669   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7670 }
7671 
7672 // Handle 8 bit and 16 bit buffer stores
7673 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7674                                                       EVT VDataType, SDLoc DL,
7675                                                       SDValue Ops[],
7676                                                       MemSDNode *M) const {
7677   if (VDataType == MVT::f16)
7678     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7679 
7680   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7681   Ops[1] = BufferStoreExt;
7682   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7683                                  AMDGPUISD::BUFFER_STORE_SHORT;
7684   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7685   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7686                                      M->getMemOperand());
7687 }
7688 
7689 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7690                                  ISD::LoadExtType ExtType, SDValue Op,
7691                                  const SDLoc &SL, EVT VT) {
7692   if (VT.bitsLT(Op.getValueType()))
7693     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7694 
7695   switch (ExtType) {
7696   case ISD::SEXTLOAD:
7697     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7698   case ISD::ZEXTLOAD:
7699     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7700   case ISD::EXTLOAD:
7701     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7702   case ISD::NON_EXTLOAD:
7703     return Op;
7704   }
7705 
7706   llvm_unreachable("invalid ext type");
7707 }
7708 
7709 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7710   SelectionDAG &DAG = DCI.DAG;
7711   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7712     return SDValue();
7713 
7714   // FIXME: Constant loads should all be marked invariant.
7715   unsigned AS = Ld->getAddressSpace();
7716   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7717       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7718       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7719     return SDValue();
7720 
7721   // Don't do this early, since it may interfere with adjacent load merging for
7722   // illegal types. We can avoid losing alignment information for exotic types
7723   // pre-legalize.
7724   EVT MemVT = Ld->getMemoryVT();
7725   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7726       MemVT.getSizeInBits() >= 32)
7727     return SDValue();
7728 
7729   SDLoc SL(Ld);
7730 
7731   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7732          "unexpected vector extload");
7733 
7734   // TODO: Drop only high part of range.
7735   SDValue Ptr = Ld->getBasePtr();
7736   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7737                                 MVT::i32, SL, Ld->getChain(), Ptr,
7738                                 Ld->getOffset(),
7739                                 Ld->getPointerInfo(), MVT::i32,
7740                                 Ld->getAlignment(),
7741                                 Ld->getMemOperand()->getFlags(),
7742                                 Ld->getAAInfo(),
7743                                 nullptr); // Drop ranges
7744 
7745   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7746   if (MemVT.isFloatingPoint()) {
7747     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7748            "unexpected fp extload");
7749     TruncVT = MemVT.changeTypeToInteger();
7750   }
7751 
7752   SDValue Cvt = NewLoad;
7753   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7754     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7755                       DAG.getValueType(TruncVT));
7756   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7757              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7758     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7759   } else {
7760     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7761   }
7762 
7763   EVT VT = Ld->getValueType(0);
7764   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7765 
7766   DCI.AddToWorklist(Cvt.getNode());
7767 
7768   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7769   // the appropriate extension from the 32-bit load.
7770   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7771   DCI.AddToWorklist(Cvt.getNode());
7772 
7773   // Handle conversion back to floating point if necessary.
7774   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7775 
7776   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7777 }
7778 
7779 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7780   SDLoc DL(Op);
7781   LoadSDNode *Load = cast<LoadSDNode>(Op);
7782   ISD::LoadExtType ExtType = Load->getExtensionType();
7783   EVT MemVT = Load->getMemoryVT();
7784 
7785   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7786     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7787       return SDValue();
7788 
7789     // FIXME: Copied from PPC
7790     // First, load into 32 bits, then truncate to 1 bit.
7791 
7792     SDValue Chain = Load->getChain();
7793     SDValue BasePtr = Load->getBasePtr();
7794     MachineMemOperand *MMO = Load->getMemOperand();
7795 
7796     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7797 
7798     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7799                                    BasePtr, RealMemVT, MMO);
7800 
7801     if (!MemVT.isVector()) {
7802       SDValue Ops[] = {
7803         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7804         NewLD.getValue(1)
7805       };
7806 
7807       return DAG.getMergeValues(Ops, DL);
7808     }
7809 
7810     SmallVector<SDValue, 3> Elts;
7811     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7812       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7813                                 DAG.getConstant(I, DL, MVT::i32));
7814 
7815       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7816     }
7817 
7818     SDValue Ops[] = {
7819       DAG.getBuildVector(MemVT, DL, Elts),
7820       NewLD.getValue(1)
7821     };
7822 
7823     return DAG.getMergeValues(Ops, DL);
7824   }
7825 
7826   if (!MemVT.isVector())
7827     return SDValue();
7828 
7829   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7830          "Custom lowering for non-i32 vectors hasn't been implemented.");
7831 
7832   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7833                                       MemVT, *Load->getMemOperand())) {
7834     SDValue Ops[2];
7835     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7836     return DAG.getMergeValues(Ops, DL);
7837   }
7838 
7839   unsigned Alignment = Load->getAlignment();
7840   unsigned AS = Load->getAddressSpace();
7841   if (Subtarget->hasLDSMisalignedBug() &&
7842       AS == AMDGPUAS::FLAT_ADDRESS &&
7843       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7844     return SplitVectorLoad(Op, DAG);
7845   }
7846 
7847   MachineFunction &MF = DAG.getMachineFunction();
7848   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7849   // If there is a possibilty that flat instruction access scratch memory
7850   // then we need to use the same legalization rules we use for private.
7851   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7852       !Subtarget->hasMultiDwordFlatScratchAddressing())
7853     AS = MFI->hasFlatScratchInit() ?
7854          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7855 
7856   unsigned NumElements = MemVT.getVectorNumElements();
7857 
7858   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7859       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7860     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7861       if (MemVT.isPow2VectorType())
7862         return SDValue();
7863       if (NumElements == 3)
7864         return WidenVectorLoad(Op, DAG);
7865       return SplitVectorLoad(Op, DAG);
7866     }
7867     // Non-uniform loads will be selected to MUBUF instructions, so they
7868     // have the same legalization requirements as global and private
7869     // loads.
7870     //
7871   }
7872 
7873   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7874       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7875       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7876     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7877         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
7878         Alignment >= 4 && NumElements < 32) {
7879       if (MemVT.isPow2VectorType())
7880         return SDValue();
7881       if (NumElements == 3)
7882         return WidenVectorLoad(Op, DAG);
7883       return SplitVectorLoad(Op, DAG);
7884     }
7885     // Non-uniform loads will be selected to MUBUF instructions, so they
7886     // have the same legalization requirements as global and private
7887     // loads.
7888     //
7889   }
7890   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7891       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7892       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7893       AS == AMDGPUAS::FLAT_ADDRESS) {
7894     if (NumElements > 4)
7895       return SplitVectorLoad(Op, DAG);
7896     // v3 loads not supported on SI.
7897     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7898       return WidenVectorLoad(Op, DAG);
7899     // v3 and v4 loads are supported for private and global memory.
7900     return SDValue();
7901   }
7902   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7903     // Depending on the setting of the private_element_size field in the
7904     // resource descriptor, we can only make private accesses up to a certain
7905     // size.
7906     switch (Subtarget->getMaxPrivateElementSize()) {
7907     case 4: {
7908       SDValue Ops[2];
7909       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7910       return DAG.getMergeValues(Ops, DL);
7911     }
7912     case 8:
7913       if (NumElements > 2)
7914         return SplitVectorLoad(Op, DAG);
7915       return SDValue();
7916     case 16:
7917       // Same as global/flat
7918       if (NumElements > 4)
7919         return SplitVectorLoad(Op, DAG);
7920       // v3 loads not supported on SI.
7921       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7922         return WidenVectorLoad(Op, DAG);
7923       return SDValue();
7924     default:
7925       llvm_unreachable("unsupported private_element_size");
7926     }
7927   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7928     // Use ds_read_b128 if possible.
7929     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7930         MemVT.getStoreSize() == 16)
7931       return SDValue();
7932 
7933     if (NumElements > 2)
7934       return SplitVectorLoad(Op, DAG);
7935 
7936     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7937     // address is negative, then the instruction is incorrectly treated as
7938     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7939     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7940     // load later in the SILoadStoreOptimizer.
7941     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7942         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7943         Load->getAlignment() < 8) {
7944       return SplitVectorLoad(Op, DAG);
7945     }
7946   }
7947   return SDValue();
7948 }
7949 
7950 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7951   EVT VT = Op.getValueType();
7952   assert(VT.getSizeInBits() == 64);
7953 
7954   SDLoc DL(Op);
7955   SDValue Cond = Op.getOperand(0);
7956 
7957   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7958   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7959 
7960   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7961   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7962 
7963   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7964   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7965 
7966   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7967 
7968   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7969   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7970 
7971   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7972 
7973   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7974   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7975 }
7976 
7977 // Catch division cases where we can use shortcuts with rcp and rsq
7978 // instructions.
7979 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7980                                               SelectionDAG &DAG) const {
7981   SDLoc SL(Op);
7982   SDValue LHS = Op.getOperand(0);
7983   SDValue RHS = Op.getOperand(1);
7984   EVT VT = Op.getValueType();
7985   const SDNodeFlags Flags = Op->getFlags();
7986 
7987   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7988                             Flags.hasApproximateFuncs();
7989 
7990   // Without !fpmath accuracy information, we can't do more because we don't
7991   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7992   if (!AllowInaccurateRcp)
7993     return SDValue();
7994 
7995   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7996     if (CLHS->isExactlyValue(1.0)) {
7997       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7998       // the CI documentation has a worst case error of 1 ulp.
7999       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8000       // use it as long as we aren't trying to use denormals.
8001       //
8002       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8003 
8004       // 1.0 / sqrt(x) -> rsq(x)
8005 
8006       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8007       // error seems really high at 2^29 ULP.
8008       if (RHS.getOpcode() == ISD::FSQRT)
8009         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8010 
8011       // 1.0 / x -> rcp(x)
8012       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8013     }
8014 
8015     // Same as for 1.0, but expand the sign out of the constant.
8016     if (CLHS->isExactlyValue(-1.0)) {
8017       // -1.0 / x -> rcp (fneg x)
8018       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8019       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8020     }
8021   }
8022 
8023   // Turn into multiply by the reciprocal.
8024   // x / y -> x * (1.0 / y)
8025   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8026   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8027 }
8028 
8029 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8030                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8031                           SDNodeFlags Flags) {
8032   if (GlueChain->getNumValues() <= 1) {
8033     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8034   }
8035 
8036   assert(GlueChain->getNumValues() == 3);
8037 
8038   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8039   switch (Opcode) {
8040   default: llvm_unreachable("no chain equivalent for opcode");
8041   case ISD::FMUL:
8042     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8043     break;
8044   }
8045 
8046   return DAG.getNode(Opcode, SL, VTList,
8047                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8048                      Flags);
8049 }
8050 
8051 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8052                            EVT VT, SDValue A, SDValue B, SDValue C,
8053                            SDValue GlueChain, SDNodeFlags Flags) {
8054   if (GlueChain->getNumValues() <= 1) {
8055     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8056   }
8057 
8058   assert(GlueChain->getNumValues() == 3);
8059 
8060   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8061   switch (Opcode) {
8062   default: llvm_unreachable("no chain equivalent for opcode");
8063   case ISD::FMA:
8064     Opcode = AMDGPUISD::FMA_W_CHAIN;
8065     break;
8066   }
8067 
8068   return DAG.getNode(Opcode, SL, VTList,
8069                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8070                      Flags);
8071 }
8072 
8073 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8074   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8075     return FastLowered;
8076 
8077   SDLoc SL(Op);
8078   SDValue Src0 = Op.getOperand(0);
8079   SDValue Src1 = Op.getOperand(1);
8080 
8081   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8082   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8083 
8084   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8085   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8086 
8087   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8088   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8089 
8090   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8091 }
8092 
8093 // Faster 2.5 ULP division that does not support denormals.
8094 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8095   SDLoc SL(Op);
8096   SDValue LHS = Op.getOperand(1);
8097   SDValue RHS = Op.getOperand(2);
8098 
8099   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8100 
8101   const APFloat K0Val(BitsToFloat(0x6f800000));
8102   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8103 
8104   const APFloat K1Val(BitsToFloat(0x2f800000));
8105   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8106 
8107   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8108 
8109   EVT SetCCVT =
8110     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8111 
8112   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8113 
8114   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8115 
8116   // TODO: Should this propagate fast-math-flags?
8117   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8118 
8119   // rcp does not support denormals.
8120   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8121 
8122   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8123 
8124   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8125 }
8126 
8127 // Returns immediate value for setting the F32 denorm mode when using the
8128 // S_DENORM_MODE instruction.
8129 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8130                                           const SDLoc &SL, const GCNSubtarget *ST) {
8131   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8132   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8133                                 ? FP_DENORM_FLUSH_NONE
8134                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8135 
8136   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8137   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8138 }
8139 
8140 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8141   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8142     return FastLowered;
8143 
8144   // The selection matcher assumes anything with a chain selecting to a
8145   // mayRaiseFPException machine instruction. Since we're introducing a chain
8146   // here, we need to explicitly report nofpexcept for the regular fdiv
8147   // lowering.
8148   SDNodeFlags Flags = Op->getFlags();
8149   Flags.setNoFPExcept(true);
8150 
8151   SDLoc SL(Op);
8152   SDValue LHS = Op.getOperand(0);
8153   SDValue RHS = Op.getOperand(1);
8154 
8155   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8156 
8157   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8158 
8159   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8160                                           {RHS, RHS, LHS}, Flags);
8161   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8162                                         {LHS, RHS, LHS}, Flags);
8163 
8164   // Denominator is scaled to not be denormal, so using rcp is ok.
8165   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8166                                   DenominatorScaled, Flags);
8167   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8168                                      DenominatorScaled, Flags);
8169 
8170   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8171                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8172                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8173   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8174 
8175   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8176 
8177   if (!HasFP32Denormals) {
8178     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8179     // lowering. The chain dependence is insufficient, and we need glue. We do
8180     // not need the glue variants in a strictfp function.
8181 
8182     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8183 
8184     SDNode *EnableDenorm;
8185     if (Subtarget->hasDenormModeInst()) {
8186       const SDValue EnableDenormValue =
8187           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8188 
8189       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8190                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8191     } else {
8192       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8193                                                         SL, MVT::i32);
8194       EnableDenorm =
8195           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8196                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8197     }
8198 
8199     SDValue Ops[3] = {
8200       NegDivScale0,
8201       SDValue(EnableDenorm, 0),
8202       SDValue(EnableDenorm, 1)
8203     };
8204 
8205     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8206   }
8207 
8208   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8209                              ApproxRcp, One, NegDivScale0, Flags);
8210 
8211   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8212                              ApproxRcp, Fma0, Flags);
8213 
8214   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8215                            Fma1, Fma1, Flags);
8216 
8217   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8218                              NumeratorScaled, Mul, Flags);
8219 
8220   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8221                              Fma2, Fma1, Mul, Fma2, Flags);
8222 
8223   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8224                              NumeratorScaled, Fma3, Flags);
8225 
8226   if (!HasFP32Denormals) {
8227     SDNode *DisableDenorm;
8228     if (Subtarget->hasDenormModeInst()) {
8229       const SDValue DisableDenormValue =
8230           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8231 
8232       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8233                                   Fma4.getValue(1), DisableDenormValue,
8234                                   Fma4.getValue(2)).getNode();
8235     } else {
8236       const SDValue DisableDenormValue =
8237           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8238 
8239       DisableDenorm = DAG.getMachineNode(
8240           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8241           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8242     }
8243 
8244     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8245                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8246     DAG.setRoot(OutputChain);
8247   }
8248 
8249   SDValue Scale = NumeratorScaled.getValue(1);
8250   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8251                              {Fma4, Fma1, Fma3, Scale}, Flags);
8252 
8253   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8254 }
8255 
8256 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8257   if (DAG.getTarget().Options.UnsafeFPMath)
8258     return lowerFastUnsafeFDIV(Op, DAG);
8259 
8260   SDLoc SL(Op);
8261   SDValue X = Op.getOperand(0);
8262   SDValue Y = Op.getOperand(1);
8263 
8264   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8265 
8266   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8267 
8268   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8269 
8270   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8271 
8272   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8273 
8274   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8275 
8276   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8277 
8278   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8279 
8280   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8281 
8282   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8283   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8284 
8285   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8286                              NegDivScale0, Mul, DivScale1);
8287 
8288   SDValue Scale;
8289 
8290   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8291     // Workaround a hardware bug on SI where the condition output from div_scale
8292     // is not usable.
8293 
8294     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8295 
8296     // Figure out if the scale to use for div_fmas.
8297     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8298     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8299     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8300     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8301 
8302     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8303     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8304 
8305     SDValue Scale0Hi
8306       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8307     SDValue Scale1Hi
8308       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8309 
8310     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8311     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8312     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8313   } else {
8314     Scale = DivScale1.getValue(1);
8315   }
8316 
8317   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8318                              Fma4, Fma3, Mul, Scale);
8319 
8320   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8321 }
8322 
8323 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8324   EVT VT = Op.getValueType();
8325 
8326   if (VT == MVT::f32)
8327     return LowerFDIV32(Op, DAG);
8328 
8329   if (VT == MVT::f64)
8330     return LowerFDIV64(Op, DAG);
8331 
8332   if (VT == MVT::f16)
8333     return LowerFDIV16(Op, DAG);
8334 
8335   llvm_unreachable("Unexpected type for fdiv");
8336 }
8337 
8338 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8339   SDLoc DL(Op);
8340   StoreSDNode *Store = cast<StoreSDNode>(Op);
8341   EVT VT = Store->getMemoryVT();
8342 
8343   if (VT == MVT::i1) {
8344     return DAG.getTruncStore(Store->getChain(), DL,
8345        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8346        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8347   }
8348 
8349   assert(VT.isVector() &&
8350          Store->getValue().getValueType().getScalarType() == MVT::i32);
8351 
8352   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8353                                       VT, *Store->getMemOperand())) {
8354     return expandUnalignedStore(Store, DAG);
8355   }
8356 
8357   unsigned AS = Store->getAddressSpace();
8358   if (Subtarget->hasLDSMisalignedBug() &&
8359       AS == AMDGPUAS::FLAT_ADDRESS &&
8360       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8361     return SplitVectorStore(Op, DAG);
8362   }
8363 
8364   MachineFunction &MF = DAG.getMachineFunction();
8365   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8366   // If there is a possibilty that flat instruction access scratch memory
8367   // then we need to use the same legalization rules we use for private.
8368   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8369       !Subtarget->hasMultiDwordFlatScratchAddressing())
8370     AS = MFI->hasFlatScratchInit() ?
8371          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8372 
8373   unsigned NumElements = VT.getVectorNumElements();
8374   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8375       AS == AMDGPUAS::FLAT_ADDRESS) {
8376     if (NumElements > 4)
8377       return SplitVectorStore(Op, DAG);
8378     // v3 stores not supported on SI.
8379     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8380       return SplitVectorStore(Op, DAG);
8381     return SDValue();
8382   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8383     switch (Subtarget->getMaxPrivateElementSize()) {
8384     case 4:
8385       return scalarizeVectorStore(Store, DAG);
8386     case 8:
8387       if (NumElements > 2)
8388         return SplitVectorStore(Op, DAG);
8389       return SDValue();
8390     case 16:
8391       if (NumElements > 4 || NumElements == 3)
8392         return SplitVectorStore(Op, DAG);
8393       return SDValue();
8394     default:
8395       llvm_unreachable("unsupported private_element_size");
8396     }
8397   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8398     // Use ds_write_b128 if possible.
8399     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8400         VT.getStoreSize() == 16 && NumElements != 3)
8401       return SDValue();
8402 
8403     if (NumElements > 2)
8404       return SplitVectorStore(Op, DAG);
8405 
8406     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8407     // address is negative, then the instruction is incorrectly treated as
8408     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8409     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8410     // store later in the SILoadStoreOptimizer.
8411     if (!Subtarget->hasUsableDSOffset() &&
8412         NumElements == 2 && VT.getStoreSize() == 8 &&
8413         Store->getAlignment() < 8) {
8414       return SplitVectorStore(Op, DAG);
8415     }
8416 
8417     return SDValue();
8418   } else {
8419     llvm_unreachable("unhandled address space");
8420   }
8421 }
8422 
8423 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8424   SDLoc DL(Op);
8425   EVT VT = Op.getValueType();
8426   SDValue Arg = Op.getOperand(0);
8427   SDValue TrigVal;
8428 
8429   // Propagate fast-math flags so that the multiply we introduce can be folded
8430   // if Arg is already the result of a multiply by constant.
8431   auto Flags = Op->getFlags();
8432 
8433   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8434 
8435   if (Subtarget->hasTrigReducedRange()) {
8436     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8437     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8438   } else {
8439     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8440   }
8441 
8442   switch (Op.getOpcode()) {
8443   case ISD::FCOS:
8444     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8445   case ISD::FSIN:
8446     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8447   default:
8448     llvm_unreachable("Wrong trig opcode");
8449   }
8450 }
8451 
8452 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8453   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8454   assert(AtomicNode->isCompareAndSwap());
8455   unsigned AS = AtomicNode->getAddressSpace();
8456 
8457   // No custom lowering required for local address space
8458   if (!isFlatGlobalAddrSpace(AS))
8459     return Op;
8460 
8461   // Non-local address space requires custom lowering for atomic compare
8462   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8463   SDLoc DL(Op);
8464   SDValue ChainIn = Op.getOperand(0);
8465   SDValue Addr = Op.getOperand(1);
8466   SDValue Old = Op.getOperand(2);
8467   SDValue New = Op.getOperand(3);
8468   EVT VT = Op.getValueType();
8469   MVT SimpleVT = VT.getSimpleVT();
8470   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8471 
8472   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8473   SDValue Ops[] = { ChainIn, Addr, NewOld };
8474 
8475   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8476                                  Ops, VT, AtomicNode->getMemOperand());
8477 }
8478 
8479 //===----------------------------------------------------------------------===//
8480 // Custom DAG optimizations
8481 //===----------------------------------------------------------------------===//
8482 
8483 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8484                                                      DAGCombinerInfo &DCI) const {
8485   EVT VT = N->getValueType(0);
8486   EVT ScalarVT = VT.getScalarType();
8487   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8488     return SDValue();
8489 
8490   SelectionDAG &DAG = DCI.DAG;
8491   SDLoc DL(N);
8492 
8493   SDValue Src = N->getOperand(0);
8494   EVT SrcVT = Src.getValueType();
8495 
8496   // TODO: We could try to match extracting the higher bytes, which would be
8497   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8498   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8499   // about in practice.
8500   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8501     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8502       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8503       DCI.AddToWorklist(Cvt.getNode());
8504 
8505       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8506       if (ScalarVT != MVT::f32) {
8507         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8508                           DAG.getTargetConstant(0, DL, MVT::i32));
8509       }
8510       return Cvt;
8511     }
8512   }
8513 
8514   return SDValue();
8515 }
8516 
8517 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8518 
8519 // This is a variant of
8520 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8521 //
8522 // The normal DAG combiner will do this, but only if the add has one use since
8523 // that would increase the number of instructions.
8524 //
8525 // This prevents us from seeing a constant offset that can be folded into a
8526 // memory instruction's addressing mode. If we know the resulting add offset of
8527 // a pointer can be folded into an addressing offset, we can replace the pointer
8528 // operand with the add of new constant offset. This eliminates one of the uses,
8529 // and may allow the remaining use to also be simplified.
8530 //
8531 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8532                                                unsigned AddrSpace,
8533                                                EVT MemVT,
8534                                                DAGCombinerInfo &DCI) const {
8535   SDValue N0 = N->getOperand(0);
8536   SDValue N1 = N->getOperand(1);
8537 
8538   // We only do this to handle cases where it's profitable when there are
8539   // multiple uses of the add, so defer to the standard combine.
8540   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8541       N0->hasOneUse())
8542     return SDValue();
8543 
8544   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8545   if (!CN1)
8546     return SDValue();
8547 
8548   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8549   if (!CAdd)
8550     return SDValue();
8551 
8552   // If the resulting offset is too large, we can't fold it into the addressing
8553   // mode offset.
8554   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8555   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8556 
8557   AddrMode AM;
8558   AM.HasBaseReg = true;
8559   AM.BaseOffs = Offset.getSExtValue();
8560   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8561     return SDValue();
8562 
8563   SelectionDAG &DAG = DCI.DAG;
8564   SDLoc SL(N);
8565   EVT VT = N->getValueType(0);
8566 
8567   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8568   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8569 
8570   SDNodeFlags Flags;
8571   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8572                           (N0.getOpcode() == ISD::OR ||
8573                            N0->getFlags().hasNoUnsignedWrap()));
8574 
8575   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8576 }
8577 
8578 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8579                                                   DAGCombinerInfo &DCI) const {
8580   SDValue Ptr = N->getBasePtr();
8581   SelectionDAG &DAG = DCI.DAG;
8582   SDLoc SL(N);
8583 
8584   // TODO: We could also do this for multiplies.
8585   if (Ptr.getOpcode() == ISD::SHL) {
8586     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8587                                           N->getMemoryVT(), DCI);
8588     if (NewPtr) {
8589       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8590 
8591       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8592       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8593     }
8594   }
8595 
8596   return SDValue();
8597 }
8598 
8599 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8600   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8601          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8602          (Opc == ISD::XOR && Val == 0);
8603 }
8604 
8605 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8606 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8607 // integer combine opportunities since most 64-bit operations are decomposed
8608 // this way.  TODO: We won't want this for SALU especially if it is an inline
8609 // immediate.
8610 SDValue SITargetLowering::splitBinaryBitConstantOp(
8611   DAGCombinerInfo &DCI,
8612   const SDLoc &SL,
8613   unsigned Opc, SDValue LHS,
8614   const ConstantSDNode *CRHS) const {
8615   uint64_t Val = CRHS->getZExtValue();
8616   uint32_t ValLo = Lo_32(Val);
8617   uint32_t ValHi = Hi_32(Val);
8618   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8619 
8620     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8621          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8622         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8623     // If we need to materialize a 64-bit immediate, it will be split up later
8624     // anyway. Avoid creating the harder to understand 64-bit immediate
8625     // materialization.
8626     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8627   }
8628 
8629   return SDValue();
8630 }
8631 
8632 // Returns true if argument is a boolean value which is not serialized into
8633 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8634 static bool isBoolSGPR(SDValue V) {
8635   if (V.getValueType() != MVT::i1)
8636     return false;
8637   switch (V.getOpcode()) {
8638   default: break;
8639   case ISD::SETCC:
8640   case ISD::AND:
8641   case ISD::OR:
8642   case ISD::XOR:
8643   case AMDGPUISD::FP_CLASS:
8644     return true;
8645   }
8646   return false;
8647 }
8648 
8649 // If a constant has all zeroes or all ones within each byte return it.
8650 // Otherwise return 0.
8651 static uint32_t getConstantPermuteMask(uint32_t C) {
8652   // 0xff for any zero byte in the mask
8653   uint32_t ZeroByteMask = 0;
8654   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8655   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8656   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8657   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8658   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8659   if ((NonZeroByteMask & C) != NonZeroByteMask)
8660     return 0; // Partial bytes selected.
8661   return C;
8662 }
8663 
8664 // Check if a node selects whole bytes from its operand 0 starting at a byte
8665 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8666 // or -1 if not succeeded.
8667 // Note byte select encoding:
8668 // value 0-3 selects corresponding source byte;
8669 // value 0xc selects zero;
8670 // value 0xff selects 0xff.
8671 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8672   assert(V.getValueSizeInBits() == 32);
8673 
8674   if (V.getNumOperands() != 2)
8675     return ~0;
8676 
8677   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8678   if (!N1)
8679     return ~0;
8680 
8681   uint32_t C = N1->getZExtValue();
8682 
8683   switch (V.getOpcode()) {
8684   default:
8685     break;
8686   case ISD::AND:
8687     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8688       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8689     }
8690     break;
8691 
8692   case ISD::OR:
8693     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8694       return (0x03020100 & ~ConstMask) | ConstMask;
8695     }
8696     break;
8697 
8698   case ISD::SHL:
8699     if (C % 8)
8700       return ~0;
8701 
8702     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8703 
8704   case ISD::SRL:
8705     if (C % 8)
8706       return ~0;
8707 
8708     return uint32_t(0x0c0c0c0c03020100ull >> C);
8709   }
8710 
8711   return ~0;
8712 }
8713 
8714 SDValue SITargetLowering::performAndCombine(SDNode *N,
8715                                             DAGCombinerInfo &DCI) const {
8716   if (DCI.isBeforeLegalize())
8717     return SDValue();
8718 
8719   SelectionDAG &DAG = DCI.DAG;
8720   EVT VT = N->getValueType(0);
8721   SDValue LHS = N->getOperand(0);
8722   SDValue RHS = N->getOperand(1);
8723 
8724 
8725   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8726   if (VT == MVT::i64 && CRHS) {
8727     if (SDValue Split
8728         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8729       return Split;
8730   }
8731 
8732   if (CRHS && VT == MVT::i32) {
8733     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8734     // nb = number of trailing zeroes in mask
8735     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8736     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8737     uint64_t Mask = CRHS->getZExtValue();
8738     unsigned Bits = countPopulation(Mask);
8739     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8740         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8741       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8742         unsigned Shift = CShift->getZExtValue();
8743         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8744         unsigned Offset = NB + Shift;
8745         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8746           SDLoc SL(N);
8747           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8748                                     LHS->getOperand(0),
8749                                     DAG.getConstant(Offset, SL, MVT::i32),
8750                                     DAG.getConstant(Bits, SL, MVT::i32));
8751           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8752           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8753                                     DAG.getValueType(NarrowVT));
8754           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8755                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8756           return Shl;
8757         }
8758       }
8759     }
8760 
8761     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8762     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8763         isa<ConstantSDNode>(LHS.getOperand(2))) {
8764       uint32_t Sel = getConstantPermuteMask(Mask);
8765       if (!Sel)
8766         return SDValue();
8767 
8768       // Select 0xc for all zero bytes
8769       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8770       SDLoc DL(N);
8771       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8772                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8773     }
8774   }
8775 
8776   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8777   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8778   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8779     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8780     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8781 
8782     SDValue X = LHS.getOperand(0);
8783     SDValue Y = RHS.getOperand(0);
8784     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8785       return SDValue();
8786 
8787     if (LCC == ISD::SETO) {
8788       if (X != LHS.getOperand(1))
8789         return SDValue();
8790 
8791       if (RCC == ISD::SETUNE) {
8792         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8793         if (!C1 || !C1->isInfinity() || C1->isNegative())
8794           return SDValue();
8795 
8796         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8797                               SIInstrFlags::N_SUBNORMAL |
8798                               SIInstrFlags::N_ZERO |
8799                               SIInstrFlags::P_ZERO |
8800                               SIInstrFlags::P_SUBNORMAL |
8801                               SIInstrFlags::P_NORMAL;
8802 
8803         static_assert(((~(SIInstrFlags::S_NAN |
8804                           SIInstrFlags::Q_NAN |
8805                           SIInstrFlags::N_INFINITY |
8806                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8807                       "mask not equal");
8808 
8809         SDLoc DL(N);
8810         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8811                            X, DAG.getConstant(Mask, DL, MVT::i32));
8812       }
8813     }
8814   }
8815 
8816   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8817     std::swap(LHS, RHS);
8818 
8819   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8820       RHS.hasOneUse()) {
8821     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8822     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8823     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8824     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8825     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8826         (RHS.getOperand(0) == LHS.getOperand(0) &&
8827          LHS.getOperand(0) == LHS.getOperand(1))) {
8828       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8829       unsigned NewMask = LCC == ISD::SETO ?
8830         Mask->getZExtValue() & ~OrdMask :
8831         Mask->getZExtValue() & OrdMask;
8832 
8833       SDLoc DL(N);
8834       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8835                          DAG.getConstant(NewMask, DL, MVT::i32));
8836     }
8837   }
8838 
8839   if (VT == MVT::i32 &&
8840       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8841     // and x, (sext cc from i1) => select cc, x, 0
8842     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8843       std::swap(LHS, RHS);
8844     if (isBoolSGPR(RHS.getOperand(0)))
8845       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8846                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8847   }
8848 
8849   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8850   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8851   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8852       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8853     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8854     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8855     if (LHSMask != ~0u && RHSMask != ~0u) {
8856       // Canonicalize the expression in an attempt to have fewer unique masks
8857       // and therefore fewer registers used to hold the masks.
8858       if (LHSMask > RHSMask) {
8859         std::swap(LHSMask, RHSMask);
8860         std::swap(LHS, RHS);
8861       }
8862 
8863       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8864       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8865       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8866       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8867 
8868       // Check of we need to combine values from two sources within a byte.
8869       if (!(LHSUsedLanes & RHSUsedLanes) &&
8870           // If we select high and lower word keep it for SDWA.
8871           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8872           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8873         // Each byte in each mask is either selector mask 0-3, or has higher
8874         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8875         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8876         // mask which is not 0xff wins. By anding both masks we have a correct
8877         // result except that 0x0c shall be corrected to give 0x0c only.
8878         uint32_t Mask = LHSMask & RHSMask;
8879         for (unsigned I = 0; I < 32; I += 8) {
8880           uint32_t ByteSel = 0xff << I;
8881           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8882             Mask &= (0x0c << I) & 0xffffffff;
8883         }
8884 
8885         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8886         // or 0x0c.
8887         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8888         SDLoc DL(N);
8889 
8890         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8891                            LHS.getOperand(0), RHS.getOperand(0),
8892                            DAG.getConstant(Sel, DL, MVT::i32));
8893       }
8894     }
8895   }
8896 
8897   return SDValue();
8898 }
8899 
8900 SDValue SITargetLowering::performOrCombine(SDNode *N,
8901                                            DAGCombinerInfo &DCI) const {
8902   SelectionDAG &DAG = DCI.DAG;
8903   SDValue LHS = N->getOperand(0);
8904   SDValue RHS = N->getOperand(1);
8905 
8906   EVT VT = N->getValueType(0);
8907   if (VT == MVT::i1) {
8908     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8909     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8910         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8911       SDValue Src = LHS.getOperand(0);
8912       if (Src != RHS.getOperand(0))
8913         return SDValue();
8914 
8915       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8916       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8917       if (!CLHS || !CRHS)
8918         return SDValue();
8919 
8920       // Only 10 bits are used.
8921       static const uint32_t MaxMask = 0x3ff;
8922 
8923       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8924       SDLoc DL(N);
8925       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8926                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8927     }
8928 
8929     return SDValue();
8930   }
8931 
8932   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8933   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8934       LHS.getOpcode() == AMDGPUISD::PERM &&
8935       isa<ConstantSDNode>(LHS.getOperand(2))) {
8936     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8937     if (!Sel)
8938       return SDValue();
8939 
8940     Sel |= LHS.getConstantOperandVal(2);
8941     SDLoc DL(N);
8942     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8943                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8944   }
8945 
8946   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8947   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8948   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8949       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8950     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8951     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8952     if (LHSMask != ~0u && RHSMask != ~0u) {
8953       // Canonicalize the expression in an attempt to have fewer unique masks
8954       // and therefore fewer registers used to hold the masks.
8955       if (LHSMask > RHSMask) {
8956         std::swap(LHSMask, RHSMask);
8957         std::swap(LHS, RHS);
8958       }
8959 
8960       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8961       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8962       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8963       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8964 
8965       // Check of we need to combine values from two sources within a byte.
8966       if (!(LHSUsedLanes & RHSUsedLanes) &&
8967           // If we select high and lower word keep it for SDWA.
8968           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8969           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8970         // Kill zero bytes selected by other mask. Zero value is 0xc.
8971         LHSMask &= ~RHSUsedLanes;
8972         RHSMask &= ~LHSUsedLanes;
8973         // Add 4 to each active LHS lane
8974         LHSMask |= LHSUsedLanes & 0x04040404;
8975         // Combine masks
8976         uint32_t Sel = LHSMask | RHSMask;
8977         SDLoc DL(N);
8978 
8979         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8980                            LHS.getOperand(0), RHS.getOperand(0),
8981                            DAG.getConstant(Sel, DL, MVT::i32));
8982       }
8983     }
8984   }
8985 
8986   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
8987     return SDValue();
8988 
8989   // TODO: This could be a generic combine with a predicate for extracting the
8990   // high half of an integer being free.
8991 
8992   // (or i64:x, (zero_extend i32:y)) ->
8993   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8994   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8995       RHS.getOpcode() != ISD::ZERO_EXTEND)
8996     std::swap(LHS, RHS);
8997 
8998   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8999     SDValue ExtSrc = RHS.getOperand(0);
9000     EVT SrcVT = ExtSrc.getValueType();
9001     if (SrcVT == MVT::i32) {
9002       SDLoc SL(N);
9003       SDValue LowLHS, HiBits;
9004       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9005       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9006 
9007       DCI.AddToWorklist(LowOr.getNode());
9008       DCI.AddToWorklist(HiBits.getNode());
9009 
9010       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9011                                 LowOr, HiBits);
9012       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9013     }
9014   }
9015 
9016   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9017   if (CRHS) {
9018     if (SDValue Split
9019           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9020       return Split;
9021   }
9022 
9023   return SDValue();
9024 }
9025 
9026 SDValue SITargetLowering::performXorCombine(SDNode *N,
9027                                             DAGCombinerInfo &DCI) const {
9028   EVT VT = N->getValueType(0);
9029   if (VT != MVT::i64)
9030     return SDValue();
9031 
9032   SDValue LHS = N->getOperand(0);
9033   SDValue RHS = N->getOperand(1);
9034 
9035   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9036   if (CRHS) {
9037     if (SDValue Split
9038           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9039       return Split;
9040   }
9041 
9042   return SDValue();
9043 }
9044 
9045 // Instructions that will be lowered with a final instruction that zeros the
9046 // high result bits.
9047 // XXX - probably only need to list legal operations.
9048 static bool fp16SrcZerosHighBits(unsigned Opc) {
9049   switch (Opc) {
9050   case ISD::FADD:
9051   case ISD::FSUB:
9052   case ISD::FMUL:
9053   case ISD::FDIV:
9054   case ISD::FREM:
9055   case ISD::FMA:
9056   case ISD::FMAD:
9057   case ISD::FCANONICALIZE:
9058   case ISD::FP_ROUND:
9059   case ISD::UINT_TO_FP:
9060   case ISD::SINT_TO_FP:
9061   case ISD::FABS:
9062     // Fabs is lowered to a bit operation, but it's an and which will clear the
9063     // high bits anyway.
9064   case ISD::FSQRT:
9065   case ISD::FSIN:
9066   case ISD::FCOS:
9067   case ISD::FPOWI:
9068   case ISD::FPOW:
9069   case ISD::FLOG:
9070   case ISD::FLOG2:
9071   case ISD::FLOG10:
9072   case ISD::FEXP:
9073   case ISD::FEXP2:
9074   case ISD::FCEIL:
9075   case ISD::FTRUNC:
9076   case ISD::FRINT:
9077   case ISD::FNEARBYINT:
9078   case ISD::FROUND:
9079   case ISD::FFLOOR:
9080   case ISD::FMINNUM:
9081   case ISD::FMAXNUM:
9082   case AMDGPUISD::FRACT:
9083   case AMDGPUISD::CLAMP:
9084   case AMDGPUISD::COS_HW:
9085   case AMDGPUISD::SIN_HW:
9086   case AMDGPUISD::FMIN3:
9087   case AMDGPUISD::FMAX3:
9088   case AMDGPUISD::FMED3:
9089   case AMDGPUISD::FMAD_FTZ:
9090   case AMDGPUISD::RCP:
9091   case AMDGPUISD::RSQ:
9092   case AMDGPUISD::RCP_IFLAG:
9093   case AMDGPUISD::LDEXP:
9094     return true;
9095   default:
9096     // fcopysign, select and others may be lowered to 32-bit bit operations
9097     // which don't zero the high bits.
9098     return false;
9099   }
9100 }
9101 
9102 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9103                                                    DAGCombinerInfo &DCI) const {
9104   if (!Subtarget->has16BitInsts() ||
9105       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9106     return SDValue();
9107 
9108   EVT VT = N->getValueType(0);
9109   if (VT != MVT::i32)
9110     return SDValue();
9111 
9112   SDValue Src = N->getOperand(0);
9113   if (Src.getValueType() != MVT::i16)
9114     return SDValue();
9115 
9116   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9117   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9118   if (Src.getOpcode() == ISD::BITCAST) {
9119     SDValue BCSrc = Src.getOperand(0);
9120     if (BCSrc.getValueType() == MVT::f16 &&
9121         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9122       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9123   }
9124 
9125   return SDValue();
9126 }
9127 
9128 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9129                                                         DAGCombinerInfo &DCI)
9130                                                         const {
9131   SDValue Src = N->getOperand(0);
9132   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9133 
9134   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9135       VTSign->getVT() == MVT::i8) ||
9136       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9137       VTSign->getVT() == MVT::i16)) &&
9138       Src.hasOneUse()) {
9139     auto *M = cast<MemSDNode>(Src);
9140     SDValue Ops[] = {
9141       Src.getOperand(0), // Chain
9142       Src.getOperand(1), // rsrc
9143       Src.getOperand(2), // vindex
9144       Src.getOperand(3), // voffset
9145       Src.getOperand(4), // soffset
9146       Src.getOperand(5), // offset
9147       Src.getOperand(6),
9148       Src.getOperand(7)
9149     };
9150     // replace with BUFFER_LOAD_BYTE/SHORT
9151     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9152                                          Src.getOperand(0).getValueType());
9153     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9154                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9155     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9156                                                           ResList,
9157                                                           Ops, M->getMemoryVT(),
9158                                                           M->getMemOperand());
9159     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9160                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9161   }
9162   return SDValue();
9163 }
9164 
9165 SDValue SITargetLowering::performClassCombine(SDNode *N,
9166                                               DAGCombinerInfo &DCI) const {
9167   SelectionDAG &DAG = DCI.DAG;
9168   SDValue Mask = N->getOperand(1);
9169 
9170   // fp_class x, 0 -> false
9171   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9172     if (CMask->isNullValue())
9173       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9174   }
9175 
9176   if (N->getOperand(0).isUndef())
9177     return DAG.getUNDEF(MVT::i1);
9178 
9179   return SDValue();
9180 }
9181 
9182 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9183                                             DAGCombinerInfo &DCI) const {
9184   EVT VT = N->getValueType(0);
9185   SDValue N0 = N->getOperand(0);
9186 
9187   if (N0.isUndef())
9188     return N0;
9189 
9190   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9191                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9192     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9193                            N->getFlags());
9194   }
9195 
9196   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9197     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9198                            N0.getOperand(0), N->getFlags());
9199   }
9200 
9201   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9202 }
9203 
9204 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9205                                        unsigned MaxDepth) const {
9206   unsigned Opcode = Op.getOpcode();
9207   if (Opcode == ISD::FCANONICALIZE)
9208     return true;
9209 
9210   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9211     auto F = CFP->getValueAPF();
9212     if (F.isNaN() && F.isSignaling())
9213       return false;
9214     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9215   }
9216 
9217   // If source is a result of another standard FP operation it is already in
9218   // canonical form.
9219   if (MaxDepth == 0)
9220     return false;
9221 
9222   switch (Opcode) {
9223   // These will flush denorms if required.
9224   case ISD::FADD:
9225   case ISD::FSUB:
9226   case ISD::FMUL:
9227   case ISD::FCEIL:
9228   case ISD::FFLOOR:
9229   case ISD::FMA:
9230   case ISD::FMAD:
9231   case ISD::FSQRT:
9232   case ISD::FDIV:
9233   case ISD::FREM:
9234   case ISD::FP_ROUND:
9235   case ISD::FP_EXTEND:
9236   case AMDGPUISD::FMUL_LEGACY:
9237   case AMDGPUISD::FMAD_FTZ:
9238   case AMDGPUISD::RCP:
9239   case AMDGPUISD::RSQ:
9240   case AMDGPUISD::RSQ_CLAMP:
9241   case AMDGPUISD::RCP_LEGACY:
9242   case AMDGPUISD::RCP_IFLAG:
9243   case AMDGPUISD::DIV_SCALE:
9244   case AMDGPUISD::DIV_FMAS:
9245   case AMDGPUISD::DIV_FIXUP:
9246   case AMDGPUISD::FRACT:
9247   case AMDGPUISD::LDEXP:
9248   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9249   case AMDGPUISD::CVT_F32_UBYTE0:
9250   case AMDGPUISD::CVT_F32_UBYTE1:
9251   case AMDGPUISD::CVT_F32_UBYTE2:
9252   case AMDGPUISD::CVT_F32_UBYTE3:
9253     return true;
9254 
9255   // It can/will be lowered or combined as a bit operation.
9256   // Need to check their input recursively to handle.
9257   case ISD::FNEG:
9258   case ISD::FABS:
9259   case ISD::FCOPYSIGN:
9260     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9261 
9262   case ISD::FSIN:
9263   case ISD::FCOS:
9264   case ISD::FSINCOS:
9265     return Op.getValueType().getScalarType() != MVT::f16;
9266 
9267   case ISD::FMINNUM:
9268   case ISD::FMAXNUM:
9269   case ISD::FMINNUM_IEEE:
9270   case ISD::FMAXNUM_IEEE:
9271   case AMDGPUISD::CLAMP:
9272   case AMDGPUISD::FMED3:
9273   case AMDGPUISD::FMAX3:
9274   case AMDGPUISD::FMIN3: {
9275     // FIXME: Shouldn't treat the generic operations different based these.
9276     // However, we aren't really required to flush the result from
9277     // minnum/maxnum..
9278 
9279     // snans will be quieted, so we only need to worry about denormals.
9280     if (Subtarget->supportsMinMaxDenormModes() ||
9281         denormalsEnabledForType(DAG, Op.getValueType()))
9282       return true;
9283 
9284     // Flushing may be required.
9285     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9286     // targets need to check their input recursively.
9287 
9288     // FIXME: Does this apply with clamp? It's implemented with max.
9289     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9290       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9291         return false;
9292     }
9293 
9294     return true;
9295   }
9296   case ISD::SELECT: {
9297     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9298            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9299   }
9300   case ISD::BUILD_VECTOR: {
9301     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9302       SDValue SrcOp = Op.getOperand(i);
9303       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9304         return false;
9305     }
9306 
9307     return true;
9308   }
9309   case ISD::EXTRACT_VECTOR_ELT:
9310   case ISD::EXTRACT_SUBVECTOR: {
9311     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9312   }
9313   case ISD::INSERT_VECTOR_ELT: {
9314     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9315            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9316   }
9317   case ISD::UNDEF:
9318     // Could be anything.
9319     return false;
9320 
9321   case ISD::BITCAST: {
9322     // Hack round the mess we make when legalizing extract_vector_elt
9323     SDValue Src = Op.getOperand(0);
9324     if (Src.getValueType() == MVT::i16 &&
9325         Src.getOpcode() == ISD::TRUNCATE) {
9326       SDValue TruncSrc = Src.getOperand(0);
9327       if (TruncSrc.getValueType() == MVT::i32 &&
9328           TruncSrc.getOpcode() == ISD::BITCAST &&
9329           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9330         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9331       }
9332     }
9333 
9334     return false;
9335   }
9336   case ISD::INTRINSIC_WO_CHAIN: {
9337     unsigned IntrinsicID
9338       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9339     // TODO: Handle more intrinsics
9340     switch (IntrinsicID) {
9341     case Intrinsic::amdgcn_cvt_pkrtz:
9342     case Intrinsic::amdgcn_cubeid:
9343     case Intrinsic::amdgcn_frexp_mant:
9344     case Intrinsic::amdgcn_fdot2:
9345     case Intrinsic::amdgcn_rcp:
9346     case Intrinsic::amdgcn_rsq:
9347     case Intrinsic::amdgcn_rsq_clamp:
9348     case Intrinsic::amdgcn_rcp_legacy:
9349     case Intrinsic::amdgcn_rsq_legacy:
9350     case Intrinsic::amdgcn_trig_preop:
9351       return true;
9352     default:
9353       break;
9354     }
9355 
9356     LLVM_FALLTHROUGH;
9357   }
9358   default:
9359     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9360            DAG.isKnownNeverSNaN(Op);
9361   }
9362 
9363   llvm_unreachable("invalid operation");
9364 }
9365 
9366 // Constant fold canonicalize.
9367 SDValue SITargetLowering::getCanonicalConstantFP(
9368   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9369   // Flush denormals to 0 if not enabled.
9370   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9371     return DAG.getConstantFP(0.0, SL, VT);
9372 
9373   if (C.isNaN()) {
9374     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9375     if (C.isSignaling()) {
9376       // Quiet a signaling NaN.
9377       // FIXME: Is this supposed to preserve payload bits?
9378       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9379     }
9380 
9381     // Make sure it is the canonical NaN bitpattern.
9382     //
9383     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9384     // immediate?
9385     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9386       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9387   }
9388 
9389   // Already canonical.
9390   return DAG.getConstantFP(C, SL, VT);
9391 }
9392 
9393 static bool vectorEltWillFoldAway(SDValue Op) {
9394   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9395 }
9396 
9397 SDValue SITargetLowering::performFCanonicalizeCombine(
9398   SDNode *N,
9399   DAGCombinerInfo &DCI) const {
9400   SelectionDAG &DAG = DCI.DAG;
9401   SDValue N0 = N->getOperand(0);
9402   EVT VT = N->getValueType(0);
9403 
9404   // fcanonicalize undef -> qnan
9405   if (N0.isUndef()) {
9406     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9407     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9408   }
9409 
9410   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9411     EVT VT = N->getValueType(0);
9412     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9413   }
9414 
9415   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9416   //                                                   (fcanonicalize k)
9417   //
9418   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9419 
9420   // TODO: This could be better with wider vectors that will be split to v2f16,
9421   // and to consider uses since there aren't that many packed operations.
9422   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9423       isTypeLegal(MVT::v2f16)) {
9424     SDLoc SL(N);
9425     SDValue NewElts[2];
9426     SDValue Lo = N0.getOperand(0);
9427     SDValue Hi = N0.getOperand(1);
9428     EVT EltVT = Lo.getValueType();
9429 
9430     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9431       for (unsigned I = 0; I != 2; ++I) {
9432         SDValue Op = N0.getOperand(I);
9433         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9434           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9435                                               CFP->getValueAPF());
9436         } else if (Op.isUndef()) {
9437           // Handled below based on what the other operand is.
9438           NewElts[I] = Op;
9439         } else {
9440           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9441         }
9442       }
9443 
9444       // If one half is undef, and one is constant, perfer a splat vector rather
9445       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9446       // cheaper to use and may be free with a packed operation.
9447       if (NewElts[0].isUndef()) {
9448         if (isa<ConstantFPSDNode>(NewElts[1]))
9449           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9450             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9451       }
9452 
9453       if (NewElts[1].isUndef()) {
9454         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9455           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9456       }
9457 
9458       return DAG.getBuildVector(VT, SL, NewElts);
9459     }
9460   }
9461 
9462   unsigned SrcOpc = N0.getOpcode();
9463 
9464   // If it's free to do so, push canonicalizes further up the source, which may
9465   // find a canonical source.
9466   //
9467   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9468   // sNaNs.
9469   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9470     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9471     if (CRHS && N0.hasOneUse()) {
9472       SDLoc SL(N);
9473       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9474                                    N0.getOperand(0));
9475       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9476       DCI.AddToWorklist(Canon0.getNode());
9477 
9478       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9479     }
9480   }
9481 
9482   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9483 }
9484 
9485 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9486   switch (Opc) {
9487   case ISD::FMAXNUM:
9488   case ISD::FMAXNUM_IEEE:
9489     return AMDGPUISD::FMAX3;
9490   case ISD::SMAX:
9491     return AMDGPUISD::SMAX3;
9492   case ISD::UMAX:
9493     return AMDGPUISD::UMAX3;
9494   case ISD::FMINNUM:
9495   case ISD::FMINNUM_IEEE:
9496     return AMDGPUISD::FMIN3;
9497   case ISD::SMIN:
9498     return AMDGPUISD::SMIN3;
9499   case ISD::UMIN:
9500     return AMDGPUISD::UMIN3;
9501   default:
9502     llvm_unreachable("Not a min/max opcode");
9503   }
9504 }
9505 
9506 SDValue SITargetLowering::performIntMed3ImmCombine(
9507   SelectionDAG &DAG, const SDLoc &SL,
9508   SDValue Op0, SDValue Op1, bool Signed) const {
9509   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9510   if (!K1)
9511     return SDValue();
9512 
9513   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9514   if (!K0)
9515     return SDValue();
9516 
9517   if (Signed) {
9518     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9519       return SDValue();
9520   } else {
9521     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9522       return SDValue();
9523   }
9524 
9525   EVT VT = K0->getValueType(0);
9526   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9527   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9528     return DAG.getNode(Med3Opc, SL, VT,
9529                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9530   }
9531 
9532   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9533   MVT NVT = MVT::i32;
9534   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9535 
9536   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9537   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9538   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9539 
9540   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9541   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9542 }
9543 
9544 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9545   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9546     return C;
9547 
9548   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9549     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9550       return C;
9551   }
9552 
9553   return nullptr;
9554 }
9555 
9556 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9557                                                   const SDLoc &SL,
9558                                                   SDValue Op0,
9559                                                   SDValue Op1) const {
9560   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9561   if (!K1)
9562     return SDValue();
9563 
9564   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9565   if (!K0)
9566     return SDValue();
9567 
9568   // Ordered >= (although NaN inputs should have folded away by now).
9569   if (K0->getValueAPF() > K1->getValueAPF())
9570     return SDValue();
9571 
9572   const MachineFunction &MF = DAG.getMachineFunction();
9573   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9574 
9575   // TODO: Check IEEE bit enabled?
9576   EVT VT = Op0.getValueType();
9577   if (Info->getMode().DX10Clamp) {
9578     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9579     // hardware fmed3 behavior converting to a min.
9580     // FIXME: Should this be allowing -0.0?
9581     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9582       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9583   }
9584 
9585   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9586   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9587     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9588     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9589     // then give the other result, which is different from med3 with a NaN
9590     // input.
9591     SDValue Var = Op0.getOperand(0);
9592     if (!DAG.isKnownNeverSNaN(Var))
9593       return SDValue();
9594 
9595     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9596 
9597     if ((!K0->hasOneUse() ||
9598          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9599         (!K1->hasOneUse() ||
9600          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9601       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9602                          Var, SDValue(K0, 0), SDValue(K1, 0));
9603     }
9604   }
9605 
9606   return SDValue();
9607 }
9608 
9609 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9610                                                DAGCombinerInfo &DCI) const {
9611   SelectionDAG &DAG = DCI.DAG;
9612 
9613   EVT VT = N->getValueType(0);
9614   unsigned Opc = N->getOpcode();
9615   SDValue Op0 = N->getOperand(0);
9616   SDValue Op1 = N->getOperand(1);
9617 
9618   // Only do this if the inner op has one use since this will just increases
9619   // register pressure for no benefit.
9620 
9621   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9622       !VT.isVector() &&
9623       (VT == MVT::i32 || VT == MVT::f32 ||
9624        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9625     // max(max(a, b), c) -> max3(a, b, c)
9626     // min(min(a, b), c) -> min3(a, b, c)
9627     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9628       SDLoc DL(N);
9629       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9630                          DL,
9631                          N->getValueType(0),
9632                          Op0.getOperand(0),
9633                          Op0.getOperand(1),
9634                          Op1);
9635     }
9636 
9637     // Try commuted.
9638     // max(a, max(b, c)) -> max3(a, b, c)
9639     // min(a, min(b, c)) -> min3(a, b, c)
9640     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9641       SDLoc DL(N);
9642       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9643                          DL,
9644                          N->getValueType(0),
9645                          Op0,
9646                          Op1.getOperand(0),
9647                          Op1.getOperand(1));
9648     }
9649   }
9650 
9651   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9652   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9653     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9654       return Med3;
9655   }
9656 
9657   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9658     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9659       return Med3;
9660   }
9661 
9662   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9663   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9664        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9665        (Opc == AMDGPUISD::FMIN_LEGACY &&
9666         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9667       (VT == MVT::f32 || VT == MVT::f64 ||
9668        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9669        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9670       Op0.hasOneUse()) {
9671     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9672       return Res;
9673   }
9674 
9675   return SDValue();
9676 }
9677 
9678 static bool isClampZeroToOne(SDValue A, SDValue B) {
9679   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9680     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9681       // FIXME: Should this be allowing -0.0?
9682       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9683              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9684     }
9685   }
9686 
9687   return false;
9688 }
9689 
9690 // FIXME: Should only worry about snans for version with chain.
9691 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9692                                               DAGCombinerInfo &DCI) const {
9693   EVT VT = N->getValueType(0);
9694   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9695   // NaNs. With a NaN input, the order of the operands may change the result.
9696 
9697   SelectionDAG &DAG = DCI.DAG;
9698   SDLoc SL(N);
9699 
9700   SDValue Src0 = N->getOperand(0);
9701   SDValue Src1 = N->getOperand(1);
9702   SDValue Src2 = N->getOperand(2);
9703 
9704   if (isClampZeroToOne(Src0, Src1)) {
9705     // const_a, const_b, x -> clamp is safe in all cases including signaling
9706     // nans.
9707     // FIXME: Should this be allowing -0.0?
9708     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9709   }
9710 
9711   const MachineFunction &MF = DAG.getMachineFunction();
9712   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9713 
9714   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9715   // handling no dx10-clamp?
9716   if (Info->getMode().DX10Clamp) {
9717     // If NaNs is clamped to 0, we are free to reorder the inputs.
9718 
9719     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9720       std::swap(Src0, Src1);
9721 
9722     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9723       std::swap(Src1, Src2);
9724 
9725     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9726       std::swap(Src0, Src1);
9727 
9728     if (isClampZeroToOne(Src1, Src2))
9729       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9730   }
9731 
9732   return SDValue();
9733 }
9734 
9735 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9736                                                  DAGCombinerInfo &DCI) const {
9737   SDValue Src0 = N->getOperand(0);
9738   SDValue Src1 = N->getOperand(1);
9739   if (Src0.isUndef() && Src1.isUndef())
9740     return DCI.DAG.getUNDEF(N->getValueType(0));
9741   return SDValue();
9742 }
9743 
9744 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9745 // expanded into a set of cmp/select instructions.
9746 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9747                                                 unsigned NumElem,
9748                                                 bool IsDivergentIdx) {
9749   if (UseDivergentRegisterIndexing)
9750     return false;
9751 
9752   unsigned VecSize = EltSize * NumElem;
9753 
9754   // Sub-dword vectors of size 2 dword or less have better implementation.
9755   if (VecSize <= 64 && EltSize < 32)
9756     return false;
9757 
9758   // Always expand the rest of sub-dword instructions, otherwise it will be
9759   // lowered via memory.
9760   if (EltSize < 32)
9761     return true;
9762 
9763   // Always do this if var-idx is divergent, otherwise it will become a loop.
9764   if (IsDivergentIdx)
9765     return true;
9766 
9767   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9768   unsigned NumInsts = NumElem /* Number of compares */ +
9769                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9770   return NumInsts <= 16;
9771 }
9772 
9773 static bool shouldExpandVectorDynExt(SDNode *N) {
9774   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9775   if (isa<ConstantSDNode>(Idx))
9776     return false;
9777 
9778   SDValue Vec = N->getOperand(0);
9779   EVT VecVT = Vec.getValueType();
9780   EVT EltVT = VecVT.getVectorElementType();
9781   unsigned EltSize = EltVT.getSizeInBits();
9782   unsigned NumElem = VecVT.getVectorNumElements();
9783 
9784   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9785                                                     Idx->isDivergent());
9786 }
9787 
9788 SDValue SITargetLowering::performExtractVectorEltCombine(
9789   SDNode *N, DAGCombinerInfo &DCI) const {
9790   SDValue Vec = N->getOperand(0);
9791   SelectionDAG &DAG = DCI.DAG;
9792 
9793   EVT VecVT = Vec.getValueType();
9794   EVT EltVT = VecVT.getVectorElementType();
9795 
9796   if ((Vec.getOpcode() == ISD::FNEG ||
9797        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9798     SDLoc SL(N);
9799     EVT EltVT = N->getValueType(0);
9800     SDValue Idx = N->getOperand(1);
9801     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9802                               Vec.getOperand(0), Idx);
9803     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9804   }
9805 
9806   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9807   //    =>
9808   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9809   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9810   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9811   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9812     SDLoc SL(N);
9813     EVT EltVT = N->getValueType(0);
9814     SDValue Idx = N->getOperand(1);
9815     unsigned Opc = Vec.getOpcode();
9816 
9817     switch(Opc) {
9818     default:
9819       break;
9820       // TODO: Support other binary operations.
9821     case ISD::FADD:
9822     case ISD::FSUB:
9823     case ISD::FMUL:
9824     case ISD::ADD:
9825     case ISD::UMIN:
9826     case ISD::UMAX:
9827     case ISD::SMIN:
9828     case ISD::SMAX:
9829     case ISD::FMAXNUM:
9830     case ISD::FMINNUM:
9831     case ISD::FMAXNUM_IEEE:
9832     case ISD::FMINNUM_IEEE: {
9833       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9834                                  Vec.getOperand(0), Idx);
9835       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9836                                  Vec.getOperand(1), Idx);
9837 
9838       DCI.AddToWorklist(Elt0.getNode());
9839       DCI.AddToWorklist(Elt1.getNode());
9840       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9841     }
9842     }
9843   }
9844 
9845   unsigned VecSize = VecVT.getSizeInBits();
9846   unsigned EltSize = EltVT.getSizeInBits();
9847 
9848   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9849   if (::shouldExpandVectorDynExt(N)) {
9850     SDLoc SL(N);
9851     SDValue Idx = N->getOperand(1);
9852     SDValue V;
9853     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9854       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9855       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9856       if (I == 0)
9857         V = Elt;
9858       else
9859         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9860     }
9861     return V;
9862   }
9863 
9864   if (!DCI.isBeforeLegalize())
9865     return SDValue();
9866 
9867   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9868   // elements. This exposes more load reduction opportunities by replacing
9869   // multiple small extract_vector_elements with a single 32-bit extract.
9870   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9871   if (isa<MemSDNode>(Vec) &&
9872       EltSize <= 16 &&
9873       EltVT.isByteSized() &&
9874       VecSize > 32 &&
9875       VecSize % 32 == 0 &&
9876       Idx) {
9877     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9878 
9879     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9880     unsigned EltIdx = BitIndex / 32;
9881     unsigned LeftoverBitIdx = BitIndex % 32;
9882     SDLoc SL(N);
9883 
9884     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9885     DCI.AddToWorklist(Cast.getNode());
9886 
9887     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9888                               DAG.getConstant(EltIdx, SL, MVT::i32));
9889     DCI.AddToWorklist(Elt.getNode());
9890     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9891                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9892     DCI.AddToWorklist(Srl.getNode());
9893 
9894     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9895     DCI.AddToWorklist(Trunc.getNode());
9896     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9897   }
9898 
9899   return SDValue();
9900 }
9901 
9902 SDValue
9903 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9904                                                 DAGCombinerInfo &DCI) const {
9905   SDValue Vec = N->getOperand(0);
9906   SDValue Idx = N->getOperand(2);
9907   EVT VecVT = Vec.getValueType();
9908   EVT EltVT = VecVT.getVectorElementType();
9909 
9910   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9911   // => BUILD_VECTOR n x select (e, const-idx)
9912   if (!::shouldExpandVectorDynExt(N))
9913     return SDValue();
9914 
9915   SelectionDAG &DAG = DCI.DAG;
9916   SDLoc SL(N);
9917   SDValue Ins = N->getOperand(1);
9918   EVT IdxVT = Idx.getValueType();
9919 
9920   SmallVector<SDValue, 16> Ops;
9921   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9922     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9923     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9924     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9925     Ops.push_back(V);
9926   }
9927 
9928   return DAG.getBuildVector(VecVT, SL, Ops);
9929 }
9930 
9931 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9932                                           const SDNode *N0,
9933                                           const SDNode *N1) const {
9934   EVT VT = N0->getValueType(0);
9935 
9936   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9937   // support denormals ever.
9938   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9939        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9940         getSubtarget()->hasMadF16())) &&
9941        isOperationLegal(ISD::FMAD, VT))
9942     return ISD::FMAD;
9943 
9944   const TargetOptions &Options = DAG.getTarget().Options;
9945   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9946        (N0->getFlags().hasAllowContract() &&
9947         N1->getFlags().hasAllowContract())) &&
9948       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9949     return ISD::FMA;
9950   }
9951 
9952   return 0;
9953 }
9954 
9955 // For a reassociatable opcode perform:
9956 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9957 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9958                                                SelectionDAG &DAG) const {
9959   EVT VT = N->getValueType(0);
9960   if (VT != MVT::i32 && VT != MVT::i64)
9961     return SDValue();
9962 
9963   unsigned Opc = N->getOpcode();
9964   SDValue Op0 = N->getOperand(0);
9965   SDValue Op1 = N->getOperand(1);
9966 
9967   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9968     return SDValue();
9969 
9970   if (Op0->isDivergent())
9971     std::swap(Op0, Op1);
9972 
9973   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9974     return SDValue();
9975 
9976   SDValue Op2 = Op1.getOperand(1);
9977   Op1 = Op1.getOperand(0);
9978   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9979     return SDValue();
9980 
9981   if (Op1->isDivergent())
9982     std::swap(Op1, Op2);
9983 
9984   // If either operand is constant this will conflict with
9985   // DAGCombiner::ReassociateOps().
9986   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9987       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9988     return SDValue();
9989 
9990   SDLoc SL(N);
9991   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9992   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9993 }
9994 
9995 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9996                            EVT VT,
9997                            SDValue N0, SDValue N1, SDValue N2,
9998                            bool Signed) {
9999   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10000   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10001   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10002   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10003 }
10004 
10005 SDValue SITargetLowering::performAddCombine(SDNode *N,
10006                                             DAGCombinerInfo &DCI) const {
10007   SelectionDAG &DAG = DCI.DAG;
10008   EVT VT = N->getValueType(0);
10009   SDLoc SL(N);
10010   SDValue LHS = N->getOperand(0);
10011   SDValue RHS = N->getOperand(1);
10012 
10013   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10014       && Subtarget->hasMad64_32() &&
10015       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10016       VT.getScalarSizeInBits() <= 64) {
10017     if (LHS.getOpcode() != ISD::MUL)
10018       std::swap(LHS, RHS);
10019 
10020     SDValue MulLHS = LHS.getOperand(0);
10021     SDValue MulRHS = LHS.getOperand(1);
10022     SDValue AddRHS = RHS;
10023 
10024     // TODO: Maybe restrict if SGPR inputs.
10025     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10026         numBitsUnsigned(MulRHS, DAG) <= 32) {
10027       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10028       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10029       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10030       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10031     }
10032 
10033     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10034       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10035       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10036       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10037       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10038     }
10039 
10040     return SDValue();
10041   }
10042 
10043   if (SDValue V = reassociateScalarOps(N, DAG)) {
10044     return V;
10045   }
10046 
10047   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10048     return SDValue();
10049 
10050   // add x, zext (setcc) => addcarry x, 0, setcc
10051   // add x, sext (setcc) => subcarry x, 0, setcc
10052   unsigned Opc = LHS.getOpcode();
10053   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10054       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10055     std::swap(RHS, LHS);
10056 
10057   Opc = RHS.getOpcode();
10058   switch (Opc) {
10059   default: break;
10060   case ISD::ZERO_EXTEND:
10061   case ISD::SIGN_EXTEND:
10062   case ISD::ANY_EXTEND: {
10063     auto Cond = RHS.getOperand(0);
10064     // If this won't be a real VOPC output, we would still need to insert an
10065     // extra instruction anyway.
10066     if (!isBoolSGPR(Cond))
10067       break;
10068     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10069     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10070     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10071     return DAG.getNode(Opc, SL, VTList, Args);
10072   }
10073   case ISD::ADDCARRY: {
10074     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10075     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10076     if (!C || C->getZExtValue() != 0) break;
10077     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10078     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10079   }
10080   }
10081   return SDValue();
10082 }
10083 
10084 SDValue SITargetLowering::performSubCombine(SDNode *N,
10085                                             DAGCombinerInfo &DCI) const {
10086   SelectionDAG &DAG = DCI.DAG;
10087   EVT VT = N->getValueType(0);
10088 
10089   if (VT != MVT::i32)
10090     return SDValue();
10091 
10092   SDLoc SL(N);
10093   SDValue LHS = N->getOperand(0);
10094   SDValue RHS = N->getOperand(1);
10095 
10096   // sub x, zext (setcc) => subcarry x, 0, setcc
10097   // sub x, sext (setcc) => addcarry x, 0, setcc
10098   unsigned Opc = RHS.getOpcode();
10099   switch (Opc) {
10100   default: break;
10101   case ISD::ZERO_EXTEND:
10102   case ISD::SIGN_EXTEND:
10103   case ISD::ANY_EXTEND: {
10104     auto Cond = RHS.getOperand(0);
10105     // If this won't be a real VOPC output, we would still need to insert an
10106     // extra instruction anyway.
10107     if (!isBoolSGPR(Cond))
10108       break;
10109     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10110     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10111     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10112     return DAG.getNode(Opc, SL, VTList, Args);
10113   }
10114   }
10115 
10116   if (LHS.getOpcode() == ISD::SUBCARRY) {
10117     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10118     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10119     if (!C || !C->isNullValue())
10120       return SDValue();
10121     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10122     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10123   }
10124   return SDValue();
10125 }
10126 
10127 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10128   DAGCombinerInfo &DCI) const {
10129 
10130   if (N->getValueType(0) != MVT::i32)
10131     return SDValue();
10132 
10133   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10134   if (!C || C->getZExtValue() != 0)
10135     return SDValue();
10136 
10137   SelectionDAG &DAG = DCI.DAG;
10138   SDValue LHS = N->getOperand(0);
10139 
10140   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10141   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10142   unsigned LHSOpc = LHS.getOpcode();
10143   unsigned Opc = N->getOpcode();
10144   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10145       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10146     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10147     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10148   }
10149   return SDValue();
10150 }
10151 
10152 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10153                                              DAGCombinerInfo &DCI) const {
10154   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10155     return SDValue();
10156 
10157   SelectionDAG &DAG = DCI.DAG;
10158   EVT VT = N->getValueType(0);
10159 
10160   SDLoc SL(N);
10161   SDValue LHS = N->getOperand(0);
10162   SDValue RHS = N->getOperand(1);
10163 
10164   // These should really be instruction patterns, but writing patterns with
10165   // source modiifiers is a pain.
10166 
10167   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10168   if (LHS.getOpcode() == ISD::FADD) {
10169     SDValue A = LHS.getOperand(0);
10170     if (A == LHS.getOperand(1)) {
10171       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10172       if (FusedOp != 0) {
10173         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10174         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10175       }
10176     }
10177   }
10178 
10179   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10180   if (RHS.getOpcode() == ISD::FADD) {
10181     SDValue A = RHS.getOperand(0);
10182     if (A == RHS.getOperand(1)) {
10183       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10184       if (FusedOp != 0) {
10185         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10186         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10187       }
10188     }
10189   }
10190 
10191   return SDValue();
10192 }
10193 
10194 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10195                                              DAGCombinerInfo &DCI) const {
10196   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10197     return SDValue();
10198 
10199   SelectionDAG &DAG = DCI.DAG;
10200   SDLoc SL(N);
10201   EVT VT = N->getValueType(0);
10202   assert(!VT.isVector());
10203 
10204   // Try to get the fneg to fold into the source modifier. This undoes generic
10205   // DAG combines and folds them into the mad.
10206   //
10207   // Only do this if we are not trying to support denormals. v_mad_f32 does
10208   // not support denormals ever.
10209   SDValue LHS = N->getOperand(0);
10210   SDValue RHS = N->getOperand(1);
10211   if (LHS.getOpcode() == ISD::FADD) {
10212     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10213     SDValue A = LHS.getOperand(0);
10214     if (A == LHS.getOperand(1)) {
10215       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10216       if (FusedOp != 0){
10217         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10218         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10219 
10220         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10221       }
10222     }
10223   }
10224 
10225   if (RHS.getOpcode() == ISD::FADD) {
10226     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10227 
10228     SDValue A = RHS.getOperand(0);
10229     if (A == RHS.getOperand(1)) {
10230       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10231       if (FusedOp != 0){
10232         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10233         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10234       }
10235     }
10236   }
10237 
10238   return SDValue();
10239 }
10240 
10241 SDValue SITargetLowering::performFMACombine(SDNode *N,
10242                                             DAGCombinerInfo &DCI) const {
10243   SelectionDAG &DAG = DCI.DAG;
10244   EVT VT = N->getValueType(0);
10245   SDLoc SL(N);
10246 
10247   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10248     return SDValue();
10249 
10250   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10251   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10252   SDValue Op1 = N->getOperand(0);
10253   SDValue Op2 = N->getOperand(1);
10254   SDValue FMA = N->getOperand(2);
10255 
10256   if (FMA.getOpcode() != ISD::FMA ||
10257       Op1.getOpcode() != ISD::FP_EXTEND ||
10258       Op2.getOpcode() != ISD::FP_EXTEND)
10259     return SDValue();
10260 
10261   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10262   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10263   // is sufficient to allow generaing fdot2.
10264   const TargetOptions &Options = DAG.getTarget().Options;
10265   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10266       (N->getFlags().hasAllowContract() &&
10267        FMA->getFlags().hasAllowContract())) {
10268     Op1 = Op1.getOperand(0);
10269     Op2 = Op2.getOperand(0);
10270     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10271         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10272       return SDValue();
10273 
10274     SDValue Vec1 = Op1.getOperand(0);
10275     SDValue Idx1 = Op1.getOperand(1);
10276     SDValue Vec2 = Op2.getOperand(0);
10277 
10278     SDValue FMAOp1 = FMA.getOperand(0);
10279     SDValue FMAOp2 = FMA.getOperand(1);
10280     SDValue FMAAcc = FMA.getOperand(2);
10281 
10282     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10283         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10284       return SDValue();
10285 
10286     FMAOp1 = FMAOp1.getOperand(0);
10287     FMAOp2 = FMAOp2.getOperand(0);
10288     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10289         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10290       return SDValue();
10291 
10292     SDValue Vec3 = FMAOp1.getOperand(0);
10293     SDValue Vec4 = FMAOp2.getOperand(0);
10294     SDValue Idx2 = FMAOp1.getOperand(1);
10295 
10296     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10297         // Idx1 and Idx2 cannot be the same.
10298         Idx1 == Idx2)
10299       return SDValue();
10300 
10301     if (Vec1 == Vec2 || Vec3 == Vec4)
10302       return SDValue();
10303 
10304     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10305       return SDValue();
10306 
10307     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10308         (Vec1 == Vec4 && Vec2 == Vec3)) {
10309       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10310                          DAG.getTargetConstant(0, SL, MVT::i1));
10311     }
10312   }
10313   return SDValue();
10314 }
10315 
10316 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10317                                               DAGCombinerInfo &DCI) const {
10318   SelectionDAG &DAG = DCI.DAG;
10319   SDLoc SL(N);
10320 
10321   SDValue LHS = N->getOperand(0);
10322   SDValue RHS = N->getOperand(1);
10323   EVT VT = LHS.getValueType();
10324   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10325 
10326   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10327   if (!CRHS) {
10328     CRHS = dyn_cast<ConstantSDNode>(LHS);
10329     if (CRHS) {
10330       std::swap(LHS, RHS);
10331       CC = getSetCCSwappedOperands(CC);
10332     }
10333   }
10334 
10335   if (CRHS) {
10336     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10337         isBoolSGPR(LHS.getOperand(0))) {
10338       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10339       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10340       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10341       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10342       if ((CRHS->isAllOnesValue() &&
10343            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10344           (CRHS->isNullValue() &&
10345            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10346         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10347                            DAG.getConstant(-1, SL, MVT::i1));
10348       if ((CRHS->isAllOnesValue() &&
10349            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10350           (CRHS->isNullValue() &&
10351            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10352         return LHS.getOperand(0);
10353     }
10354 
10355     uint64_t CRHSVal = CRHS->getZExtValue();
10356     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10357         LHS.getOpcode() == ISD::SELECT &&
10358         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10359         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10360         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10361         isBoolSGPR(LHS.getOperand(0))) {
10362       // Given CT != FT:
10363       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10364       // setcc (select cc, CT, CF), CF, ne => cc
10365       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10366       // setcc (select cc, CT, CF), CT, eq => cc
10367       uint64_t CT = LHS.getConstantOperandVal(1);
10368       uint64_t CF = LHS.getConstantOperandVal(2);
10369 
10370       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10371           (CT == CRHSVal && CC == ISD::SETNE))
10372         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10373                            DAG.getConstant(-1, SL, MVT::i1));
10374       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10375           (CT == CRHSVal && CC == ISD::SETEQ))
10376         return LHS.getOperand(0);
10377     }
10378   }
10379 
10380   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10381                                            VT != MVT::f16))
10382     return SDValue();
10383 
10384   // Match isinf/isfinite pattern
10385   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10386   // (fcmp one (fabs x), inf) -> (fp_class x,
10387   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10388   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10389     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10390     if (!CRHS)
10391       return SDValue();
10392 
10393     const APFloat &APF = CRHS->getValueAPF();
10394     if (APF.isInfinity() && !APF.isNegative()) {
10395       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10396                                  SIInstrFlags::N_INFINITY;
10397       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10398                                     SIInstrFlags::P_ZERO |
10399                                     SIInstrFlags::N_NORMAL |
10400                                     SIInstrFlags::P_NORMAL |
10401                                     SIInstrFlags::N_SUBNORMAL |
10402                                     SIInstrFlags::P_SUBNORMAL;
10403       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10404       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10405                          DAG.getConstant(Mask, SL, MVT::i32));
10406     }
10407   }
10408 
10409   return SDValue();
10410 }
10411 
10412 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10413                                                      DAGCombinerInfo &DCI) const {
10414   SelectionDAG &DAG = DCI.DAG;
10415   SDLoc SL(N);
10416   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10417 
10418   SDValue Src = N->getOperand(0);
10419   SDValue Shift = N->getOperand(0);
10420 
10421   // TODO: Extend type shouldn't matter (assuming legal types).
10422   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10423     Shift = Shift.getOperand(0);
10424 
10425   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10426     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10427     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10428     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10429     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10430     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10431     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10432       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10433                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10434 
10435       unsigned ShiftOffset = 8 * Offset;
10436       if (Shift.getOpcode() == ISD::SHL)
10437         ShiftOffset -= C->getZExtValue();
10438       else
10439         ShiftOffset += C->getZExtValue();
10440 
10441       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10442         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10443                            MVT::f32, Shift);
10444       }
10445     }
10446   }
10447 
10448   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10449   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10450   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10451     // We simplified Src. If this node is not dead, visit it again so it is
10452     // folded properly.
10453     if (N->getOpcode() != ISD::DELETED_NODE)
10454       DCI.AddToWorklist(N);
10455     return SDValue(N, 0);
10456   }
10457 
10458   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10459   if (SDValue DemandedSrc =
10460           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10461     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10462 
10463   return SDValue();
10464 }
10465 
10466 SDValue SITargetLowering::performClampCombine(SDNode *N,
10467                                               DAGCombinerInfo &DCI) const {
10468   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10469   if (!CSrc)
10470     return SDValue();
10471 
10472   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10473   const APFloat &F = CSrc->getValueAPF();
10474   APFloat Zero = APFloat::getZero(F.getSemantics());
10475   if (F < Zero ||
10476       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10477     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10478   }
10479 
10480   APFloat One(F.getSemantics(), "1.0");
10481   if (F > One)
10482     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10483 
10484   return SDValue(CSrc, 0);
10485 }
10486 
10487 
10488 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10489                                             DAGCombinerInfo &DCI) const {
10490   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10491     return SDValue();
10492   switch (N->getOpcode()) {
10493   default:
10494     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10495   case ISD::ADD:
10496     return performAddCombine(N, DCI);
10497   case ISD::SUB:
10498     return performSubCombine(N, DCI);
10499   case ISD::ADDCARRY:
10500   case ISD::SUBCARRY:
10501     return performAddCarrySubCarryCombine(N, DCI);
10502   case ISD::FADD:
10503     return performFAddCombine(N, DCI);
10504   case ISD::FSUB:
10505     return performFSubCombine(N, DCI);
10506   case ISD::SETCC:
10507     return performSetCCCombine(N, DCI);
10508   case ISD::FMAXNUM:
10509   case ISD::FMINNUM:
10510   case ISD::FMAXNUM_IEEE:
10511   case ISD::FMINNUM_IEEE:
10512   case ISD::SMAX:
10513   case ISD::SMIN:
10514   case ISD::UMAX:
10515   case ISD::UMIN:
10516   case AMDGPUISD::FMIN_LEGACY:
10517   case AMDGPUISD::FMAX_LEGACY:
10518     return performMinMaxCombine(N, DCI);
10519   case ISD::FMA:
10520     return performFMACombine(N, DCI);
10521   case ISD::LOAD: {
10522     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10523       return Widended;
10524     LLVM_FALLTHROUGH;
10525   }
10526   case ISD::STORE:
10527   case ISD::ATOMIC_LOAD:
10528   case ISD::ATOMIC_STORE:
10529   case ISD::ATOMIC_CMP_SWAP:
10530   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10531   case ISD::ATOMIC_SWAP:
10532   case ISD::ATOMIC_LOAD_ADD:
10533   case ISD::ATOMIC_LOAD_SUB:
10534   case ISD::ATOMIC_LOAD_AND:
10535   case ISD::ATOMIC_LOAD_OR:
10536   case ISD::ATOMIC_LOAD_XOR:
10537   case ISD::ATOMIC_LOAD_NAND:
10538   case ISD::ATOMIC_LOAD_MIN:
10539   case ISD::ATOMIC_LOAD_MAX:
10540   case ISD::ATOMIC_LOAD_UMIN:
10541   case ISD::ATOMIC_LOAD_UMAX:
10542   case ISD::ATOMIC_LOAD_FADD:
10543   case AMDGPUISD::ATOMIC_INC:
10544   case AMDGPUISD::ATOMIC_DEC:
10545   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10546   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10547     if (DCI.isBeforeLegalize())
10548       break;
10549     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10550   case ISD::AND:
10551     return performAndCombine(N, DCI);
10552   case ISD::OR:
10553     return performOrCombine(N, DCI);
10554   case ISD::XOR:
10555     return performXorCombine(N, DCI);
10556   case ISD::ZERO_EXTEND:
10557     return performZeroExtendCombine(N, DCI);
10558   case ISD::SIGN_EXTEND_INREG:
10559     return performSignExtendInRegCombine(N , DCI);
10560   case AMDGPUISD::FP_CLASS:
10561     return performClassCombine(N, DCI);
10562   case ISD::FCANONICALIZE:
10563     return performFCanonicalizeCombine(N, DCI);
10564   case AMDGPUISD::RCP:
10565     return performRcpCombine(N, DCI);
10566   case AMDGPUISD::FRACT:
10567   case AMDGPUISD::RSQ:
10568   case AMDGPUISD::RCP_LEGACY:
10569   case AMDGPUISD::RCP_IFLAG:
10570   case AMDGPUISD::RSQ_CLAMP:
10571   case AMDGPUISD::LDEXP: {
10572     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10573     SDValue Src = N->getOperand(0);
10574     if (Src.isUndef())
10575       return Src;
10576     break;
10577   }
10578   case ISD::SINT_TO_FP:
10579   case ISD::UINT_TO_FP:
10580     return performUCharToFloatCombine(N, DCI);
10581   case AMDGPUISD::CVT_F32_UBYTE0:
10582   case AMDGPUISD::CVT_F32_UBYTE1:
10583   case AMDGPUISD::CVT_F32_UBYTE2:
10584   case AMDGPUISD::CVT_F32_UBYTE3:
10585     return performCvtF32UByteNCombine(N, DCI);
10586   case AMDGPUISD::FMED3:
10587     return performFMed3Combine(N, DCI);
10588   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10589     return performCvtPkRTZCombine(N, DCI);
10590   case AMDGPUISD::CLAMP:
10591     return performClampCombine(N, DCI);
10592   case ISD::SCALAR_TO_VECTOR: {
10593     SelectionDAG &DAG = DCI.DAG;
10594     EVT VT = N->getValueType(0);
10595 
10596     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10597     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10598       SDLoc SL(N);
10599       SDValue Src = N->getOperand(0);
10600       EVT EltVT = Src.getValueType();
10601       if (EltVT == MVT::f16)
10602         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10603 
10604       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10605       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10606     }
10607 
10608     break;
10609   }
10610   case ISD::EXTRACT_VECTOR_ELT:
10611     return performExtractVectorEltCombine(N, DCI);
10612   case ISD::INSERT_VECTOR_ELT:
10613     return performInsertVectorEltCombine(N, DCI);
10614   }
10615   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10616 }
10617 
10618 /// Helper function for adjustWritemask
10619 static unsigned SubIdx2Lane(unsigned Idx) {
10620   switch (Idx) {
10621   default: return 0;
10622   case AMDGPU::sub0: return 0;
10623   case AMDGPU::sub1: return 1;
10624   case AMDGPU::sub2: return 2;
10625   case AMDGPU::sub3: return 3;
10626   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10627   }
10628 }
10629 
10630 /// Adjust the writemask of MIMG instructions
10631 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10632                                           SelectionDAG &DAG) const {
10633   unsigned Opcode = Node->getMachineOpcode();
10634 
10635   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10636   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10637   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10638     return Node; // not implemented for D16
10639 
10640   SDNode *Users[5] = { nullptr };
10641   unsigned Lane = 0;
10642   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10643   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10644   unsigned NewDmask = 0;
10645   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10646   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10647   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10648                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10649   unsigned TFCLane = 0;
10650   bool HasChain = Node->getNumValues() > 1;
10651 
10652   if (OldDmask == 0) {
10653     // These are folded out, but on the chance it happens don't assert.
10654     return Node;
10655   }
10656 
10657   unsigned OldBitsSet = countPopulation(OldDmask);
10658   // Work out which is the TFE/LWE lane if that is enabled.
10659   if (UsesTFC) {
10660     TFCLane = OldBitsSet;
10661   }
10662 
10663   // Try to figure out the used register components
10664   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10665        I != E; ++I) {
10666 
10667     // Don't look at users of the chain.
10668     if (I.getUse().getResNo() != 0)
10669       continue;
10670 
10671     // Abort if we can't understand the usage
10672     if (!I->isMachineOpcode() ||
10673         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10674       return Node;
10675 
10676     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10677     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10678     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10679     // set, etc.
10680     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10681 
10682     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10683     if (UsesTFC && Lane == TFCLane) {
10684       Users[Lane] = *I;
10685     } else {
10686       // Set which texture component corresponds to the lane.
10687       unsigned Comp;
10688       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10689         Comp = countTrailingZeros(Dmask);
10690         Dmask &= ~(1 << Comp);
10691       }
10692 
10693       // Abort if we have more than one user per component.
10694       if (Users[Lane])
10695         return Node;
10696 
10697       Users[Lane] = *I;
10698       NewDmask |= 1 << Comp;
10699     }
10700   }
10701 
10702   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10703   bool NoChannels = !NewDmask;
10704   if (NoChannels) {
10705     if (!UsesTFC) {
10706       // No uses of the result and not using TFC. Then do nothing.
10707       return Node;
10708     }
10709     // If the original dmask has one channel - then nothing to do
10710     if (OldBitsSet == 1)
10711       return Node;
10712     // Use an arbitrary dmask - required for the instruction to work
10713     NewDmask = 1;
10714   }
10715   // Abort if there's no change
10716   if (NewDmask == OldDmask)
10717     return Node;
10718 
10719   unsigned BitsSet = countPopulation(NewDmask);
10720 
10721   // Check for TFE or LWE - increase the number of channels by one to account
10722   // for the extra return value
10723   // This will need adjustment for D16 if this is also included in
10724   // adjustWriteMask (this function) but at present D16 are excluded.
10725   unsigned NewChannels = BitsSet + UsesTFC;
10726 
10727   int NewOpcode =
10728       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10729   assert(NewOpcode != -1 &&
10730          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10731          "failed to find equivalent MIMG op");
10732 
10733   // Adjust the writemask in the node
10734   SmallVector<SDValue, 12> Ops;
10735   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10736   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10737   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10738 
10739   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10740 
10741   MVT ResultVT = NewChannels == 1 ?
10742     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10743                            NewChannels == 5 ? 8 : NewChannels);
10744   SDVTList NewVTList = HasChain ?
10745     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10746 
10747 
10748   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10749                                               NewVTList, Ops);
10750 
10751   if (HasChain) {
10752     // Update chain.
10753     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10754     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10755   }
10756 
10757   if (NewChannels == 1) {
10758     assert(Node->hasNUsesOfValue(1, 0));
10759     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10760                                       SDLoc(Node), Users[Lane]->getValueType(0),
10761                                       SDValue(NewNode, 0));
10762     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10763     return nullptr;
10764   }
10765 
10766   // Update the users of the node with the new indices
10767   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10768     SDNode *User = Users[i];
10769     if (!User) {
10770       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10771       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10772       if (i || !NoChannels)
10773         continue;
10774     } else {
10775       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10776       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10777     }
10778 
10779     switch (Idx) {
10780     default: break;
10781     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10782     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10783     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10784     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10785     }
10786   }
10787 
10788   DAG.RemoveDeadNode(Node);
10789   return nullptr;
10790 }
10791 
10792 static bool isFrameIndexOp(SDValue Op) {
10793   if (Op.getOpcode() == ISD::AssertZext)
10794     Op = Op.getOperand(0);
10795 
10796   return isa<FrameIndexSDNode>(Op);
10797 }
10798 
10799 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10800 /// with frame index operands.
10801 /// LLVM assumes that inputs are to these instructions are registers.
10802 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10803                                                         SelectionDAG &DAG) const {
10804   if (Node->getOpcode() == ISD::CopyToReg) {
10805     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10806     SDValue SrcVal = Node->getOperand(2);
10807 
10808     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10809     // to try understanding copies to physical registers.
10810     if (SrcVal.getValueType() == MVT::i1 &&
10811         Register::isPhysicalRegister(DestReg->getReg())) {
10812       SDLoc SL(Node);
10813       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10814       SDValue VReg = DAG.getRegister(
10815         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10816 
10817       SDNode *Glued = Node->getGluedNode();
10818       SDValue ToVReg
10819         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10820                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10821       SDValue ToResultReg
10822         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10823                            VReg, ToVReg.getValue(1));
10824       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10825       DAG.RemoveDeadNode(Node);
10826       return ToResultReg.getNode();
10827     }
10828   }
10829 
10830   SmallVector<SDValue, 8> Ops;
10831   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10832     if (!isFrameIndexOp(Node->getOperand(i))) {
10833       Ops.push_back(Node->getOperand(i));
10834       continue;
10835     }
10836 
10837     SDLoc DL(Node);
10838     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10839                                      Node->getOperand(i).getValueType(),
10840                                      Node->getOperand(i)), 0));
10841   }
10842 
10843   return DAG.UpdateNodeOperands(Node, Ops);
10844 }
10845 
10846 /// Fold the instructions after selecting them.
10847 /// Returns null if users were already updated.
10848 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10849                                           SelectionDAG &DAG) const {
10850   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10851   unsigned Opcode = Node->getMachineOpcode();
10852 
10853   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10854       !TII->isGather4(Opcode)) {
10855     return adjustWritemask(Node, DAG);
10856   }
10857 
10858   if (Opcode == AMDGPU::INSERT_SUBREG ||
10859       Opcode == AMDGPU::REG_SEQUENCE) {
10860     legalizeTargetIndependentNode(Node, DAG);
10861     return Node;
10862   }
10863 
10864   switch (Opcode) {
10865   case AMDGPU::V_DIV_SCALE_F32:
10866   case AMDGPU::V_DIV_SCALE_F64: {
10867     // Satisfy the operand register constraint when one of the inputs is
10868     // undefined. Ordinarily each undef value will have its own implicit_def of
10869     // a vreg, so force these to use a single register.
10870     SDValue Src0 = Node->getOperand(0);
10871     SDValue Src1 = Node->getOperand(1);
10872     SDValue Src2 = Node->getOperand(2);
10873 
10874     if ((Src0.isMachineOpcode() &&
10875          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10876         (Src0 == Src1 || Src0 == Src2))
10877       break;
10878 
10879     MVT VT = Src0.getValueType().getSimpleVT();
10880     const TargetRegisterClass *RC =
10881         getRegClassFor(VT, Src0.getNode()->isDivergent());
10882 
10883     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10884     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10885 
10886     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10887                                       UndefReg, Src0, SDValue());
10888 
10889     // src0 must be the same register as src1 or src2, even if the value is
10890     // undefined, so make sure we don't violate this constraint.
10891     if (Src0.isMachineOpcode() &&
10892         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10893       if (Src1.isMachineOpcode() &&
10894           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10895         Src0 = Src1;
10896       else if (Src2.isMachineOpcode() &&
10897                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10898         Src0 = Src2;
10899       else {
10900         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10901         Src0 = UndefReg;
10902         Src1 = UndefReg;
10903       }
10904     } else
10905       break;
10906 
10907     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10908     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10909       Ops.push_back(Node->getOperand(I));
10910 
10911     Ops.push_back(ImpDef.getValue(1));
10912     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10913   }
10914   default:
10915     break;
10916   }
10917 
10918   return Node;
10919 }
10920 
10921 /// Assign the register class depending on the number of
10922 /// bits set in the writemask
10923 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10924                                                      SDNode *Node) const {
10925   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10926 
10927   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10928 
10929   if (TII->isVOP3(MI.getOpcode())) {
10930     // Make sure constant bus requirements are respected.
10931     TII->legalizeOperandsVOP3(MRI, MI);
10932 
10933     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10934     // This saves a chain-copy of registers and better ballance register
10935     // use between vgpr and agpr as agpr tuples tend to be big.
10936     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10937       unsigned Opc = MI.getOpcode();
10938       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10939       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10940                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10941         if (I == -1)
10942           break;
10943         MachineOperand &Op = MI.getOperand(I);
10944         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10945              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10946             !Register::isVirtualRegister(Op.getReg()) ||
10947             !TRI->isAGPR(MRI, Op.getReg()))
10948           continue;
10949         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10950         if (!Src || !Src->isCopy() ||
10951             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10952           continue;
10953         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10954         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10955         // All uses of agpr64 and agpr32 can also accept vgpr except for
10956         // v_accvgpr_read, but we do not produce agpr reads during selection,
10957         // so no use checks are needed.
10958         MRI.setRegClass(Op.getReg(), NewRC);
10959       }
10960     }
10961 
10962     return;
10963   }
10964 
10965   // Replace unused atomics with the no return version.
10966   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10967   if (NoRetAtomicOp != -1) {
10968     if (!Node->hasAnyUseOfValue(0)) {
10969       MI.setDesc(TII->get(NoRetAtomicOp));
10970       MI.RemoveOperand(0);
10971       return;
10972     }
10973 
10974     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10975     // instruction, because the return type of these instructions is a vec2 of
10976     // the memory type, so it can be tied to the input operand.
10977     // This means these instructions always have a use, so we need to add a
10978     // special case to check if the atomic has only one extract_subreg use,
10979     // which itself has no uses.
10980     if ((Node->hasNUsesOfValue(1, 0) &&
10981          Node->use_begin()->isMachineOpcode() &&
10982          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10983          !Node->use_begin()->hasAnyUseOfValue(0))) {
10984       Register Def = MI.getOperand(0).getReg();
10985 
10986       // Change this into a noret atomic.
10987       MI.setDesc(TII->get(NoRetAtomicOp));
10988       MI.RemoveOperand(0);
10989 
10990       // If we only remove the def operand from the atomic instruction, the
10991       // extract_subreg will be left with a use of a vreg without a def.
10992       // So we need to insert an implicit_def to avoid machine verifier
10993       // errors.
10994       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10995               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10996     }
10997     return;
10998   }
10999 }
11000 
11001 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11002                               uint64_t Val) {
11003   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11004   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11005 }
11006 
11007 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11008                                                 const SDLoc &DL,
11009                                                 SDValue Ptr) const {
11010   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11011 
11012   // Build the half of the subregister with the constants before building the
11013   // full 128-bit register. If we are building multiple resource descriptors,
11014   // this will allow CSEing of the 2-component register.
11015   const SDValue Ops0[] = {
11016     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11017     buildSMovImm32(DAG, DL, 0),
11018     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11019     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11020     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11021   };
11022 
11023   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11024                                                 MVT::v2i32, Ops0), 0);
11025 
11026   // Combine the constants and the pointer.
11027   const SDValue Ops1[] = {
11028     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11029     Ptr,
11030     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11031     SubRegHi,
11032     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11033   };
11034 
11035   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11036 }
11037 
11038 /// Return a resource descriptor with the 'Add TID' bit enabled
11039 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11040 ///        of the resource descriptor) to create an offset, which is added to
11041 ///        the resource pointer.
11042 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11043                                            SDValue Ptr, uint32_t RsrcDword1,
11044                                            uint64_t RsrcDword2And3) const {
11045   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11046   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11047   if (RsrcDword1) {
11048     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11049                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11050                     0);
11051   }
11052 
11053   SDValue DataLo = buildSMovImm32(DAG, DL,
11054                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11055   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11056 
11057   const SDValue Ops[] = {
11058     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11059     PtrLo,
11060     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11061     PtrHi,
11062     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11063     DataLo,
11064     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11065     DataHi,
11066     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11067   };
11068 
11069   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11070 }
11071 
11072 //===----------------------------------------------------------------------===//
11073 //                         SI Inline Assembly Support
11074 //===----------------------------------------------------------------------===//
11075 
11076 std::pair<unsigned, const TargetRegisterClass *>
11077 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11078                                                StringRef Constraint,
11079                                                MVT VT) const {
11080   const TargetRegisterClass *RC = nullptr;
11081   if (Constraint.size() == 1) {
11082     const unsigned BitWidth = VT.getSizeInBits();
11083     switch (Constraint[0]) {
11084     default:
11085       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11086     case 's':
11087     case 'r':
11088       switch (BitWidth) {
11089       case 16:
11090         RC = &AMDGPU::SReg_32RegClass;
11091         break;
11092       case 64:
11093         RC = &AMDGPU::SGPR_64RegClass;
11094         break;
11095       default:
11096         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11097         if (!RC)
11098           return std::make_pair(0U, nullptr);
11099         break;
11100       }
11101       break;
11102     case 'v':
11103       switch (BitWidth) {
11104       case 16:
11105         RC = &AMDGPU::VGPR_32RegClass;
11106         break;
11107       default:
11108         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11109         if (!RC)
11110           return std::make_pair(0U, nullptr);
11111         break;
11112       }
11113       break;
11114     case 'a':
11115       if (!Subtarget->hasMAIInsts())
11116         break;
11117       switch (BitWidth) {
11118       case 16:
11119         RC = &AMDGPU::AGPR_32RegClass;
11120         break;
11121       default:
11122         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11123         if (!RC)
11124           return std::make_pair(0U, nullptr);
11125         break;
11126       }
11127       break;
11128     }
11129     // We actually support i128, i16 and f16 as inline parameters
11130     // even if they are not reported as legal
11131     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11132                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11133       return std::make_pair(0U, RC);
11134   }
11135 
11136   if (Constraint.size() > 1) {
11137     if (Constraint[1] == 'v') {
11138       RC = &AMDGPU::VGPR_32RegClass;
11139     } else if (Constraint[1] == 's') {
11140       RC = &AMDGPU::SGPR_32RegClass;
11141     } else if (Constraint[1] == 'a') {
11142       RC = &AMDGPU::AGPR_32RegClass;
11143     }
11144 
11145     if (RC) {
11146       uint32_t Idx;
11147       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11148       if (!Failed && Idx < RC->getNumRegs())
11149         return std::make_pair(RC->getRegister(Idx), RC);
11150     }
11151   }
11152 
11153   // FIXME: Returns VS_32 for physical SGPR constraints
11154   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11155 }
11156 
11157 SITargetLowering::ConstraintType
11158 SITargetLowering::getConstraintType(StringRef Constraint) const {
11159   if (Constraint.size() == 1) {
11160     switch (Constraint[0]) {
11161     default: break;
11162     case 's':
11163     case 'v':
11164     case 'a':
11165       return C_RegisterClass;
11166     case 'A':
11167       return C_Other;
11168     }
11169   }
11170   return TargetLowering::getConstraintType(Constraint);
11171 }
11172 
11173 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11174                                                     std::string &Constraint,
11175                                                     std::vector<SDValue> &Ops,
11176                                                     SelectionDAG &DAG) const {
11177   if (Constraint.length() == 1 && Constraint[0] == 'A') {
11178     LowerAsmOperandForConstraintA(Op, Ops, DAG);
11179   } else {
11180     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11181   }
11182 }
11183 
11184 void SITargetLowering::LowerAsmOperandForConstraintA(SDValue Op,
11185                                                      std::vector<SDValue> &Ops,
11186                                                      SelectionDAG &DAG) const {
11187   unsigned Size = Op.getScalarValueSizeInBits();
11188   if (Size > 64)
11189     return;
11190 
11191   uint64_t Val;
11192   bool IsConst = false;
11193   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11194     Val = C->getSExtValue();
11195     IsConst = true;
11196   } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11197     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11198     IsConst = true;
11199   } else if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11200     if (Size != 16 || Op.getNumOperands() != 2)
11201       return;
11202     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11203       return;
11204     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11205       Val = C->getSExtValue();
11206       IsConst = true;
11207     } else if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11208       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11209       IsConst = true;
11210     }
11211   }
11212 
11213   if (IsConst) {
11214     bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11215     if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11216         (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11217         (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11218       // Clear unused bits of fp constants
11219       if (!AMDGPU::isInlinableIntLiteral(Val)) {
11220         unsigned UnusedBits = 64 - Size;
11221         Val = (Val << UnusedBits) >> UnusedBits;
11222       }
11223       auto Res = DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64);
11224       Ops.push_back(Res);
11225     }
11226   }
11227 }
11228 
11229 // Figure out which registers should be reserved for stack access. Only after
11230 // the function is legalized do we know all of the non-spill stack objects or if
11231 // calls are present.
11232 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11233   MachineRegisterInfo &MRI = MF.getRegInfo();
11234   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11235   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11236   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11237 
11238   if (Info->isEntryFunction()) {
11239     // Callable functions have fixed registers used for stack access.
11240     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11241   }
11242 
11243   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11244                              Info->getStackPtrOffsetReg()));
11245   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11246     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11247 
11248   // We need to worry about replacing the default register with itself in case
11249   // of MIR testcases missing the MFI.
11250   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11251     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11252 
11253   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11254     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11255 
11256   Info->limitOccupancy(MF);
11257 
11258   if (ST.isWave32() && !MF.empty()) {
11259     // Add VCC_HI def because many instructions marked as imp-use VCC where
11260     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11261     // having a use of undef.
11262 
11263     const SIInstrInfo *TII = ST.getInstrInfo();
11264     DebugLoc DL;
11265 
11266     MachineBasicBlock &MBB = MF.front();
11267     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11268     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11269 
11270     for (auto &MBB : MF) {
11271       for (auto &MI : MBB) {
11272         TII->fixImplicitOperands(MI);
11273       }
11274     }
11275   }
11276 
11277   TargetLoweringBase::finalizeLowering(MF);
11278 
11279   // Allocate a VGPR for future SGPR Spill if
11280   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11281   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11282   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11283       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11284     Info->reserveVGPRforSGPRSpills(MF);
11285 }
11286 
11287 void SITargetLowering::computeKnownBitsForFrameIndex(
11288   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11289   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11290 
11291   // Set the high bits to zero based on the maximum allowed scratch size per
11292   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11293   // calculation won't overflow, so assume the sign bit is never set.
11294   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11295 }
11296 
11297 Align SITargetLowering::computeKnownAlignForTargetInstr(
11298   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11299   unsigned Depth) const {
11300   const MachineInstr *MI = MRI.getVRegDef(R);
11301   switch (MI->getOpcode()) {
11302   case AMDGPU::G_INTRINSIC:
11303   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11304     // FIXME: Can this move to generic code? What about the case where the call
11305     // site specifies a lower alignment?
11306     Intrinsic::ID IID = MI->getIntrinsicID();
11307     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11308     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11309     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11310       return *RetAlign;
11311     return Align(1);
11312   }
11313   default:
11314     return Align(1);
11315   }
11316 }
11317 
11318 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11319   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11320   const Align CacheLineAlign = Align(64);
11321 
11322   // Pre-GFX10 target did not benefit from loop alignment
11323   if (!ML || DisableLoopAlignment ||
11324       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11325       getSubtarget()->hasInstFwdPrefetchBug())
11326     return PrefAlign;
11327 
11328   // On GFX10 I$ is 4 x 64 bytes cache lines.
11329   // By default prefetcher keeps one cache line behind and reads two ahead.
11330   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11331   // behind and one ahead.
11332   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11333   // If loop fits 64 bytes it always spans no more than two cache lines and
11334   // does not need an alignment.
11335   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11336   // Else if loop is less or equal 192 bytes we need two lines behind.
11337 
11338   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11339   const MachineBasicBlock *Header = ML->getHeader();
11340   if (Header->getAlignment() != PrefAlign)
11341     return Header->getAlignment(); // Already processed.
11342 
11343   unsigned LoopSize = 0;
11344   for (const MachineBasicBlock *MBB : ML->blocks()) {
11345     // If inner loop block is aligned assume in average half of the alignment
11346     // size to be added as nops.
11347     if (MBB != Header)
11348       LoopSize += MBB->getAlignment().value() / 2;
11349 
11350     for (const MachineInstr &MI : *MBB) {
11351       LoopSize += TII->getInstSizeInBytes(MI);
11352       if (LoopSize > 192)
11353         return PrefAlign;
11354     }
11355   }
11356 
11357   if (LoopSize <= 64)
11358     return PrefAlign;
11359 
11360   if (LoopSize <= 128)
11361     return CacheLineAlign;
11362 
11363   // If any of parent loops is surrounded by prefetch instructions do not
11364   // insert new for inner loop, which would reset parent's settings.
11365   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11366     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11367       auto I = Exit->getFirstNonDebugInstr();
11368       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11369         return CacheLineAlign;
11370     }
11371   }
11372 
11373   MachineBasicBlock *Pre = ML->getLoopPreheader();
11374   MachineBasicBlock *Exit = ML->getExitBlock();
11375 
11376   if (Pre && Exit) {
11377     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11378             TII->get(AMDGPU::S_INST_PREFETCH))
11379       .addImm(1); // prefetch 2 lines behind PC
11380 
11381     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11382             TII->get(AMDGPU::S_INST_PREFETCH))
11383       .addImm(2); // prefetch 1 line behind PC
11384   }
11385 
11386   return CacheLineAlign;
11387 }
11388 
11389 LLVM_ATTRIBUTE_UNUSED
11390 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11391   assert(N->getOpcode() == ISD::CopyFromReg);
11392   do {
11393     // Follow the chain until we find an INLINEASM node.
11394     N = N->getOperand(0).getNode();
11395     if (N->getOpcode() == ISD::INLINEASM ||
11396         N->getOpcode() == ISD::INLINEASM_BR)
11397       return true;
11398   } while (N->getOpcode() == ISD::CopyFromReg);
11399   return false;
11400 }
11401 
11402 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11403   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11404 {
11405   switch (N->getOpcode()) {
11406     case ISD::CopyFromReg:
11407     {
11408       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11409       const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11410       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11411       Register Reg = R->getReg();
11412 
11413       // FIXME: Why does this need to consider isLiveIn?
11414       if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11415         return !TRI->isSGPRReg(MRI, Reg);
11416 
11417       if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11418         return KDA->isDivergent(V);
11419 
11420       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11421       return !TRI->isSGPRReg(MRI, Reg);
11422     }
11423     break;
11424     case ISD::LOAD: {
11425       const LoadSDNode *L = cast<LoadSDNode>(N);
11426       unsigned AS = L->getAddressSpace();
11427       // A flat load may access private memory.
11428       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11429     } break;
11430     case ISD::CALLSEQ_END:
11431     return true;
11432     break;
11433     case ISD::INTRINSIC_WO_CHAIN:
11434     {
11435 
11436     }
11437       return AMDGPU::isIntrinsicSourceOfDivergence(
11438       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11439     case ISD::INTRINSIC_W_CHAIN:
11440       return AMDGPU::isIntrinsicSourceOfDivergence(
11441       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11442   }
11443   return false;
11444 }
11445 
11446 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11447                                                EVT VT) const {
11448   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11449   case MVT::f32:
11450     return hasFP32Denormals(DAG.getMachineFunction());
11451   case MVT::f64:
11452   case MVT::f16:
11453     return hasFP64FP16Denormals(DAG.getMachineFunction());
11454   default:
11455     return false;
11456   }
11457 }
11458 
11459 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11460                                                     const SelectionDAG &DAG,
11461                                                     bool SNaN,
11462                                                     unsigned Depth) const {
11463   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11464     const MachineFunction &MF = DAG.getMachineFunction();
11465     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11466 
11467     if (Info->getMode().DX10Clamp)
11468       return true; // Clamped to 0.
11469     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11470   }
11471 
11472   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11473                                                             SNaN, Depth);
11474 }
11475 
11476 TargetLowering::AtomicExpansionKind
11477 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11478   switch (RMW->getOperation()) {
11479   case AtomicRMWInst::FAdd: {
11480     Type *Ty = RMW->getType();
11481 
11482     // We don't have a way to support 16-bit atomics now, so just leave them
11483     // as-is.
11484     if (Ty->isHalfTy())
11485       return AtomicExpansionKind::None;
11486 
11487     if (!Ty->isFloatTy())
11488       return AtomicExpansionKind::CmpXChg;
11489 
11490     // TODO: Do have these for flat. Older targets also had them for buffers.
11491     unsigned AS = RMW->getPointerAddressSpace();
11492 
11493     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11494       return RMW->use_empty() ? AtomicExpansionKind::None :
11495                                 AtomicExpansionKind::CmpXChg;
11496     }
11497 
11498     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11499       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11500   }
11501   default:
11502     break;
11503   }
11504 
11505   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11506 }
11507 
11508 const TargetRegisterClass *
11509 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11510   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11511   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11512   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11513     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11514                                                : &AMDGPU::SReg_32RegClass;
11515   if (!TRI->isSGPRClass(RC) && !isDivergent)
11516     return TRI->getEquivalentSGPRClass(RC);
11517   else if (TRI->isSGPRClass(RC) && isDivergent)
11518     return TRI->getEquivalentVGPRClass(RC);
11519 
11520   return RC;
11521 }
11522 
11523 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11524 // uniform values (as produced by the mask results of control flow intrinsics)
11525 // used outside of divergent blocks. The phi users need to also be treated as
11526 // always uniform.
11527 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11528                       unsigned WaveSize) {
11529   // FIXME: We asssume we never cast the mask results of a control flow
11530   // intrinsic.
11531   // Early exit if the type won't be consistent as a compile time hack.
11532   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11533   if (!IT || IT->getBitWidth() != WaveSize)
11534     return false;
11535 
11536   if (!isa<Instruction>(V))
11537     return false;
11538   if (!Visited.insert(V).second)
11539     return false;
11540   bool Result = false;
11541   for (auto U : V->users()) {
11542     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11543       if (V == U->getOperand(1)) {
11544         switch (Intrinsic->getIntrinsicID()) {
11545         default:
11546           Result = false;
11547           break;
11548         case Intrinsic::amdgcn_if_break:
11549         case Intrinsic::amdgcn_if:
11550         case Intrinsic::amdgcn_else:
11551           Result = true;
11552           break;
11553         }
11554       }
11555       if (V == U->getOperand(0)) {
11556         switch (Intrinsic->getIntrinsicID()) {
11557         default:
11558           Result = false;
11559           break;
11560         case Intrinsic::amdgcn_end_cf:
11561         case Intrinsic::amdgcn_loop:
11562           Result = true;
11563           break;
11564         }
11565       }
11566     } else {
11567       Result = hasCFUser(U, Visited, WaveSize);
11568     }
11569     if (Result)
11570       break;
11571   }
11572   return Result;
11573 }
11574 
11575 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11576                                                const Value *V) const {
11577   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11578     if (CI->isInlineAsm()) {
11579       // FIXME: This cannot give a correct answer. This should only trigger in
11580       // the case where inline asm returns mixed SGPR and VGPR results, used
11581       // outside the defining block. We don't have a specific result to
11582       // consider, so this assumes if any value is SGPR, the overall register
11583       // also needs to be SGPR.
11584       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11585       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11586           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11587       for (auto &TC : TargetConstraints) {
11588         if (TC.Type == InlineAsm::isOutput) {
11589           ComputeConstraintToUse(TC, SDValue());
11590           unsigned AssignedReg;
11591           const TargetRegisterClass *RC;
11592           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11593               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11594           if (RC) {
11595             MachineRegisterInfo &MRI = MF.getRegInfo();
11596             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11597               return true;
11598             else if (SIRI->isSGPRClass(RC))
11599               return true;
11600           }
11601         }
11602       }
11603     }
11604   }
11605   SmallPtrSet<const Value *, 16> Visited;
11606   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11607 }
11608