1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// Custom DAG lowering for SI
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #ifdef _MSC_VER
16 // Provide M_PI.
17 #define _USE_MATH_DEFINES
18 #endif
19 
20 #include "SIISelLowering.h"
21 #include "AMDGPU.h"
22 #include "AMDGPUIntrinsicInfo.h"
23 #include "AMDGPUSubtarget.h"
24 #include "AMDGPUTargetMachine.h"
25 #include "SIDefines.h"
26 #include "SIInstrInfo.h"
27 #include "SIMachineFunctionInfo.h"
28 #include "SIRegisterInfo.h"
29 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
30 #include "Utils/AMDGPUBaseInfo.h"
31 #include "llvm/ADT/APFloat.h"
32 #include "llvm/ADT/APInt.h"
33 #include "llvm/ADT/ArrayRef.h"
34 #include "llvm/ADT/BitVector.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/ADT/Twine.h"
40 #include "llvm/CodeGen/Analysis.h"
41 #include "llvm/CodeGen/CallingConvLower.h"
42 #include "llvm/CodeGen/DAGCombine.h"
43 #include "llvm/CodeGen/ISDOpcodes.h"
44 #include "llvm/CodeGen/MachineBasicBlock.h"
45 #include "llvm/CodeGen/MachineFrameInfo.h"
46 #include "llvm/CodeGen/MachineFunction.h"
47 #include "llvm/CodeGen/MachineInstr.h"
48 #include "llvm/CodeGen/MachineInstrBuilder.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/TargetCallingConv.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Target/TargetOptions.h"
79 #include <cassert>
80 #include <cmath>
81 #include <cstdint>
82 #include <iterator>
83 #include <tuple>
84 #include <utility>
85 #include <vector>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "si-lower"
90 
91 STATISTIC(NumTailCalls, "Number of tail calls");
92 
93 static cl::opt<bool> EnableVGPRIndexMode(
94   "amdgpu-vgpr-index-mode",
95   cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
96   cl::init(false));
97 
98 static cl::opt<unsigned> AssumeFrameIndexHighZeroBits(
99   "amdgpu-frame-index-zero-bits",
100   cl::desc("High bits of frame index assumed to be zero"),
101   cl::init(5),
102   cl::ReallyHidden);
103 
104 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
105   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
106   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
107     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
108       return AMDGPU::SGPR0 + Reg;
109     }
110   }
111   llvm_unreachable("Cannot allocate sgpr");
112 }
113 
114 SITargetLowering::SITargetLowering(const TargetMachine &TM,
115                                    const SISubtarget &STI)
116     : AMDGPUTargetLowering(TM, STI) {
117   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
118   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
119 
120   addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
121   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
122 
123   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
124   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
125   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
126 
127   addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
128   addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
129 
130   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
131   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
132 
133   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
134   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
135 
136   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
137   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
138 
139   if (Subtarget->has16BitInsts()) {
140     addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
141     addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
142 
143     // Unless there are also VOP3P operations, not operations are really legal.
144     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
145     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
146     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
147     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
148   }
149 
150   computeRegisterProperties(STI.getRegisterInfo());
151 
152   // We need to custom lower vector stores from local memory
153   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
154   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
155   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
156   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
157   setOperationAction(ISD::LOAD, MVT::i1, Custom);
158 
159   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
160   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
161   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
162   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
163   setOperationAction(ISD::STORE, MVT::i1, Custom);
164 
165   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
166   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
167   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
168   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
169   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
170   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
171   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
172   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
173   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
174   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
175 
176   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
177   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
178 
179   setOperationAction(ISD::SELECT, MVT::i1, Promote);
180   setOperationAction(ISD::SELECT, MVT::i64, Custom);
181   setOperationAction(ISD::SELECT, MVT::f64, Promote);
182   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
183 
184   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
185   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
186   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
187   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
188   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
189 
190   setOperationAction(ISD::SETCC, MVT::i1, Promote);
191   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
192   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
193   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
194 
195   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
196   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
197 
198   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
199   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
200   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
201   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
202   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
203   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
204   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
205 
206   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
207   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
208   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
209   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
210   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
211 
212   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
213   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
214   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
215 
216   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
217   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
218   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
219   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
220 
221   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
222   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
223   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
224   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
225   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
226   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
227 
228   setOperationAction(ISD::UADDO, MVT::i32, Legal);
229   setOperationAction(ISD::USUBO, MVT::i32, Legal);
230 
231   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
232   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
233 
234 #if 0
235   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
236   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
237 #endif
238 
239   // We only support LOAD/STORE and vector manipulation ops for vectors
240   // with > 4 elements.
241   for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
242         MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16 }) {
243     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
244       switch (Op) {
245       case ISD::LOAD:
246       case ISD::STORE:
247       case ISD::BUILD_VECTOR:
248       case ISD::BITCAST:
249       case ISD::EXTRACT_VECTOR_ELT:
250       case ISD::INSERT_VECTOR_ELT:
251       case ISD::INSERT_SUBVECTOR:
252       case ISD::EXTRACT_SUBVECTOR:
253       case ISD::SCALAR_TO_VECTOR:
254         break;
255       case ISD::CONCAT_VECTORS:
256         setOperationAction(Op, VT, Custom);
257         break;
258       default:
259         setOperationAction(Op, VT, Expand);
260         break;
261       }
262     }
263   }
264 
265   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
266 
267   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
268   // is expanded to avoid having two separate loops in case the index is a VGPR.
269 
270   // Most operations are naturally 32-bit vector operations. We only support
271   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
272   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
273     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
274     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
275 
276     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
277     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
278 
279     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
280     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
281 
282     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
283     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
284   }
285 
286   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
287   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
288   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
289   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
290 
291   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
292   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
293 
294   // Avoid stack access for these.
295   // TODO: Generalize to more vector types.
296   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
297   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
298   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
299   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
300 
301   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
302   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
303   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
304   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
305   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
306 
307   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
308   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
309   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
310 
311   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
312   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
313   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
314   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
315 
316   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
317   // and output demarshalling
318   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
319   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
320 
321   // We can't return success/failure, only the old value,
322   // let LLVM add the comparison
323   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
324   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
325 
326   if (getSubtarget()->hasFlatAddressSpace()) {
327     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
328     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
329   }
330 
331   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
332   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
333 
334   // On SI this is s_memtime and s_memrealtime on VI.
335   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
336   setOperationAction(ISD::TRAP, MVT::Other, Custom);
337   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
338 
339   setOperationAction(ISD::FMINNUM, MVT::f64, Legal);
340   setOperationAction(ISD::FMAXNUM, MVT::f64, Legal);
341 
342   if (Subtarget->getGeneration() >= SISubtarget::SEA_ISLANDS) {
343     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
344     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
345     setOperationAction(ISD::FRINT, MVT::f64, Legal);
346   }
347 
348   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
349 
350   setOperationAction(ISD::FSIN, MVT::f32, Custom);
351   setOperationAction(ISD::FCOS, MVT::f32, Custom);
352   setOperationAction(ISD::FDIV, MVT::f32, Custom);
353   setOperationAction(ISD::FDIV, MVT::f64, Custom);
354 
355   if (Subtarget->has16BitInsts()) {
356     setOperationAction(ISD::Constant, MVT::i16, Legal);
357 
358     setOperationAction(ISD::SMIN, MVT::i16, Legal);
359     setOperationAction(ISD::SMAX, MVT::i16, Legal);
360 
361     setOperationAction(ISD::UMIN, MVT::i16, Legal);
362     setOperationAction(ISD::UMAX, MVT::i16, Legal);
363 
364     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
365     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
366 
367     setOperationAction(ISD::ROTR, MVT::i16, Promote);
368     setOperationAction(ISD::ROTL, MVT::i16, Promote);
369 
370     setOperationAction(ISD::SDIV, MVT::i16, Promote);
371     setOperationAction(ISD::UDIV, MVT::i16, Promote);
372     setOperationAction(ISD::SREM, MVT::i16, Promote);
373     setOperationAction(ISD::UREM, MVT::i16, Promote);
374 
375     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
376     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
377 
378     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
379     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
380     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
381     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
382     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
383 
384     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
385 
386     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
387 
388     setOperationAction(ISD::LOAD, MVT::i16, Custom);
389 
390     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
391 
392     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
393     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
394     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
395     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
396 
397     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
398     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
399     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
400     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
401 
402     // F16 - Constant Actions.
403     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
404 
405     // F16 - Load/Store Actions.
406     setOperationAction(ISD::LOAD, MVT::f16, Promote);
407     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
408     setOperationAction(ISD::STORE, MVT::f16, Promote);
409     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
410 
411     // F16 - VOP1 Actions.
412     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
413     setOperationAction(ISD::FCOS, MVT::f16, Promote);
414     setOperationAction(ISD::FSIN, MVT::f16, Promote);
415     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
416     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
417     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
418     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
419     setOperationAction(ISD::FROUND, MVT::f16, Custom);
420 
421     // F16 - VOP2 Actions.
422     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
423     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
424     setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
425     setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
426     setOperationAction(ISD::FDIV, MVT::f16, Custom);
427 
428     // F16 - VOP3 Actions.
429     setOperationAction(ISD::FMA, MVT::f16, Legal);
430     if (!Subtarget->hasFP16Denormals())
431       setOperationAction(ISD::FMAD, MVT::f16, Legal);
432 
433     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
434       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
435         switch (Op) {
436         case ISD::LOAD:
437         case ISD::STORE:
438         case ISD::BUILD_VECTOR:
439         case ISD::BITCAST:
440         case ISD::EXTRACT_VECTOR_ELT:
441         case ISD::INSERT_VECTOR_ELT:
442         case ISD::INSERT_SUBVECTOR:
443         case ISD::EXTRACT_SUBVECTOR:
444         case ISD::SCALAR_TO_VECTOR:
445           break;
446         case ISD::CONCAT_VECTORS:
447           setOperationAction(Op, VT, Custom);
448           break;
449         default:
450           setOperationAction(Op, VT, Expand);
451           break;
452         }
453       }
454     }
455 
456     // XXX - Do these do anything? Vector constants turn into build_vector.
457     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
458     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
459 
460     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
461     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
462 
463     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
464     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
465     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
466     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
467 
468     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
469     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
470     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
471     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
472 
473     setOperationAction(ISD::AND, MVT::v2i16, Promote);
474     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
475     setOperationAction(ISD::OR, MVT::v2i16, Promote);
476     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
477     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
478     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
479 
480     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
481     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
482     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
483     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
484 
485     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
486     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
487     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
488     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
489 
490     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
491     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
492     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
493     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
494 
495     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
496     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
497     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
498 
499     if (!Subtarget->hasVOP3PInsts()) {
500       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
501       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
502     }
503 
504     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
505     // This isn't really legal, but this avoids the legalizer unrolling it (and
506     // allows matching fneg (fabs x) patterns)
507     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
508   }
509 
510   if (Subtarget->hasVOP3PInsts()) {
511     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
512     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
513     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
514     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
515     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
516     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
517     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
518     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
519     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
520     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
521 
522     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
523     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
524     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
525     setOperationAction(ISD::FMINNUM, MVT::v2f16, Legal);
526     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Legal);
527     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
528 
529     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
530     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
531 
532     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
533     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
534     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
535     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
536     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
537     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
538 
539     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
540     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
541     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
542     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
543 
544     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
545     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
546     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
547     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
548 
549     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
550     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
551   }
552 
553   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
554   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
555 
556   if (Subtarget->has16BitInsts()) {
557     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
558     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
559     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
560     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
561   } else {
562     // Legalization hack.
563     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
564     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
565 
566     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
567     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
568   }
569 
570   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
571     setOperationAction(ISD::SELECT, VT, Custom);
572   }
573 
574   setTargetDAGCombine(ISD::ADD);
575   setTargetDAGCombine(ISD::ADDCARRY);
576   setTargetDAGCombine(ISD::SUB);
577   setTargetDAGCombine(ISD::SUBCARRY);
578   setTargetDAGCombine(ISD::FADD);
579   setTargetDAGCombine(ISD::FSUB);
580   setTargetDAGCombine(ISD::FMINNUM);
581   setTargetDAGCombine(ISD::FMAXNUM);
582   setTargetDAGCombine(ISD::SMIN);
583   setTargetDAGCombine(ISD::SMAX);
584   setTargetDAGCombine(ISD::UMIN);
585   setTargetDAGCombine(ISD::UMAX);
586   setTargetDAGCombine(ISD::SETCC);
587   setTargetDAGCombine(ISD::AND);
588   setTargetDAGCombine(ISD::OR);
589   setTargetDAGCombine(ISD::XOR);
590   setTargetDAGCombine(ISD::SINT_TO_FP);
591   setTargetDAGCombine(ISD::UINT_TO_FP);
592   setTargetDAGCombine(ISD::FCANONICALIZE);
593   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
594   setTargetDAGCombine(ISD::ZERO_EXTEND);
595   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
596   setTargetDAGCombine(ISD::BUILD_VECTOR);
597 
598   // All memory operations. Some folding on the pointer operand is done to help
599   // matching the constant offsets in the addressing modes.
600   setTargetDAGCombine(ISD::LOAD);
601   setTargetDAGCombine(ISD::STORE);
602   setTargetDAGCombine(ISD::ATOMIC_LOAD);
603   setTargetDAGCombine(ISD::ATOMIC_STORE);
604   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
605   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
606   setTargetDAGCombine(ISD::ATOMIC_SWAP);
607   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
608   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
609   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
610   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
611   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
612   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
613   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
614   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
615   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
616   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
617 
618   setSchedulingPreference(Sched::RegPressure);
619 }
620 
621 const SISubtarget *SITargetLowering::getSubtarget() const {
622   return static_cast<const SISubtarget *>(Subtarget);
623 }
624 
625 //===----------------------------------------------------------------------===//
626 // TargetLowering queries
627 //===----------------------------------------------------------------------===//
628 
629 // v_mad_mix* support a conversion from f16 to f32.
630 //
631 // There is only one special case when denormals are enabled we don't currently,
632 // where this is OK to use.
633 bool SITargetLowering::isFPExtFoldable(unsigned Opcode,
634                                            EVT DestVT, EVT SrcVT) const {
635   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
636           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
637          DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
638          SrcVT.getScalarType() == MVT::f16;
639 }
640 
641 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
642   // SI has some legal vector types, but no legal vector operations. Say no
643   // shuffles are legal in order to prefer scalarizing some vector operations.
644   return false;
645 }
646 
647 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
648                                           const CallInst &CI,
649                                           MachineFunction &MF,
650                                           unsigned IntrID) const {
651   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
652           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
653     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
654                                                   (Intrinsic::ID)IntrID);
655     if (Attr.hasFnAttribute(Attribute::ReadNone))
656       return false;
657 
658     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
659 
660     if (RsrcIntr->IsImage) {
661       Info.ptrVal = MFI->getImagePSV(
662         *MF.getSubtarget<SISubtarget>().getInstrInfo(),
663         CI.getArgOperand(RsrcIntr->RsrcArg));
664       Info.align = 0;
665     } else {
666       Info.ptrVal = MFI->getBufferPSV(
667         *MF.getSubtarget<SISubtarget>().getInstrInfo(),
668         CI.getArgOperand(RsrcIntr->RsrcArg));
669     }
670 
671     Info.flags = MachineMemOperand::MODereferenceable;
672     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
673       Info.opc = ISD::INTRINSIC_W_CHAIN;
674       Info.memVT = MVT::getVT(CI.getType());
675       Info.flags |= MachineMemOperand::MOLoad;
676     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
677       Info.opc = ISD::INTRINSIC_VOID;
678       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
679       Info.flags |= MachineMemOperand::MOStore;
680     } else {
681       // Atomic
682       Info.opc = ISD::INTRINSIC_W_CHAIN;
683       Info.memVT = MVT::getVT(CI.getType());
684       Info.flags = MachineMemOperand::MOLoad |
685                    MachineMemOperand::MOStore |
686                    MachineMemOperand::MODereferenceable;
687 
688       // XXX - Should this be volatile without known ordering?
689       Info.flags |= MachineMemOperand::MOVolatile;
690     }
691     return true;
692   }
693 
694   switch (IntrID) {
695   case Intrinsic::amdgcn_atomic_inc:
696   case Intrinsic::amdgcn_atomic_dec:
697   case Intrinsic::amdgcn_ds_fadd:
698   case Intrinsic::amdgcn_ds_fmin:
699   case Intrinsic::amdgcn_ds_fmax: {
700     Info.opc = ISD::INTRINSIC_W_CHAIN;
701     Info.memVT = MVT::getVT(CI.getType());
702     Info.ptrVal = CI.getOperand(0);
703     Info.align = 0;
704     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
705 
706     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
707     if (!Vol || !Vol->isZero())
708       Info.flags |= MachineMemOperand::MOVolatile;
709 
710     return true;
711   }
712 
713   default:
714     return false;
715   }
716 }
717 
718 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
719                                             SmallVectorImpl<Value*> &Ops,
720                                             Type *&AccessTy) const {
721   switch (II->getIntrinsicID()) {
722   case Intrinsic::amdgcn_atomic_inc:
723   case Intrinsic::amdgcn_atomic_dec:
724   case Intrinsic::amdgcn_ds_fadd:
725   case Intrinsic::amdgcn_ds_fmin:
726   case Intrinsic::amdgcn_ds_fmax: {
727     Value *Ptr = II->getArgOperand(0);
728     AccessTy = II->getType();
729     Ops.push_back(Ptr);
730     return true;
731   }
732   default:
733     return false;
734   }
735 }
736 
737 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
738   if (!Subtarget->hasFlatInstOffsets()) {
739     // Flat instructions do not have offsets, and only have the register
740     // address.
741     return AM.BaseOffs == 0 && AM.Scale == 0;
742   }
743 
744   // GFX9 added a 13-bit signed offset. When using regular flat instructions,
745   // the sign bit is ignored and is treated as a 12-bit unsigned offset.
746 
747   // Just r + i
748   return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
749 }
750 
751 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
752   if (Subtarget->hasFlatGlobalInsts())
753     return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
754 
755   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
756       // Assume the we will use FLAT for all global memory accesses
757       // on VI.
758       // FIXME: This assumption is currently wrong.  On VI we still use
759       // MUBUF instructions for the r + i addressing mode.  As currently
760       // implemented, the MUBUF instructions only work on buffer < 4GB.
761       // It may be possible to support > 4GB buffers with MUBUF instructions,
762       // by setting the stride value in the resource descriptor which would
763       // increase the size limit to (stride * 4GB).  However, this is risky,
764       // because it has never been validated.
765     return isLegalFlatAddressingMode(AM);
766   }
767 
768   return isLegalMUBUFAddressingMode(AM);
769 }
770 
771 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
772   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
773   // additionally can do r + r + i with addr64. 32-bit has more addressing
774   // mode options. Depending on the resource constant, it can also do
775   // (i64 r0) + (i32 r1) * (i14 i).
776   //
777   // Private arrays end up using a scratch buffer most of the time, so also
778   // assume those use MUBUF instructions. Scratch loads / stores are currently
779   // implemented as mubuf instructions with offen bit set, so slightly
780   // different than the normal addr64.
781   if (!isUInt<12>(AM.BaseOffs))
782     return false;
783 
784   // FIXME: Since we can split immediate into soffset and immediate offset,
785   // would it make sense to allow any immediate?
786 
787   switch (AM.Scale) {
788   case 0: // r + i or just i, depending on HasBaseReg.
789     return true;
790   case 1:
791     return true; // We have r + r or r + i.
792   case 2:
793     if (AM.HasBaseReg) {
794       // Reject 2 * r + r.
795       return false;
796     }
797 
798     // Allow 2 * r as r + r
799     // Or  2 * r + i is allowed as r + r + i.
800     return true;
801   default: // Don't allow n * r
802     return false;
803   }
804 }
805 
806 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
807                                              const AddrMode &AM, Type *Ty,
808                                              unsigned AS, Instruction *I) const {
809   // No global is ever allowed as a base.
810   if (AM.BaseGV)
811     return false;
812 
813   if (AS == AMDGPUASI.GLOBAL_ADDRESS)
814     return isLegalGlobalAddressingMode(AM);
815 
816   if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
817       AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) {
818     // If the offset isn't a multiple of 4, it probably isn't going to be
819     // correctly aligned.
820     // FIXME: Can we get the real alignment here?
821     if (AM.BaseOffs % 4 != 0)
822       return isLegalMUBUFAddressingMode(AM);
823 
824     // There are no SMRD extloads, so if we have to do a small type access we
825     // will use a MUBUF load.
826     // FIXME?: We also need to do this if unaligned, but we don't know the
827     // alignment here.
828     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
829       return isLegalGlobalAddressingMode(AM);
830 
831     if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
832       // SMRD instructions have an 8-bit, dword offset on SI.
833       if (!isUInt<8>(AM.BaseOffs / 4))
834         return false;
835     } else if (Subtarget->getGeneration() == SISubtarget::SEA_ISLANDS) {
836       // On CI+, this can also be a 32-bit literal constant offset. If it fits
837       // in 8-bits, it can use a smaller encoding.
838       if (!isUInt<32>(AM.BaseOffs / 4))
839         return false;
840     } else if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS) {
841       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
842       if (!isUInt<20>(AM.BaseOffs))
843         return false;
844     } else
845       llvm_unreachable("unhandled generation");
846 
847     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
848       return true;
849 
850     if (AM.Scale == 1 && AM.HasBaseReg)
851       return true;
852 
853     return false;
854 
855   } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
856     return isLegalMUBUFAddressingMode(AM);
857   } else if (AS == AMDGPUASI.LOCAL_ADDRESS ||
858              AS == AMDGPUASI.REGION_ADDRESS) {
859     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
860     // field.
861     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
862     // an 8-bit dword offset but we don't know the alignment here.
863     if (!isUInt<16>(AM.BaseOffs))
864       return false;
865 
866     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
867       return true;
868 
869     if (AM.Scale == 1 && AM.HasBaseReg)
870       return true;
871 
872     return false;
873   } else if (AS == AMDGPUASI.FLAT_ADDRESS ||
874              AS == AMDGPUASI.UNKNOWN_ADDRESS_SPACE) {
875     // For an unknown address space, this usually means that this is for some
876     // reason being used for pure arithmetic, and not based on some addressing
877     // computation. We don't have instructions that compute pointers with any
878     // addressing modes, so treat them as having no offset like flat
879     // instructions.
880     return isLegalFlatAddressingMode(AM);
881   } else {
882     llvm_unreachable("unhandled address space");
883   }
884 }
885 
886 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
887                                         const SelectionDAG &DAG) const {
888   if (AS == AMDGPUASI.GLOBAL_ADDRESS || AS == AMDGPUASI.FLAT_ADDRESS) {
889     return (MemVT.getSizeInBits() <= 4 * 32);
890   } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
891     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
892     return (MemVT.getSizeInBits() <= MaxPrivateBits);
893   } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
894     return (MemVT.getSizeInBits() <= 2 * 32);
895   }
896   return true;
897 }
898 
899 bool SITargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
900                                                       unsigned AddrSpace,
901                                                       unsigned Align,
902                                                       bool *IsFast) const {
903   if (IsFast)
904     *IsFast = false;
905 
906   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
907   // which isn't a simple VT.
908   // Until MVT is extended to handle this, simply check for the size and
909   // rely on the condition below: allow accesses if the size is a multiple of 4.
910   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
911                            VT.getStoreSize() > 16)) {
912     return false;
913   }
914 
915   if (AddrSpace == AMDGPUASI.LOCAL_ADDRESS ||
916       AddrSpace == AMDGPUASI.REGION_ADDRESS) {
917     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
918     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
919     // with adjacent offsets.
920     bool AlignedBy4 = (Align % 4 == 0);
921     if (IsFast)
922       *IsFast = AlignedBy4;
923 
924     return AlignedBy4;
925   }
926 
927   // FIXME: We have to be conservative here and assume that flat operations
928   // will access scratch.  If we had access to the IR function, then we
929   // could determine if any private memory was used in the function.
930   if (!Subtarget->hasUnalignedScratchAccess() &&
931       (AddrSpace == AMDGPUASI.PRIVATE_ADDRESS ||
932        AddrSpace == AMDGPUASI.FLAT_ADDRESS)) {
933     return false;
934   }
935 
936   if (Subtarget->hasUnalignedBufferAccess()) {
937     // If we have an uniform constant load, it still requires using a slow
938     // buffer instruction if unaligned.
939     if (IsFast) {
940       *IsFast = (AddrSpace == AMDGPUASI.CONSTANT_ADDRESS ||
941                  AddrSpace == AMDGPUASI.CONSTANT_ADDRESS_32BIT) ?
942         (Align % 4 == 0) : true;
943     }
944 
945     return true;
946   }
947 
948   // Smaller than dword value must be aligned.
949   if (VT.bitsLT(MVT::i32))
950     return false;
951 
952   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
953   // byte-address are ignored, thus forcing Dword alignment.
954   // This applies to private, global, and constant memory.
955   if (IsFast)
956     *IsFast = true;
957 
958   return VT.bitsGT(MVT::i32) && Align % 4 == 0;
959 }
960 
961 EVT SITargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
962                                           unsigned SrcAlign, bool IsMemset,
963                                           bool ZeroMemset,
964                                           bool MemcpyStrSrc,
965                                           MachineFunction &MF) const {
966   // FIXME: Should account for address space here.
967 
968   // The default fallback uses the private pointer size as a guess for a type to
969   // use. Make sure we switch these to 64-bit accesses.
970 
971   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
972     return MVT::v4i32;
973 
974   if (Size >= 8 && DstAlign >= 4)
975     return MVT::v2i32;
976 
977   // Use the default.
978   return MVT::Other;
979 }
980 
981 static bool isFlatGlobalAddrSpace(unsigned AS, AMDGPUAS AMDGPUASI) {
982   return AS == AMDGPUASI.GLOBAL_ADDRESS ||
983          AS == AMDGPUASI.FLAT_ADDRESS ||
984          AS == AMDGPUASI.CONSTANT_ADDRESS ||
985          AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT;
986 }
987 
988 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
989                                            unsigned DestAS) const {
990   return isFlatGlobalAddrSpace(SrcAS, AMDGPUASI) &&
991          isFlatGlobalAddrSpace(DestAS, AMDGPUASI);
992 }
993 
994 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
995   const MemSDNode *MemNode = cast<MemSDNode>(N);
996   const Value *Ptr = MemNode->getMemOperand()->getValue();
997   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
998   return I && I->getMetadata("amdgpu.noclobber");
999 }
1000 
1001 bool SITargetLowering::isCheapAddrSpaceCast(unsigned SrcAS,
1002                                             unsigned DestAS) const {
1003   // Flat -> private/local is a simple truncate.
1004   // Flat -> global is no-op
1005   if (SrcAS == AMDGPUASI.FLAT_ADDRESS)
1006     return true;
1007 
1008   return isNoopAddrSpaceCast(SrcAS, DestAS);
1009 }
1010 
1011 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1012   const MemSDNode *MemNode = cast<MemSDNode>(N);
1013 
1014   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1015 }
1016 
1017 TargetLoweringBase::LegalizeTypeAction
1018 SITargetLowering::getPreferredVectorAction(EVT VT) const {
1019   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1020     return TypeSplitVector;
1021 
1022   return TargetLoweringBase::getPreferredVectorAction(VT);
1023 }
1024 
1025 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1026                                                          Type *Ty) const {
1027   // FIXME: Could be smarter if called for vector constants.
1028   return true;
1029 }
1030 
1031 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1032   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1033     switch (Op) {
1034     case ISD::LOAD:
1035     case ISD::STORE:
1036 
1037     // These operations are done with 32-bit instructions anyway.
1038     case ISD::AND:
1039     case ISD::OR:
1040     case ISD::XOR:
1041     case ISD::SELECT:
1042       // TODO: Extensions?
1043       return true;
1044     default:
1045       return false;
1046     }
1047   }
1048 
1049   // SimplifySetCC uses this function to determine whether or not it should
1050   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1051   if (VT == MVT::i1 && Op == ISD::SETCC)
1052     return false;
1053 
1054   return TargetLowering::isTypeDesirableForOp(Op, VT);
1055 }
1056 
1057 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1058                                                    const SDLoc &SL,
1059                                                    SDValue Chain,
1060                                                    uint64_t Offset) const {
1061   const DataLayout &DL = DAG.getDataLayout();
1062   MachineFunction &MF = DAG.getMachineFunction();
1063   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1064 
1065   const ArgDescriptor *InputPtrReg;
1066   const TargetRegisterClass *RC;
1067 
1068   std::tie(InputPtrReg, RC)
1069     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1070 
1071   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1072   MVT PtrVT = getPointerTy(DL, AMDGPUASI.CONSTANT_ADDRESS);
1073   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1074     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1075 
1076   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1077 }
1078 
1079 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1080                                             const SDLoc &SL) const {
1081   auto MFI = DAG.getMachineFunction().getInfo<SIMachineFunctionInfo>();
1082   uint64_t Offset = getImplicitParameterOffset(MFI, FIRST_IMPLICIT);
1083   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1084 }
1085 
1086 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1087                                          const SDLoc &SL, SDValue Val,
1088                                          bool Signed,
1089                                          const ISD::InputArg *Arg) const {
1090   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1091       VT.bitsLT(MemVT)) {
1092     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1093     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1094   }
1095 
1096   if (MemVT.isFloatingPoint())
1097     Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1098   else if (Signed)
1099     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1100   else
1101     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1102 
1103   return Val;
1104 }
1105 
1106 SDValue SITargetLowering::lowerKernargMemParameter(
1107   SelectionDAG &DAG, EVT VT, EVT MemVT,
1108   const SDLoc &SL, SDValue Chain,
1109   uint64_t Offset, unsigned Align, bool Signed,
1110   const ISD::InputArg *Arg) const {
1111   Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1112   PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
1113   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1114 
1115   // Try to avoid using an extload by loading earlier than the argument address,
1116   // and extracting the relevant bits. The load should hopefully be merged with
1117   // the previous argument.
1118   if (Align < 4) {
1119     assert(MemVT.getStoreSize() < 4);
1120     int64_t AlignDownOffset = alignDown(Offset, 4);
1121     int64_t OffsetDiff = Offset - AlignDownOffset;
1122 
1123     EVT IntVT = MemVT.changeTypeToInteger();
1124 
1125     // TODO: If we passed in the base kernel offset we could have a better
1126     // alignment than 4, but we don't really need it.
1127     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1128     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1129                                MachineMemOperand::MODereferenceable |
1130                                MachineMemOperand::MOInvariant);
1131 
1132     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1133     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1134 
1135     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1136     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1137     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1138 
1139 
1140     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1141   }
1142 
1143   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1144   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1145                              MachineMemOperand::MODereferenceable |
1146                              MachineMemOperand::MOInvariant);
1147 
1148   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1149   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1150 }
1151 
1152 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1153                                               const SDLoc &SL, SDValue Chain,
1154                                               const ISD::InputArg &Arg) const {
1155   MachineFunction &MF = DAG.getMachineFunction();
1156   MachineFrameInfo &MFI = MF.getFrameInfo();
1157 
1158   if (Arg.Flags.isByVal()) {
1159     unsigned Size = Arg.Flags.getByValSize();
1160     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1161     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1162   }
1163 
1164   unsigned ArgOffset = VA.getLocMemOffset();
1165   unsigned ArgSize = VA.getValVT().getStoreSize();
1166 
1167   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1168 
1169   // Create load nodes to retrieve arguments from the stack.
1170   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1171   SDValue ArgValue;
1172 
1173   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1174   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1175   MVT MemVT = VA.getValVT();
1176 
1177   switch (VA.getLocInfo()) {
1178   default:
1179     break;
1180   case CCValAssign::BCvt:
1181     MemVT = VA.getLocVT();
1182     break;
1183   case CCValAssign::SExt:
1184     ExtType = ISD::SEXTLOAD;
1185     break;
1186   case CCValAssign::ZExt:
1187     ExtType = ISD::ZEXTLOAD;
1188     break;
1189   case CCValAssign::AExt:
1190     ExtType = ISD::EXTLOAD;
1191     break;
1192   }
1193 
1194   ArgValue = DAG.getExtLoad(
1195     ExtType, SL, VA.getLocVT(), Chain, FIN,
1196     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1197     MemVT);
1198   return ArgValue;
1199 }
1200 
1201 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1202   const SIMachineFunctionInfo &MFI,
1203   EVT VT,
1204   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1205   const ArgDescriptor *Reg;
1206   const TargetRegisterClass *RC;
1207 
1208   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1209   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1210 }
1211 
1212 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1213                                    CallingConv::ID CallConv,
1214                                    ArrayRef<ISD::InputArg> Ins,
1215                                    BitVector &Skipped,
1216                                    FunctionType *FType,
1217                                    SIMachineFunctionInfo *Info) {
1218   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1219     const ISD::InputArg &Arg = Ins[I];
1220 
1221     // First check if it's a PS input addr.
1222     if (CallConv == CallingConv::AMDGPU_PS && !Arg.Flags.isInReg() &&
1223         !Arg.Flags.isByVal() && PSInputNum <= 15) {
1224 
1225       if (!Arg.Used && !Info->isPSInputAllocated(PSInputNum)) {
1226         // We can safely skip PS inputs.
1227         Skipped.set(I);
1228         ++PSInputNum;
1229         continue;
1230       }
1231 
1232       Info->markPSInputAllocated(PSInputNum);
1233       if (Arg.Used)
1234         Info->markPSInputEnabled(PSInputNum);
1235 
1236       ++PSInputNum;
1237     }
1238 
1239     // Second split vertices into their elements.
1240     if (Arg.VT.isVector()) {
1241       ISD::InputArg NewArg = Arg;
1242       NewArg.Flags.setSplit();
1243       NewArg.VT = Arg.VT.getVectorElementType();
1244 
1245       // We REALLY want the ORIGINAL number of vertex elements here, e.g. a
1246       // three or five element vertex only needs three or five registers,
1247       // NOT four or eight.
1248       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1249       unsigned NumElements = ParamType->getVectorNumElements();
1250 
1251       for (unsigned J = 0; J != NumElements; ++J) {
1252         Splits.push_back(NewArg);
1253         NewArg.PartOffset += NewArg.VT.getStoreSize();
1254       }
1255     } else {
1256       Splits.push_back(Arg);
1257     }
1258   }
1259 }
1260 
1261 // Allocate special inputs passed in VGPRs.
1262 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1263                                            MachineFunction &MF,
1264                                            const SIRegisterInfo &TRI,
1265                                            SIMachineFunctionInfo &Info) {
1266   if (Info.hasWorkItemIDX()) {
1267     unsigned Reg = AMDGPU::VGPR0;
1268     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1269 
1270     CCInfo.AllocateReg(Reg);
1271     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1272   }
1273 
1274   if (Info.hasWorkItemIDY()) {
1275     unsigned Reg = AMDGPU::VGPR1;
1276     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1277 
1278     CCInfo.AllocateReg(Reg);
1279     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1280   }
1281 
1282   if (Info.hasWorkItemIDZ()) {
1283     unsigned Reg = AMDGPU::VGPR2;
1284     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1285 
1286     CCInfo.AllocateReg(Reg);
1287     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1288   }
1289 }
1290 
1291 // Try to allocate a VGPR at the end of the argument list, or if no argument
1292 // VGPRs are left allocating a stack slot.
1293 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1294   ArrayRef<MCPhysReg> ArgVGPRs
1295     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1296   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1297   if (RegIdx == ArgVGPRs.size()) {
1298     // Spill to stack required.
1299     int64_t Offset = CCInfo.AllocateStack(4, 4);
1300 
1301     return ArgDescriptor::createStack(Offset);
1302   }
1303 
1304   unsigned Reg = ArgVGPRs[RegIdx];
1305   Reg = CCInfo.AllocateReg(Reg);
1306   assert(Reg != AMDGPU::NoRegister);
1307 
1308   MachineFunction &MF = CCInfo.getMachineFunction();
1309   MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1310   return ArgDescriptor::createRegister(Reg);
1311 }
1312 
1313 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1314                                              const TargetRegisterClass *RC,
1315                                              unsigned NumArgRegs) {
1316   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1317   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1318   if (RegIdx == ArgSGPRs.size())
1319     report_fatal_error("ran out of SGPRs for arguments");
1320 
1321   unsigned Reg = ArgSGPRs[RegIdx];
1322   Reg = CCInfo.AllocateReg(Reg);
1323   assert(Reg != AMDGPU::NoRegister);
1324 
1325   MachineFunction &MF = CCInfo.getMachineFunction();
1326   MF.addLiveIn(Reg, RC);
1327   return ArgDescriptor::createRegister(Reg);
1328 }
1329 
1330 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1331   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1332 }
1333 
1334 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1335   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1336 }
1337 
1338 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1339                                       MachineFunction &MF,
1340                                       const SIRegisterInfo &TRI,
1341                                       SIMachineFunctionInfo &Info) {
1342   if (Info.hasWorkItemIDX())
1343     Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1344 
1345   if (Info.hasWorkItemIDY())
1346     Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1347 
1348   if (Info.hasWorkItemIDZ())
1349     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1350 }
1351 
1352 static void allocateSpecialInputSGPRs(CCState &CCInfo,
1353                                       MachineFunction &MF,
1354                                       const SIRegisterInfo &TRI,
1355                                       SIMachineFunctionInfo &Info) {
1356   auto &ArgInfo = Info.getArgInfo();
1357 
1358   // TODO: Unify handling with private memory pointers.
1359 
1360   if (Info.hasDispatchPtr())
1361     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1362 
1363   if (Info.hasQueuePtr())
1364     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1365 
1366   if (Info.hasKernargSegmentPtr())
1367     ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1368 
1369   if (Info.hasDispatchID())
1370     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1371 
1372   // flat_scratch_init is not applicable for non-kernel functions.
1373 
1374   if (Info.hasWorkGroupIDX())
1375     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1376 
1377   if (Info.hasWorkGroupIDY())
1378     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1379 
1380   if (Info.hasWorkGroupIDZ())
1381     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1382 
1383   if (Info.hasImplicitArgPtr())
1384     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1385 }
1386 
1387 // Allocate special inputs passed in user SGPRs.
1388 static void allocateHSAUserSGPRs(CCState &CCInfo,
1389                                  MachineFunction &MF,
1390                                  const SIRegisterInfo &TRI,
1391                                  SIMachineFunctionInfo &Info) {
1392   if (Info.hasImplicitBufferPtr()) {
1393     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1394     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1395     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1396   }
1397 
1398   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1399   if (Info.hasPrivateSegmentBuffer()) {
1400     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1401     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1402     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1403   }
1404 
1405   if (Info.hasDispatchPtr()) {
1406     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1407     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1408     CCInfo.AllocateReg(DispatchPtrReg);
1409   }
1410 
1411   if (Info.hasQueuePtr()) {
1412     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1413     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1414     CCInfo.AllocateReg(QueuePtrReg);
1415   }
1416 
1417   if (Info.hasKernargSegmentPtr()) {
1418     unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1419     MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1420     CCInfo.AllocateReg(InputPtrReg);
1421   }
1422 
1423   if (Info.hasDispatchID()) {
1424     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1425     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1426     CCInfo.AllocateReg(DispatchIDReg);
1427   }
1428 
1429   if (Info.hasFlatScratchInit()) {
1430     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1431     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1432     CCInfo.AllocateReg(FlatScratchInitReg);
1433   }
1434 
1435   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1436   // these from the dispatch pointer.
1437 }
1438 
1439 // Allocate special input registers that are initialized per-wave.
1440 static void allocateSystemSGPRs(CCState &CCInfo,
1441                                 MachineFunction &MF,
1442                                 SIMachineFunctionInfo &Info,
1443                                 CallingConv::ID CallConv,
1444                                 bool IsShader) {
1445   if (Info.hasWorkGroupIDX()) {
1446     unsigned Reg = Info.addWorkGroupIDX();
1447     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1448     CCInfo.AllocateReg(Reg);
1449   }
1450 
1451   if (Info.hasWorkGroupIDY()) {
1452     unsigned Reg = Info.addWorkGroupIDY();
1453     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1454     CCInfo.AllocateReg(Reg);
1455   }
1456 
1457   if (Info.hasWorkGroupIDZ()) {
1458     unsigned Reg = Info.addWorkGroupIDZ();
1459     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1460     CCInfo.AllocateReg(Reg);
1461   }
1462 
1463   if (Info.hasWorkGroupInfo()) {
1464     unsigned Reg = Info.addWorkGroupInfo();
1465     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1466     CCInfo.AllocateReg(Reg);
1467   }
1468 
1469   if (Info.hasPrivateSegmentWaveByteOffset()) {
1470     // Scratch wave offset passed in system SGPR.
1471     unsigned PrivateSegmentWaveByteOffsetReg;
1472 
1473     if (IsShader) {
1474       PrivateSegmentWaveByteOffsetReg =
1475         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1476 
1477       // This is true if the scratch wave byte offset doesn't have a fixed
1478       // location.
1479       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1480         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1481         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1482       }
1483     } else
1484       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1485 
1486     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1487     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1488   }
1489 }
1490 
1491 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1492                                      MachineFunction &MF,
1493                                      const SIRegisterInfo &TRI,
1494                                      SIMachineFunctionInfo &Info) {
1495   // Now that we've figured out where the scratch register inputs are, see if
1496   // should reserve the arguments and use them directly.
1497   MachineFrameInfo &MFI = MF.getFrameInfo();
1498   bool HasStackObjects = MFI.hasStackObjects();
1499 
1500   // Record that we know we have non-spill stack objects so we don't need to
1501   // check all stack objects later.
1502   if (HasStackObjects)
1503     Info.setHasNonSpillStackObjects(true);
1504 
1505   // Everything live out of a block is spilled with fast regalloc, so it's
1506   // almost certain that spilling will be required.
1507   if (TM.getOptLevel() == CodeGenOpt::None)
1508     HasStackObjects = true;
1509 
1510   // For now assume stack access is needed in any callee functions, so we need
1511   // the scratch registers to pass in.
1512   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1513 
1514   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1515   if (ST.isAmdCodeObjectV2(MF.getFunction())) {
1516     if (RequiresStackAccess) {
1517       // If we have stack objects, we unquestionably need the private buffer
1518       // resource. For the Code Object V2 ABI, this will be the first 4 user
1519       // SGPR inputs. We can reserve those and use them directly.
1520 
1521       unsigned PrivateSegmentBufferReg = Info.getPreloadedReg(
1522         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1523       Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1524 
1525       if (MFI.hasCalls()) {
1526         // If we have calls, we need to keep the frame register in a register
1527         // that won't be clobbered by a call, so ensure it is copied somewhere.
1528 
1529         // This is not a problem for the scratch wave offset, because the same
1530         // registers are reserved in all functions.
1531 
1532         // FIXME: Nothing is really ensuring this is a call preserved register,
1533         // it's just selected from the end so it happens to be.
1534         unsigned ReservedOffsetReg
1535           = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1536         Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1537       } else {
1538         unsigned PrivateSegmentWaveByteOffsetReg = Info.getPreloadedReg(
1539           AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1540         Info.setScratchWaveOffsetReg(PrivateSegmentWaveByteOffsetReg);
1541       }
1542     } else {
1543       unsigned ReservedBufferReg
1544         = TRI.reservedPrivateSegmentBufferReg(MF);
1545       unsigned ReservedOffsetReg
1546         = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1547 
1548       // We tentatively reserve the last registers (skipping the last two
1549       // which may contain VCC). After register allocation, we'll replace
1550       // these with the ones immediately after those which were really
1551       // allocated. In the prologue copies will be inserted from the argument
1552       // to these reserved registers.
1553       Info.setScratchRSrcReg(ReservedBufferReg);
1554       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1555     }
1556   } else {
1557     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1558 
1559     // Without HSA, relocations are used for the scratch pointer and the
1560     // buffer resource setup is always inserted in the prologue. Scratch wave
1561     // offset is still in an input SGPR.
1562     Info.setScratchRSrcReg(ReservedBufferReg);
1563 
1564     if (HasStackObjects && !MFI.hasCalls()) {
1565       unsigned ScratchWaveOffsetReg = Info.getPreloadedReg(
1566         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1567       Info.setScratchWaveOffsetReg(ScratchWaveOffsetReg);
1568     } else {
1569       unsigned ReservedOffsetReg
1570         = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1571       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1572     }
1573   }
1574 }
1575 
1576 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1577   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1578   return !Info->isEntryFunction();
1579 }
1580 
1581 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1582 
1583 }
1584 
1585 void SITargetLowering::insertCopiesSplitCSR(
1586   MachineBasicBlock *Entry,
1587   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1588   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1589 
1590   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1591   if (!IStart)
1592     return;
1593 
1594   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1595   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1596   MachineBasicBlock::iterator MBBI = Entry->begin();
1597   for (const MCPhysReg *I = IStart; *I; ++I) {
1598     const TargetRegisterClass *RC = nullptr;
1599     if (AMDGPU::SReg_64RegClass.contains(*I))
1600       RC = &AMDGPU::SGPR_64RegClass;
1601     else if (AMDGPU::SReg_32RegClass.contains(*I))
1602       RC = &AMDGPU::SGPR_32RegClass;
1603     else
1604       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1605 
1606     unsigned NewVR = MRI->createVirtualRegister(RC);
1607     // Create copy from CSR to a virtual register.
1608     Entry->addLiveIn(*I);
1609     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1610       .addReg(*I);
1611 
1612     // Insert the copy-back instructions right before the terminator.
1613     for (auto *Exit : Exits)
1614       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1615               TII->get(TargetOpcode::COPY), *I)
1616         .addReg(NewVR);
1617   }
1618 }
1619 
1620 SDValue SITargetLowering::LowerFormalArguments(
1621     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1622     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1623     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1624   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1625 
1626   MachineFunction &MF = DAG.getMachineFunction();
1627   const Function &Fn = MF.getFunction();
1628   FunctionType *FType = MF.getFunction().getFunctionType();
1629   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1630   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
1631 
1632   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1633     DiagnosticInfoUnsupported NoGraphicsHSA(
1634         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1635     DAG.getContext()->diagnose(NoGraphicsHSA);
1636     return DAG.getEntryNode();
1637   }
1638 
1639   // Create stack objects that are used for emitting debugger prologue if
1640   // "amdgpu-debugger-emit-prologue" attribute was specified.
1641   if (ST.debuggerEmitPrologue())
1642     createDebuggerPrologueStackObjects(MF);
1643 
1644   SmallVector<ISD::InputArg, 16> Splits;
1645   SmallVector<CCValAssign, 16> ArgLocs;
1646   BitVector Skipped(Ins.size());
1647   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1648                  *DAG.getContext());
1649 
1650   bool IsShader = AMDGPU::isShader(CallConv);
1651   bool IsKernel = AMDGPU::isKernel(CallConv);
1652   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1653 
1654   if (!IsEntryFunc) {
1655     // 4 bytes are reserved at offset 0 for the emergency stack slot. Skip over
1656     // this when allocating argument fixed offsets.
1657     CCInfo.AllocateStack(4, 4);
1658   }
1659 
1660   if (IsShader) {
1661     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1662 
1663     // At least one interpolation mode must be enabled or else the GPU will
1664     // hang.
1665     //
1666     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1667     // set PSInputAddr, the user wants to enable some bits after the compilation
1668     // based on run-time states. Since we can't know what the final PSInputEna
1669     // will look like, so we shouldn't do anything here and the user should take
1670     // responsibility for the correct programming.
1671     //
1672     // Otherwise, the following restrictions apply:
1673     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1674     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1675     //   enabled too.
1676     if (CallConv == CallingConv::AMDGPU_PS) {
1677       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1678            ((Info->getPSInputAddr() & 0xF) == 0 &&
1679             Info->isPSInputAllocated(11))) {
1680         CCInfo.AllocateReg(AMDGPU::VGPR0);
1681         CCInfo.AllocateReg(AMDGPU::VGPR1);
1682         Info->markPSInputAllocated(0);
1683         Info->markPSInputEnabled(0);
1684       }
1685       if (Subtarget->isAmdPalOS()) {
1686         // For isAmdPalOS, the user does not enable some bits after compilation
1687         // based on run-time states; the register values being generated here are
1688         // the final ones set in hardware. Therefore we need to apply the
1689         // workaround to PSInputAddr and PSInputEnable together.  (The case where
1690         // a bit is set in PSInputAddr but not PSInputEnable is where the
1691         // frontend set up an input arg for a particular interpolation mode, but
1692         // nothing uses that input arg. Really we should have an earlier pass
1693         // that removes such an arg.)
1694         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1695         if ((PsInputBits & 0x7F) == 0 ||
1696             ((PsInputBits & 0xF) == 0 &&
1697              (PsInputBits >> 11 & 1)))
1698           Info->markPSInputEnabled(
1699               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
1700       }
1701     }
1702 
1703     assert(!Info->hasDispatchPtr() &&
1704            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
1705            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
1706            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
1707            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
1708            !Info->hasWorkItemIDZ());
1709   } else if (IsKernel) {
1710     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
1711   } else {
1712     Splits.append(Ins.begin(), Ins.end());
1713   }
1714 
1715   if (IsEntryFunc) {
1716     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
1717     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
1718   }
1719 
1720   if (IsKernel) {
1721     analyzeFormalArgumentsCompute(CCInfo, Ins);
1722   } else {
1723     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
1724     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
1725   }
1726 
1727   SmallVector<SDValue, 16> Chains;
1728 
1729   // FIXME: This is the minimum kernel argument alignment. We should improve
1730   // this to the maximum alignment of the arguments.
1731   //
1732   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
1733   // kern arg offset.
1734   const unsigned KernelArgBaseAlign = 16;
1735   const unsigned ExplicitOffset = Subtarget->getExplicitKernelArgOffset(Fn);
1736 
1737    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
1738     const ISD::InputArg &Arg = Ins[i];
1739     if (Skipped[i]) {
1740       InVals.push_back(DAG.getUNDEF(Arg.VT));
1741       continue;
1742     }
1743 
1744     CCValAssign &VA = ArgLocs[ArgIdx++];
1745     MVT VT = VA.getLocVT();
1746 
1747     if (IsEntryFunc && VA.isMemLoc()) {
1748       VT = Ins[i].VT;
1749       EVT MemVT = VA.getLocVT();
1750 
1751       const uint64_t Offset = ExplicitOffset + VA.getLocMemOffset();
1752       Info->setABIArgOffset(Offset + MemVT.getStoreSize());
1753       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
1754 
1755       // The first 36 bytes of the input buffer contains information about
1756       // thread group and global sizes for clover.
1757       SDValue Arg = lowerKernargMemParameter(
1758         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
1759       Chains.push_back(Arg.getValue(1));
1760 
1761       auto *ParamTy =
1762         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
1763       if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
1764           ParamTy && ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
1765         // On SI local pointers are just offsets into LDS, so they are always
1766         // less than 16-bits.  On CI and newer they could potentially be
1767         // real pointers, so we can't guarantee their size.
1768         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
1769                           DAG.getValueType(MVT::i16));
1770       }
1771 
1772       InVals.push_back(Arg);
1773       continue;
1774     } else if (!IsEntryFunc && VA.isMemLoc()) {
1775       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
1776       InVals.push_back(Val);
1777       if (!Arg.Flags.isByVal())
1778         Chains.push_back(Val.getValue(1));
1779       continue;
1780     }
1781 
1782     assert(VA.isRegLoc() && "Parameter must be in a register!");
1783 
1784     unsigned Reg = VA.getLocReg();
1785     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
1786     EVT ValVT = VA.getValVT();
1787 
1788     Reg = MF.addLiveIn(Reg, RC);
1789     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1790 
1791     if (Arg.Flags.isSRet() && !getSubtarget()->enableHugePrivateBuffer()) {
1792       // The return object should be reasonably addressable.
1793 
1794       // FIXME: This helps when the return is a real sret. If it is a
1795       // automatically inserted sret (i.e. CanLowerReturn returns false), an
1796       // extra copy is inserted in SelectionDAGBuilder which obscures this.
1797       unsigned NumBits = 32 - AssumeFrameIndexHighZeroBits;
1798       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1799         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
1800     }
1801 
1802     // If this is an 8 or 16-bit value, it is really passed promoted
1803     // to 32 bits. Insert an assert[sz]ext to capture this, then
1804     // truncate to the right size.
1805     switch (VA.getLocInfo()) {
1806     case CCValAssign::Full:
1807       break;
1808     case CCValAssign::BCvt:
1809       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
1810       break;
1811     case CCValAssign::SExt:
1812       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
1813                         DAG.getValueType(ValVT));
1814       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1815       break;
1816     case CCValAssign::ZExt:
1817       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
1818                         DAG.getValueType(ValVT));
1819       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1820       break;
1821     case CCValAssign::AExt:
1822       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
1823       break;
1824     default:
1825       llvm_unreachable("Unknown loc info!");
1826     }
1827 
1828     if (IsShader && Arg.VT.isVector()) {
1829       // Build a vector from the registers
1830       Type *ParamType = FType->getParamType(Arg.getOrigArgIndex());
1831       unsigned NumElements = ParamType->getVectorNumElements();
1832 
1833       SmallVector<SDValue, 4> Regs;
1834       Regs.push_back(Val);
1835       for (unsigned j = 1; j != NumElements; ++j) {
1836         Reg = ArgLocs[ArgIdx++].getLocReg();
1837         Reg = MF.addLiveIn(Reg, RC);
1838 
1839         SDValue Copy = DAG.getCopyFromReg(Chain, DL, Reg, VT);
1840         Regs.push_back(Copy);
1841       }
1842 
1843       // Fill up the missing vector elements
1844       NumElements = Arg.VT.getVectorNumElements() - NumElements;
1845       Regs.append(NumElements, DAG.getUNDEF(VT));
1846 
1847       InVals.push_back(DAG.getBuildVector(Arg.VT, DL, Regs));
1848       continue;
1849     }
1850 
1851     InVals.push_back(Val);
1852   }
1853 
1854   if (!IsEntryFunc) {
1855     // Special inputs come after user arguments.
1856     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
1857   }
1858 
1859   // Start adding system SGPRs.
1860   if (IsEntryFunc) {
1861     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
1862   } else {
1863     CCInfo.AllocateReg(Info->getScratchRSrcReg());
1864     CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
1865     CCInfo.AllocateReg(Info->getFrameOffsetReg());
1866     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
1867   }
1868 
1869   auto &ArgUsageInfo =
1870     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
1871   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
1872 
1873   unsigned StackArgSize = CCInfo.getNextStackOffset();
1874   Info->setBytesInStackArgArea(StackArgSize);
1875 
1876   return Chains.empty() ? Chain :
1877     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
1878 }
1879 
1880 // TODO: If return values can't fit in registers, we should return as many as
1881 // possible in registers before passing on stack.
1882 bool SITargetLowering::CanLowerReturn(
1883   CallingConv::ID CallConv,
1884   MachineFunction &MF, bool IsVarArg,
1885   const SmallVectorImpl<ISD::OutputArg> &Outs,
1886   LLVMContext &Context) const {
1887   // Replacing returns with sret/stack usage doesn't make sense for shaders.
1888   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
1889   // for shaders. Vector types should be explicitly handled by CC.
1890   if (AMDGPU::isEntryFunctionCC(CallConv))
1891     return true;
1892 
1893   SmallVector<CCValAssign, 16> RVLocs;
1894   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
1895   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
1896 }
1897 
1898 SDValue
1899 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
1900                               bool isVarArg,
1901                               const SmallVectorImpl<ISD::OutputArg> &Outs,
1902                               const SmallVectorImpl<SDValue> &OutVals,
1903                               const SDLoc &DL, SelectionDAG &DAG) const {
1904   MachineFunction &MF = DAG.getMachineFunction();
1905   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1906 
1907   if (AMDGPU::isKernel(CallConv)) {
1908     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
1909                                              OutVals, DL, DAG);
1910   }
1911 
1912   bool IsShader = AMDGPU::isShader(CallConv);
1913 
1914   Info->setIfReturnsVoid(Outs.size() == 0);
1915   bool IsWaveEnd = Info->returnsVoid() && IsShader;
1916 
1917   SmallVector<ISD::OutputArg, 48> Splits;
1918   SmallVector<SDValue, 48> SplitVals;
1919 
1920   // Split vectors into their elements.
1921   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
1922     const ISD::OutputArg &Out = Outs[i];
1923 
1924     if (IsShader && Out.VT.isVector()) {
1925       MVT VT = Out.VT.getVectorElementType();
1926       ISD::OutputArg NewOut = Out;
1927       NewOut.Flags.setSplit();
1928       NewOut.VT = VT;
1929 
1930       // We want the original number of vector elements here, e.g.
1931       // three or five, not four or eight.
1932       unsigned NumElements = Out.ArgVT.getVectorNumElements();
1933 
1934       for (unsigned j = 0; j != NumElements; ++j) {
1935         SDValue Elem = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, OutVals[i],
1936                                    DAG.getConstant(j, DL, MVT::i32));
1937         SplitVals.push_back(Elem);
1938         Splits.push_back(NewOut);
1939         NewOut.PartOffset += NewOut.VT.getStoreSize();
1940       }
1941     } else {
1942       SplitVals.push_back(OutVals[i]);
1943       Splits.push_back(Out);
1944     }
1945   }
1946 
1947   // CCValAssign - represent the assignment of the return value to a location.
1948   SmallVector<CCValAssign, 48> RVLocs;
1949 
1950   // CCState - Info about the registers and stack slots.
1951   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
1952                  *DAG.getContext());
1953 
1954   // Analyze outgoing return values.
1955   CCInfo.AnalyzeReturn(Splits, CCAssignFnForReturn(CallConv, isVarArg));
1956 
1957   SDValue Flag;
1958   SmallVector<SDValue, 48> RetOps;
1959   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
1960 
1961   // Add return address for callable functions.
1962   if (!Info->isEntryFunction()) {
1963     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1964     SDValue ReturnAddrReg = CreateLiveInRegister(
1965       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
1966 
1967     // FIXME: Should be able to use a vreg here, but need a way to prevent it
1968     // from being allcoated to a CSR.
1969 
1970     SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
1971                                                 MVT::i64);
1972 
1973     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
1974     Flag = Chain.getValue(1);
1975 
1976     RetOps.push_back(PhysReturnAddrReg);
1977   }
1978 
1979   // Copy the result values into the output registers.
1980   for (unsigned i = 0, realRVLocIdx = 0;
1981        i != RVLocs.size();
1982        ++i, ++realRVLocIdx) {
1983     CCValAssign &VA = RVLocs[i];
1984     assert(VA.isRegLoc() && "Can only return in registers!");
1985     // TODO: Partially return in registers if return values don't fit.
1986 
1987     SDValue Arg = SplitVals[realRVLocIdx];
1988 
1989     // Copied from other backends.
1990     switch (VA.getLocInfo()) {
1991     case CCValAssign::Full:
1992       break;
1993     case CCValAssign::BCvt:
1994       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
1995       break;
1996     case CCValAssign::SExt:
1997       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
1998       break;
1999     case CCValAssign::ZExt:
2000       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2001       break;
2002     case CCValAssign::AExt:
2003       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2004       break;
2005     default:
2006       llvm_unreachable("Unknown loc info!");
2007     }
2008 
2009     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2010     Flag = Chain.getValue(1);
2011     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2012   }
2013 
2014   // FIXME: Does sret work properly?
2015   if (!Info->isEntryFunction()) {
2016     const SIRegisterInfo *TRI
2017       = static_cast<const SISubtarget *>(Subtarget)->getRegisterInfo();
2018     const MCPhysReg *I =
2019       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2020     if (I) {
2021       for (; *I; ++I) {
2022         if (AMDGPU::SReg_64RegClass.contains(*I))
2023           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2024         else if (AMDGPU::SReg_32RegClass.contains(*I))
2025           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2026         else
2027           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2028       }
2029     }
2030   }
2031 
2032   // Update chain and glue.
2033   RetOps[0] = Chain;
2034   if (Flag.getNode())
2035     RetOps.push_back(Flag);
2036 
2037   unsigned Opc = AMDGPUISD::ENDPGM;
2038   if (!IsWaveEnd)
2039     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2040   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2041 }
2042 
2043 SDValue SITargetLowering::LowerCallResult(
2044     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2045     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2046     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2047     SDValue ThisVal) const {
2048   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2049 
2050   // Assign locations to each value returned by this call.
2051   SmallVector<CCValAssign, 16> RVLocs;
2052   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2053                  *DAG.getContext());
2054   CCInfo.AnalyzeCallResult(Ins, RetCC);
2055 
2056   // Copy all of the result registers out of their specified physreg.
2057   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2058     CCValAssign VA = RVLocs[i];
2059     SDValue Val;
2060 
2061     if (VA.isRegLoc()) {
2062       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2063       Chain = Val.getValue(1);
2064       InFlag = Val.getValue(2);
2065     } else if (VA.isMemLoc()) {
2066       report_fatal_error("TODO: return values in memory");
2067     } else
2068       llvm_unreachable("unknown argument location type");
2069 
2070     switch (VA.getLocInfo()) {
2071     case CCValAssign::Full:
2072       break;
2073     case CCValAssign::BCvt:
2074       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2075       break;
2076     case CCValAssign::ZExt:
2077       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2078                         DAG.getValueType(VA.getValVT()));
2079       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2080       break;
2081     case CCValAssign::SExt:
2082       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2083                         DAG.getValueType(VA.getValVT()));
2084       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2085       break;
2086     case CCValAssign::AExt:
2087       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2088       break;
2089     default:
2090       llvm_unreachable("Unknown loc info!");
2091     }
2092 
2093     InVals.push_back(Val);
2094   }
2095 
2096   return Chain;
2097 }
2098 
2099 // Add code to pass special inputs required depending on used features separate
2100 // from the explicit user arguments present in the IR.
2101 void SITargetLowering::passSpecialInputs(
2102     CallLoweringInfo &CLI,
2103     const SIMachineFunctionInfo &Info,
2104     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2105     SmallVectorImpl<SDValue> &MemOpChains,
2106     SDValue Chain,
2107     SDValue StackPtr) const {
2108   // If we don't have a call site, this was a call inserted by
2109   // legalization. These can never use special inputs.
2110   if (!CLI.CS)
2111     return;
2112 
2113   const Function *CalleeFunc = CLI.CS.getCalledFunction();
2114   assert(CalleeFunc);
2115 
2116   SelectionDAG &DAG = CLI.DAG;
2117   const SDLoc &DL = CLI.DL;
2118 
2119   const SISubtarget *ST = getSubtarget();
2120   const SIRegisterInfo *TRI = ST->getRegisterInfo();
2121 
2122   auto &ArgUsageInfo =
2123     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2124   const AMDGPUFunctionArgInfo &CalleeArgInfo
2125     = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2126 
2127   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2128 
2129   // TODO: Unify with private memory register handling. This is complicated by
2130   // the fact that at least in kernels, the input argument is not necessarily
2131   // in the same location as the input.
2132   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2133     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2134     AMDGPUFunctionArgInfo::QUEUE_PTR,
2135     AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2136     AMDGPUFunctionArgInfo::DISPATCH_ID,
2137     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2138     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2139     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2140     AMDGPUFunctionArgInfo::WORKITEM_ID_X,
2141     AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
2142     AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
2143     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2144   };
2145 
2146   for (auto InputID : InputRegs) {
2147     const ArgDescriptor *OutgoingArg;
2148     const TargetRegisterClass *ArgRC;
2149 
2150     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2151     if (!OutgoingArg)
2152       continue;
2153 
2154     const ArgDescriptor *IncomingArg;
2155     const TargetRegisterClass *IncomingArgRC;
2156     std::tie(IncomingArg, IncomingArgRC)
2157       = CallerArgInfo.getPreloadedValue(InputID);
2158     assert(IncomingArgRC == ArgRC);
2159 
2160     // All special arguments are ints for now.
2161     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2162     SDValue InputReg;
2163 
2164     if (IncomingArg) {
2165       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2166     } else {
2167       // The implicit arg ptr is special because it doesn't have a corresponding
2168       // input for kernels, and is computed from the kernarg segment pointer.
2169       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2170       InputReg = getImplicitArgPtr(DAG, DL);
2171     }
2172 
2173     if (OutgoingArg->isRegister()) {
2174       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2175     } else {
2176       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, StackPtr,
2177                                               InputReg,
2178                                               OutgoingArg->getStackOffset());
2179       MemOpChains.push_back(ArgStore);
2180     }
2181   }
2182 }
2183 
2184 static bool canGuaranteeTCO(CallingConv::ID CC) {
2185   return CC == CallingConv::Fast;
2186 }
2187 
2188 /// Return true if we might ever do TCO for calls with this calling convention.
2189 static bool mayTailCallThisCC(CallingConv::ID CC) {
2190   switch (CC) {
2191   case CallingConv::C:
2192     return true;
2193   default:
2194     return canGuaranteeTCO(CC);
2195   }
2196 }
2197 
2198 bool SITargetLowering::isEligibleForTailCallOptimization(
2199     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2200     const SmallVectorImpl<ISD::OutputArg> &Outs,
2201     const SmallVectorImpl<SDValue> &OutVals,
2202     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2203   if (!mayTailCallThisCC(CalleeCC))
2204     return false;
2205 
2206   MachineFunction &MF = DAG.getMachineFunction();
2207   const Function &CallerF = MF.getFunction();
2208   CallingConv::ID CallerCC = CallerF.getCallingConv();
2209   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2210   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2211 
2212   // Kernels aren't callable, and don't have a live in return address so it
2213   // doesn't make sense to do a tail call with entry functions.
2214   if (!CallerPreserved)
2215     return false;
2216 
2217   bool CCMatch = CallerCC == CalleeCC;
2218 
2219   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2220     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2221       return true;
2222     return false;
2223   }
2224 
2225   // TODO: Can we handle var args?
2226   if (IsVarArg)
2227     return false;
2228 
2229   for (const Argument &Arg : CallerF.args()) {
2230     if (Arg.hasByValAttr())
2231       return false;
2232   }
2233 
2234   LLVMContext &Ctx = *DAG.getContext();
2235 
2236   // Check that the call results are passed in the same way.
2237   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2238                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2239                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2240     return false;
2241 
2242   // The callee has to preserve all registers the caller needs to preserve.
2243   if (!CCMatch) {
2244     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2245     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2246       return false;
2247   }
2248 
2249   // Nothing more to check if the callee is taking no arguments.
2250   if (Outs.empty())
2251     return true;
2252 
2253   SmallVector<CCValAssign, 16> ArgLocs;
2254   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2255 
2256   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2257 
2258   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2259   // If the stack arguments for this call do not fit into our own save area then
2260   // the call cannot be made tail.
2261   // TODO: Is this really necessary?
2262   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2263     return false;
2264 
2265   const MachineRegisterInfo &MRI = MF.getRegInfo();
2266   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2267 }
2268 
2269 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2270   if (!CI->isTailCall())
2271     return false;
2272 
2273   const Function *ParentFn = CI->getParent()->getParent();
2274   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2275     return false;
2276 
2277   auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2278   return (Attr.getValueAsString() != "true");
2279 }
2280 
2281 // The wave scratch offset register is used as the global base pointer.
2282 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2283                                     SmallVectorImpl<SDValue> &InVals) const {
2284   SelectionDAG &DAG = CLI.DAG;
2285   const SDLoc &DL = CLI.DL;
2286   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2287   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2288   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2289   SDValue Chain = CLI.Chain;
2290   SDValue Callee = CLI.Callee;
2291   bool &IsTailCall = CLI.IsTailCall;
2292   CallingConv::ID CallConv = CLI.CallConv;
2293   bool IsVarArg = CLI.IsVarArg;
2294   bool IsSibCall = false;
2295   bool IsThisReturn = false;
2296   MachineFunction &MF = DAG.getMachineFunction();
2297 
2298   if (IsVarArg) {
2299     return lowerUnhandledCall(CLI, InVals,
2300                               "unsupported call to variadic function ");
2301   }
2302 
2303   if (!CLI.CS.getCalledFunction()) {
2304     return lowerUnhandledCall(CLI, InVals,
2305                               "unsupported indirect call to function ");
2306   }
2307 
2308   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2309     return lowerUnhandledCall(CLI, InVals,
2310                               "unsupported required tail call to function ");
2311   }
2312 
2313   // The first 4 bytes are reserved for the callee's emergency stack slot.
2314   const unsigned CalleeUsableStackOffset = 4;
2315 
2316   if (IsTailCall) {
2317     IsTailCall = isEligibleForTailCallOptimization(
2318       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2319     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2320       report_fatal_error("failed to perform tail call elimination on a call "
2321                          "site marked musttail");
2322     }
2323 
2324     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2325 
2326     // A sibling call is one where we're under the usual C ABI and not planning
2327     // to change that but can still do a tail call:
2328     if (!TailCallOpt && IsTailCall)
2329       IsSibCall = true;
2330 
2331     if (IsTailCall)
2332       ++NumTailCalls;
2333   }
2334 
2335   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Callee)) {
2336     // FIXME: Remove this hack for function pointer types after removing
2337     // support of old address space mapping. In the new address space
2338     // mapping the pointer in default address space is 64 bit, therefore
2339     // does not need this hack.
2340     if (Callee.getValueType() == MVT::i32) {
2341       const GlobalValue *GV = GA->getGlobal();
2342       Callee = DAG.getGlobalAddress(GV, DL, MVT::i64, GA->getOffset(), false,
2343                                     GA->getTargetFlags());
2344     }
2345   }
2346   assert(Callee.getValueType() == MVT::i64);
2347 
2348   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2349 
2350   // Analyze operands of the call, assigning locations to each operand.
2351   SmallVector<CCValAssign, 16> ArgLocs;
2352   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2353   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2354   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2355 
2356   // Get a count of how many bytes are to be pushed on the stack.
2357   unsigned NumBytes = CCInfo.getNextStackOffset();
2358 
2359   if (IsSibCall) {
2360     // Since we're not changing the ABI to make this a tail call, the memory
2361     // operands are already available in the caller's incoming argument space.
2362     NumBytes = 0;
2363   }
2364 
2365   // FPDiff is the byte offset of the call's argument area from the callee's.
2366   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2367   // by this amount for a tail call. In a sibling call it must be 0 because the
2368   // caller will deallocate the entire stack and the callee still expects its
2369   // arguments to begin at SP+0. Completely unused for non-tail calls.
2370   int32_t FPDiff = 0;
2371   MachineFrameInfo &MFI = MF.getFrameInfo();
2372   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2373 
2374   SDValue CallerSavedFP;
2375 
2376   // Adjust the stack pointer for the new arguments...
2377   // These operations are automatically eliminated by the prolog/epilog pass
2378   if (!IsSibCall) {
2379     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2380 
2381     unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2382 
2383     // In the HSA case, this should be an identity copy.
2384     SDValue ScratchRSrcReg
2385       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2386     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2387 
2388     // TODO: Don't hardcode these registers and get from the callee function.
2389     SDValue ScratchWaveOffsetReg
2390       = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2391     RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2392 
2393     if (!Info->isEntryFunction()) {
2394       // Avoid clobbering this function's FP value. In the current convention
2395       // callee will overwrite this, so do save/restore around the call site.
2396       CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2397                                          Info->getFrameOffsetReg(), MVT::i32);
2398     }
2399   }
2400 
2401   // Stack pointer relative accesses are done by changing the offset SGPR. This
2402   // is just the VGPR offset component.
2403   SDValue StackPtr = DAG.getConstant(CalleeUsableStackOffset, DL, MVT::i32);
2404 
2405   SmallVector<SDValue, 8> MemOpChains;
2406   MVT PtrVT = MVT::i32;
2407 
2408   // Walk the register/memloc assignments, inserting copies/loads.
2409   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2410        ++i, ++realArgIdx) {
2411     CCValAssign &VA = ArgLocs[i];
2412     SDValue Arg = OutVals[realArgIdx];
2413 
2414     // Promote the value if needed.
2415     switch (VA.getLocInfo()) {
2416     case CCValAssign::Full:
2417       break;
2418     case CCValAssign::BCvt:
2419       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2420       break;
2421     case CCValAssign::ZExt:
2422       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2423       break;
2424     case CCValAssign::SExt:
2425       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2426       break;
2427     case CCValAssign::AExt:
2428       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2429       break;
2430     case CCValAssign::FPExt:
2431       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2432       break;
2433     default:
2434       llvm_unreachable("Unknown loc info!");
2435     }
2436 
2437     if (VA.isRegLoc()) {
2438       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2439     } else {
2440       assert(VA.isMemLoc());
2441 
2442       SDValue DstAddr;
2443       MachinePointerInfo DstInfo;
2444 
2445       unsigned LocMemOffset = VA.getLocMemOffset();
2446       int32_t Offset = LocMemOffset;
2447 
2448       SDValue PtrOff = DAG.getObjectPtrOffset(DL, StackPtr, Offset);
2449 
2450       if (IsTailCall) {
2451         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2452         unsigned OpSize = Flags.isByVal() ?
2453           Flags.getByValSize() : VA.getValVT().getStoreSize();
2454 
2455         Offset = Offset + FPDiff;
2456         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2457 
2458         DstAddr = DAG.getObjectPtrOffset(DL, DAG.getFrameIndex(FI, PtrVT),
2459                                          StackPtr);
2460         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2461 
2462         // Make sure any stack arguments overlapping with where we're storing
2463         // are loaded before this eventual operation. Otherwise they'll be
2464         // clobbered.
2465 
2466         // FIXME: Why is this really necessary? This seems to just result in a
2467         // lot of code to copy the stack and write them back to the same
2468         // locations, which are supposed to be immutable?
2469         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2470       } else {
2471         DstAddr = PtrOff;
2472         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2473       }
2474 
2475       if (Outs[i].Flags.isByVal()) {
2476         SDValue SizeNode =
2477             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2478         SDValue Cpy = DAG.getMemcpy(
2479             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2480             /*isVol = */ false, /*AlwaysInline = */ true,
2481             /*isTailCall = */ false, DstInfo,
2482             MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2483                 *DAG.getContext(), AMDGPUASI.PRIVATE_ADDRESS))));
2484 
2485         MemOpChains.push_back(Cpy);
2486       } else {
2487         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
2488         MemOpChains.push_back(Store);
2489       }
2490     }
2491   }
2492 
2493   // Copy special input registers after user input arguments.
2494   passSpecialInputs(CLI, *Info, RegsToPass, MemOpChains, Chain, StackPtr);
2495 
2496   if (!MemOpChains.empty())
2497     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2498 
2499   // Build a sequence of copy-to-reg nodes chained together with token chain
2500   // and flag operands which copy the outgoing args into the appropriate regs.
2501   SDValue InFlag;
2502   for (auto &RegToPass : RegsToPass) {
2503     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2504                              RegToPass.second, InFlag);
2505     InFlag = Chain.getValue(1);
2506   }
2507 
2508 
2509   SDValue PhysReturnAddrReg;
2510   if (IsTailCall) {
2511     // Since the return is being combined with the call, we need to pass on the
2512     // return address.
2513 
2514     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2515     SDValue ReturnAddrReg = CreateLiveInRegister(
2516       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2517 
2518     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2519                                         MVT::i64);
2520     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2521     InFlag = Chain.getValue(1);
2522   }
2523 
2524   // We don't usually want to end the call-sequence here because we would tidy
2525   // the frame up *after* the call, however in the ABI-changing tail-call case
2526   // we've carefully laid out the parameters so that when sp is reset they'll be
2527   // in the correct location.
2528   if (IsTailCall && !IsSibCall) {
2529     Chain = DAG.getCALLSEQ_END(Chain,
2530                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2531                                DAG.getTargetConstant(0, DL, MVT::i32),
2532                                InFlag, DL);
2533     InFlag = Chain.getValue(1);
2534   }
2535 
2536   std::vector<SDValue> Ops;
2537   Ops.push_back(Chain);
2538   Ops.push_back(Callee);
2539 
2540   if (IsTailCall) {
2541     // Each tail call may have to adjust the stack by a different amount, so
2542     // this information must travel along with the operation for eventual
2543     // consumption by emitEpilogue.
2544     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2545 
2546     Ops.push_back(PhysReturnAddrReg);
2547   }
2548 
2549   // Add argument registers to the end of the list so that they are known live
2550   // into the call.
2551   for (auto &RegToPass : RegsToPass) {
2552     Ops.push_back(DAG.getRegister(RegToPass.first,
2553                                   RegToPass.second.getValueType()));
2554   }
2555 
2556   // Add a register mask operand representing the call-preserved registers.
2557 
2558   const AMDGPURegisterInfo *TRI = Subtarget->getRegisterInfo();
2559   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2560   assert(Mask && "Missing call preserved mask for calling convention");
2561   Ops.push_back(DAG.getRegisterMask(Mask));
2562 
2563   if (InFlag.getNode())
2564     Ops.push_back(InFlag);
2565 
2566   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2567 
2568   // If we're doing a tall call, use a TC_RETURN here rather than an
2569   // actual call instruction.
2570   if (IsTailCall) {
2571     MFI.setHasTailCall();
2572     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2573   }
2574 
2575   // Returns a chain and a flag for retval copy to use.
2576   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2577   Chain = Call.getValue(0);
2578   InFlag = Call.getValue(1);
2579 
2580   if (CallerSavedFP) {
2581     SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2582     Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2583     InFlag = Chain.getValue(1);
2584   }
2585 
2586   uint64_t CalleePopBytes = NumBytes;
2587   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2588                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2589                              InFlag, DL);
2590   if (!Ins.empty())
2591     InFlag = Chain.getValue(1);
2592 
2593   // Handle result values, copying them out of physregs into vregs that we
2594   // return.
2595   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2596                          InVals, IsThisReturn,
2597                          IsThisReturn ? OutVals[0] : SDValue());
2598 }
2599 
2600 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2601                                              SelectionDAG &DAG) const {
2602   unsigned Reg = StringSwitch<unsigned>(RegName)
2603     .Case("m0", AMDGPU::M0)
2604     .Case("exec", AMDGPU::EXEC)
2605     .Case("exec_lo", AMDGPU::EXEC_LO)
2606     .Case("exec_hi", AMDGPU::EXEC_HI)
2607     .Case("flat_scratch", AMDGPU::FLAT_SCR)
2608     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2609     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2610     .Default(AMDGPU::NoRegister);
2611 
2612   if (Reg == AMDGPU::NoRegister) {
2613     report_fatal_error(Twine("invalid register name \""
2614                              + StringRef(RegName)  + "\"."));
2615 
2616   }
2617 
2618   if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS &&
2619       Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2620     report_fatal_error(Twine("invalid register \""
2621                              + StringRef(RegName)  + "\" for subtarget."));
2622   }
2623 
2624   switch (Reg) {
2625   case AMDGPU::M0:
2626   case AMDGPU::EXEC_LO:
2627   case AMDGPU::EXEC_HI:
2628   case AMDGPU::FLAT_SCR_LO:
2629   case AMDGPU::FLAT_SCR_HI:
2630     if (VT.getSizeInBits() == 32)
2631       return Reg;
2632     break;
2633   case AMDGPU::EXEC:
2634   case AMDGPU::FLAT_SCR:
2635     if (VT.getSizeInBits() == 64)
2636       return Reg;
2637     break;
2638   default:
2639     llvm_unreachable("missing register type checking");
2640   }
2641 
2642   report_fatal_error(Twine("invalid type for register \""
2643                            + StringRef(RegName) + "\"."));
2644 }
2645 
2646 // If kill is not the last instruction, split the block so kill is always a
2647 // proper terminator.
2648 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2649                                                     MachineBasicBlock *BB) const {
2650   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2651 
2652   MachineBasicBlock::iterator SplitPoint(&MI);
2653   ++SplitPoint;
2654 
2655   if (SplitPoint == BB->end()) {
2656     // Don't bother with a new block.
2657     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2658     return BB;
2659   }
2660 
2661   MachineFunction *MF = BB->getParent();
2662   MachineBasicBlock *SplitBB
2663     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2664 
2665   MF->insert(++MachineFunction::iterator(BB), SplitBB);
2666   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2667 
2668   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2669   BB->addSuccessor(SplitBB);
2670 
2671   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2672   return SplitBB;
2673 }
2674 
2675 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2676 // wavefront. If the value is uniform and just happens to be in a VGPR, this
2677 // will only do one iteration. In the worst case, this will loop 64 times.
2678 //
2679 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2680 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
2681   const SIInstrInfo *TII,
2682   MachineRegisterInfo &MRI,
2683   MachineBasicBlock &OrigBB,
2684   MachineBasicBlock &LoopBB,
2685   const DebugLoc &DL,
2686   const MachineOperand &IdxReg,
2687   unsigned InitReg,
2688   unsigned ResultReg,
2689   unsigned PhiReg,
2690   unsigned InitSaveExecReg,
2691   int Offset,
2692   bool UseGPRIdxMode,
2693   bool IsIndirectSrc) {
2694   MachineBasicBlock::iterator I = LoopBB.begin();
2695 
2696   unsigned PhiExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2697   unsigned NewExec = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2698   unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2699   unsigned CondReg = MRI.createVirtualRegister(&AMDGPU::SReg_64RegClass);
2700 
2701   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2702     .addReg(InitReg)
2703     .addMBB(&OrigBB)
2704     .addReg(ResultReg)
2705     .addMBB(&LoopBB);
2706 
2707   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2708     .addReg(InitSaveExecReg)
2709     .addMBB(&OrigBB)
2710     .addReg(NewExec)
2711     .addMBB(&LoopBB);
2712 
2713   // Read the next variant <- also loop target.
2714   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2715     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2716 
2717   // Compare the just read M0 value to all possible Idx values.
2718   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2719     .addReg(CurrentIdxReg)
2720     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2721 
2722   // Update EXEC, save the original EXEC value to VCC.
2723   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_AND_SAVEEXEC_B64), NewExec)
2724     .addReg(CondReg, RegState::Kill);
2725 
2726   MRI.setSimpleHint(NewExec, CondReg);
2727 
2728   if (UseGPRIdxMode) {
2729     unsigned IdxReg;
2730     if (Offset == 0) {
2731       IdxReg = CurrentIdxReg;
2732     } else {
2733       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2734       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2735         .addReg(CurrentIdxReg, RegState::Kill)
2736         .addImm(Offset);
2737     }
2738     unsigned IdxMode = IsIndirectSrc ?
2739       VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2740     MachineInstr *SetOn =
2741       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2742       .addReg(IdxReg, RegState::Kill)
2743       .addImm(IdxMode);
2744     SetOn->getOperand(3).setIsUndef();
2745   } else {
2746     // Move index from VCC into M0
2747     if (Offset == 0) {
2748       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2749         .addReg(CurrentIdxReg, RegState::Kill);
2750     } else {
2751       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2752         .addReg(CurrentIdxReg, RegState::Kill)
2753         .addImm(Offset);
2754     }
2755   }
2756 
2757   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
2758   MachineInstr *InsertPt =
2759     BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_XOR_B64), AMDGPU::EXEC)
2760     .addReg(AMDGPU::EXEC)
2761     .addReg(NewExec);
2762 
2763   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
2764   // s_cbranch_scc0?
2765 
2766   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
2767   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
2768     .addMBB(&LoopBB);
2769 
2770   return InsertPt->getIterator();
2771 }
2772 
2773 // This has slightly sub-optimal regalloc when the source vector is killed by
2774 // the read. The register allocator does not understand that the kill is
2775 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
2776 // subregister from it, using 1 more VGPR than necessary. This was saved when
2777 // this was expanded after register allocation.
2778 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
2779                                                   MachineBasicBlock &MBB,
2780                                                   MachineInstr &MI,
2781                                                   unsigned InitResultReg,
2782                                                   unsigned PhiReg,
2783                                                   int Offset,
2784                                                   bool UseGPRIdxMode,
2785                                                   bool IsIndirectSrc) {
2786   MachineFunction *MF = MBB.getParent();
2787   MachineRegisterInfo &MRI = MF->getRegInfo();
2788   const DebugLoc &DL = MI.getDebugLoc();
2789   MachineBasicBlock::iterator I(&MI);
2790 
2791   unsigned DstReg = MI.getOperand(0).getReg();
2792   unsigned SaveExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2793   unsigned TmpExec = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
2794 
2795   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
2796 
2797   // Save the EXEC mask
2798   BuildMI(MBB, I, DL, TII->get(AMDGPU::S_MOV_B64), SaveExec)
2799     .addReg(AMDGPU::EXEC);
2800 
2801   // To insert the loop we need to split the block. Move everything after this
2802   // point to a new block, and insert a new empty block between the two.
2803   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
2804   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2805   MachineFunction::iterator MBBI(MBB);
2806   ++MBBI;
2807 
2808   MF->insert(MBBI, LoopBB);
2809   MF->insert(MBBI, RemainderBB);
2810 
2811   LoopBB->addSuccessor(LoopBB);
2812   LoopBB->addSuccessor(RemainderBB);
2813 
2814   // Move the rest of the block into a new block.
2815   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
2816   RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
2817 
2818   MBB.addSuccessor(LoopBB);
2819 
2820   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2821 
2822   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
2823                                       InitResultReg, DstReg, PhiReg, TmpExec,
2824                                       Offset, UseGPRIdxMode, IsIndirectSrc);
2825 
2826   MachineBasicBlock::iterator First = RemainderBB->begin();
2827   BuildMI(*RemainderBB, First, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC)
2828     .addReg(SaveExec);
2829 
2830   return InsPt;
2831 }
2832 
2833 // Returns subreg index, offset
2834 static std::pair<unsigned, int>
2835 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
2836                             const TargetRegisterClass *SuperRC,
2837                             unsigned VecReg,
2838                             int Offset) {
2839   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
2840 
2841   // Skip out of bounds offsets, or else we would end up using an undefined
2842   // register.
2843   if (Offset >= NumElts || Offset < 0)
2844     return std::make_pair(AMDGPU::sub0, Offset);
2845 
2846   return std::make_pair(AMDGPU::sub0 + Offset, 0);
2847 }
2848 
2849 // Return true if the index is an SGPR and was set.
2850 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
2851                                  MachineRegisterInfo &MRI,
2852                                  MachineInstr &MI,
2853                                  int Offset,
2854                                  bool UseGPRIdxMode,
2855                                  bool IsIndirectSrc) {
2856   MachineBasicBlock *MBB = MI.getParent();
2857   const DebugLoc &DL = MI.getDebugLoc();
2858   MachineBasicBlock::iterator I(&MI);
2859 
2860   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
2861   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
2862 
2863   assert(Idx->getReg() != AMDGPU::NoRegister);
2864 
2865   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
2866     return false;
2867 
2868   if (UseGPRIdxMode) {
2869     unsigned IdxMode = IsIndirectSrc ?
2870       VGPRIndexMode::SRC0_ENABLE : VGPRIndexMode::DST_ENABLE;
2871     if (Offset == 0) {
2872       MachineInstr *SetOn =
2873           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2874               .add(*Idx)
2875               .addImm(IdxMode);
2876 
2877       SetOn->getOperand(3).setIsUndef();
2878     } else {
2879       unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
2880       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
2881           .add(*Idx)
2882           .addImm(Offset);
2883       MachineInstr *SetOn =
2884         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2885         .addReg(Tmp, RegState::Kill)
2886         .addImm(IdxMode);
2887 
2888       SetOn->getOperand(3).setIsUndef();
2889     }
2890 
2891     return true;
2892   }
2893 
2894   if (Offset == 0) {
2895     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
2896       .add(*Idx);
2897   } else {
2898     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
2899       .add(*Idx)
2900       .addImm(Offset);
2901   }
2902 
2903   return true;
2904 }
2905 
2906 // Control flow needs to be inserted if indexing with a VGPR.
2907 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
2908                                           MachineBasicBlock &MBB,
2909                                           const SISubtarget &ST) {
2910   const SIInstrInfo *TII = ST.getInstrInfo();
2911   const SIRegisterInfo &TRI = TII->getRegisterInfo();
2912   MachineFunction *MF = MBB.getParent();
2913   MachineRegisterInfo &MRI = MF->getRegInfo();
2914 
2915   unsigned Dst = MI.getOperand(0).getReg();
2916   unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
2917   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
2918 
2919   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
2920 
2921   unsigned SubReg;
2922   std::tie(SubReg, Offset)
2923     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
2924 
2925   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
2926 
2927   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
2928     MachineBasicBlock::iterator I(&MI);
2929     const DebugLoc &DL = MI.getDebugLoc();
2930 
2931     if (UseGPRIdxMode) {
2932       // TODO: Look at the uses to avoid the copy. This may require rescheduling
2933       // to avoid interfering with other uses, so probably requires a new
2934       // optimization pass.
2935       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
2936         .addReg(SrcReg, RegState::Undef, SubReg)
2937         .addReg(SrcReg, RegState::Implicit)
2938         .addReg(AMDGPU::M0, RegState::Implicit);
2939       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2940     } else {
2941       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
2942         .addReg(SrcReg, RegState::Undef, SubReg)
2943         .addReg(SrcReg, RegState::Implicit);
2944     }
2945 
2946     MI.eraseFromParent();
2947 
2948     return &MBB;
2949   }
2950 
2951   const DebugLoc &DL = MI.getDebugLoc();
2952   MachineBasicBlock::iterator I(&MI);
2953 
2954   unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2955   unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
2956 
2957   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
2958 
2959   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
2960                               Offset, UseGPRIdxMode, true);
2961   MachineBasicBlock *LoopBB = InsPt->getParent();
2962 
2963   if (UseGPRIdxMode) {
2964     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
2965       .addReg(SrcReg, RegState::Undef, SubReg)
2966       .addReg(SrcReg, RegState::Implicit)
2967       .addReg(AMDGPU::M0, RegState::Implicit);
2968     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
2969   } else {
2970     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
2971       .addReg(SrcReg, RegState::Undef, SubReg)
2972       .addReg(SrcReg, RegState::Implicit);
2973   }
2974 
2975   MI.eraseFromParent();
2976 
2977   return LoopBB;
2978 }
2979 
2980 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
2981                                  const TargetRegisterClass *VecRC) {
2982   switch (TRI.getRegSizeInBits(*VecRC)) {
2983   case 32: // 4 bytes
2984     return AMDGPU::V_MOVRELD_B32_V1;
2985   case 64: // 8 bytes
2986     return AMDGPU::V_MOVRELD_B32_V2;
2987   case 128: // 16 bytes
2988     return AMDGPU::V_MOVRELD_B32_V4;
2989   case 256: // 32 bytes
2990     return AMDGPU::V_MOVRELD_B32_V8;
2991   case 512: // 64 bytes
2992     return AMDGPU::V_MOVRELD_B32_V16;
2993   default:
2994     llvm_unreachable("unsupported size for MOVRELD pseudos");
2995   }
2996 }
2997 
2998 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
2999                                           MachineBasicBlock &MBB,
3000                                           const SISubtarget &ST) {
3001   const SIInstrInfo *TII = ST.getInstrInfo();
3002   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3003   MachineFunction *MF = MBB.getParent();
3004   MachineRegisterInfo &MRI = MF->getRegInfo();
3005 
3006   unsigned Dst = MI.getOperand(0).getReg();
3007   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3008   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3009   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3010   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3011   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3012 
3013   // This can be an immediate, but will be folded later.
3014   assert(Val->getReg());
3015 
3016   unsigned SubReg;
3017   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3018                                                          SrcVec->getReg(),
3019                                                          Offset);
3020   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3021 
3022   if (Idx->getReg() == AMDGPU::NoRegister) {
3023     MachineBasicBlock::iterator I(&MI);
3024     const DebugLoc &DL = MI.getDebugLoc();
3025 
3026     assert(Offset == 0);
3027 
3028     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3029         .add(*SrcVec)
3030         .add(*Val)
3031         .addImm(SubReg);
3032 
3033     MI.eraseFromParent();
3034     return &MBB;
3035   }
3036 
3037   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3038     MachineBasicBlock::iterator I(&MI);
3039     const DebugLoc &DL = MI.getDebugLoc();
3040 
3041     if (UseGPRIdxMode) {
3042       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3043           .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3044           .add(*Val)
3045           .addReg(Dst, RegState::ImplicitDefine)
3046           .addReg(SrcVec->getReg(), RegState::Implicit)
3047           .addReg(AMDGPU::M0, RegState::Implicit);
3048 
3049       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3050     } else {
3051       const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3052 
3053       BuildMI(MBB, I, DL, MovRelDesc)
3054           .addReg(Dst, RegState::Define)
3055           .addReg(SrcVec->getReg())
3056           .add(*Val)
3057           .addImm(SubReg - AMDGPU::sub0);
3058     }
3059 
3060     MI.eraseFromParent();
3061     return &MBB;
3062   }
3063 
3064   if (Val->isReg())
3065     MRI.clearKillFlags(Val->getReg());
3066 
3067   const DebugLoc &DL = MI.getDebugLoc();
3068 
3069   unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3070 
3071   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3072                               Offset, UseGPRIdxMode, false);
3073   MachineBasicBlock *LoopBB = InsPt->getParent();
3074 
3075   if (UseGPRIdxMode) {
3076     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3077         .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3078         .add(*Val)                               // src0
3079         .addReg(Dst, RegState::ImplicitDefine)
3080         .addReg(PhiReg, RegState::Implicit)
3081         .addReg(AMDGPU::M0, RegState::Implicit);
3082     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3083   } else {
3084     const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3085 
3086     BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3087         .addReg(Dst, RegState::Define)
3088         .addReg(PhiReg)
3089         .add(*Val)
3090         .addImm(SubReg - AMDGPU::sub0);
3091   }
3092 
3093   MI.eraseFromParent();
3094 
3095   return LoopBB;
3096 }
3097 
3098 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3099   MachineInstr &MI, MachineBasicBlock *BB) const {
3100 
3101   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3102   MachineFunction *MF = BB->getParent();
3103   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3104 
3105   if (TII->isMIMG(MI)) {
3106     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3107       report_fatal_error("missing mem operand from MIMG instruction");
3108     }
3109     // Add a memoperand for mimg instructions so that they aren't assumed to
3110     // be ordered memory instuctions.
3111 
3112     return BB;
3113   }
3114 
3115   switch (MI.getOpcode()) {
3116   case AMDGPU::S_ADD_U64_PSEUDO:
3117   case AMDGPU::S_SUB_U64_PSEUDO: {
3118     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3119     const DebugLoc &DL = MI.getDebugLoc();
3120 
3121     MachineOperand &Dest = MI.getOperand(0);
3122     MachineOperand &Src0 = MI.getOperand(1);
3123     MachineOperand &Src1 = MI.getOperand(2);
3124 
3125     unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3126     unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3127 
3128     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3129      Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3130      &AMDGPU::SReg_32_XM0RegClass);
3131     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3132       Src0, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3133       &AMDGPU::SReg_32_XM0RegClass);
3134 
3135     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3136       Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub0,
3137       &AMDGPU::SReg_32_XM0RegClass);
3138     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3139       Src1, &AMDGPU::SReg_64RegClass, AMDGPU::sub1,
3140       &AMDGPU::SReg_32_XM0RegClass);
3141 
3142     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3143 
3144     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3145     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3146     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3147       .add(Src0Sub0)
3148       .add(Src1Sub0);
3149     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3150       .add(Src0Sub1)
3151       .add(Src1Sub1);
3152     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3153       .addReg(DestSub0)
3154       .addImm(AMDGPU::sub0)
3155       .addReg(DestSub1)
3156       .addImm(AMDGPU::sub1);
3157     MI.eraseFromParent();
3158     return BB;
3159   }
3160   case AMDGPU::SI_INIT_M0: {
3161     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3162             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3163         .add(MI.getOperand(0));
3164     MI.eraseFromParent();
3165     return BB;
3166   }
3167   case AMDGPU::SI_INIT_EXEC:
3168     // This should be before all vector instructions.
3169     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3170             AMDGPU::EXEC)
3171         .addImm(MI.getOperand(0).getImm());
3172     MI.eraseFromParent();
3173     return BB;
3174 
3175   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3176     // Extract the thread count from an SGPR input and set EXEC accordingly.
3177     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3178     //
3179     // S_BFE_U32 count, input, {shift, 7}
3180     // S_BFM_B64 exec, count, 0
3181     // S_CMP_EQ_U32 count, 64
3182     // S_CMOV_B64 exec, -1
3183     MachineInstr *FirstMI = &*BB->begin();
3184     MachineRegisterInfo &MRI = MF->getRegInfo();
3185     unsigned InputReg = MI.getOperand(0).getReg();
3186     unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3187     bool Found = false;
3188 
3189     // Move the COPY of the input reg to the beginning, so that we can use it.
3190     for (auto I = BB->begin(); I != &MI; I++) {
3191       if (I->getOpcode() != TargetOpcode::COPY ||
3192           I->getOperand(0).getReg() != InputReg)
3193         continue;
3194 
3195       if (I == FirstMI) {
3196         FirstMI = &*++BB->begin();
3197       } else {
3198         I->removeFromParent();
3199         BB->insert(FirstMI, &*I);
3200       }
3201       Found = true;
3202       break;
3203     }
3204     assert(Found);
3205     (void)Found;
3206 
3207     // This should be before all vector instructions.
3208     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3209         .addReg(InputReg)
3210         .addImm((MI.getOperand(1).getImm() & 0x7f) | 0x70000);
3211     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFM_B64),
3212             AMDGPU::EXEC)
3213         .addReg(CountReg)
3214         .addImm(0);
3215     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3216         .addReg(CountReg, RegState::Kill)
3217         .addImm(64);
3218     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMOV_B64),
3219             AMDGPU::EXEC)
3220         .addImm(-1);
3221     MI.eraseFromParent();
3222     return BB;
3223   }
3224 
3225   case AMDGPU::GET_GROUPSTATICSIZE: {
3226     DebugLoc DL = MI.getDebugLoc();
3227     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3228         .add(MI.getOperand(0))
3229         .addImm(MFI->getLDSSize());
3230     MI.eraseFromParent();
3231     return BB;
3232   }
3233   case AMDGPU::SI_INDIRECT_SRC_V1:
3234   case AMDGPU::SI_INDIRECT_SRC_V2:
3235   case AMDGPU::SI_INDIRECT_SRC_V4:
3236   case AMDGPU::SI_INDIRECT_SRC_V8:
3237   case AMDGPU::SI_INDIRECT_SRC_V16:
3238     return emitIndirectSrc(MI, *BB, *getSubtarget());
3239   case AMDGPU::SI_INDIRECT_DST_V1:
3240   case AMDGPU::SI_INDIRECT_DST_V2:
3241   case AMDGPU::SI_INDIRECT_DST_V4:
3242   case AMDGPU::SI_INDIRECT_DST_V8:
3243   case AMDGPU::SI_INDIRECT_DST_V16:
3244     return emitIndirectDst(MI, *BB, *getSubtarget());
3245   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3246   case AMDGPU::SI_KILL_I1_PSEUDO:
3247     return splitKillBlock(MI, BB);
3248   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3249     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3250 
3251     unsigned Dst = MI.getOperand(0).getReg();
3252     unsigned Src0 = MI.getOperand(1).getReg();
3253     unsigned Src1 = MI.getOperand(2).getReg();
3254     const DebugLoc &DL = MI.getDebugLoc();
3255     unsigned SrcCond = MI.getOperand(3).getReg();
3256 
3257     unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3258     unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3259     unsigned SrcCondCopy = MRI.createVirtualRegister(&AMDGPU::SReg_64_XEXECRegClass);
3260 
3261     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3262       .addReg(SrcCond);
3263     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3264       .addReg(Src0, 0, AMDGPU::sub0)
3265       .addReg(Src1, 0, AMDGPU::sub0)
3266       .addReg(SrcCondCopy);
3267     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3268       .addReg(Src0, 0, AMDGPU::sub1)
3269       .addReg(Src1, 0, AMDGPU::sub1)
3270       .addReg(SrcCondCopy);
3271 
3272     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3273       .addReg(DstLo)
3274       .addImm(AMDGPU::sub0)
3275       .addReg(DstHi)
3276       .addImm(AMDGPU::sub1);
3277     MI.eraseFromParent();
3278     return BB;
3279   }
3280   case AMDGPU::SI_BR_UNDEF: {
3281     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3282     const DebugLoc &DL = MI.getDebugLoc();
3283     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3284                            .add(MI.getOperand(0));
3285     Br->getOperand(1).setIsUndef(true); // read undef SCC
3286     MI.eraseFromParent();
3287     return BB;
3288   }
3289   case AMDGPU::ADJCALLSTACKUP:
3290   case AMDGPU::ADJCALLSTACKDOWN: {
3291     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3292     MachineInstrBuilder MIB(*MF, &MI);
3293 
3294     // Add an implicit use of the frame offset reg to prevent the restore copy
3295     // inserted after the call from being reorderd after stack operations in the
3296     // the caller's frame.
3297     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3298         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3299         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3300     return BB;
3301   }
3302   case AMDGPU::SI_CALL_ISEL:
3303   case AMDGPU::SI_TCRETURN_ISEL: {
3304     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3305     const DebugLoc &DL = MI.getDebugLoc();
3306     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3307 
3308     MachineRegisterInfo &MRI = MF->getRegInfo();
3309     unsigned GlobalAddrReg = MI.getOperand(0).getReg();
3310     MachineInstr *PCRel = MRI.getVRegDef(GlobalAddrReg);
3311     assert(PCRel->getOpcode() == AMDGPU::SI_PC_ADD_REL_OFFSET);
3312 
3313     const GlobalValue *G = PCRel->getOperand(1).getGlobal();
3314 
3315     MachineInstrBuilder MIB;
3316     if (MI.getOpcode() == AMDGPU::SI_CALL_ISEL) {
3317       MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg)
3318         .add(MI.getOperand(0))
3319         .addGlobalAddress(G);
3320     } else {
3321       MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_TCRETURN))
3322         .add(MI.getOperand(0))
3323         .addGlobalAddress(G);
3324 
3325       // There is an additional imm operand for tcreturn, but it should be in the
3326       // right place already.
3327     }
3328 
3329     for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
3330       MIB.add(MI.getOperand(I));
3331 
3332     MIB.setMemRefs(MI.memoperands_begin(), MI.memoperands_end());
3333     MI.eraseFromParent();
3334     return BB;
3335   }
3336   default:
3337     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3338   }
3339 }
3340 
3341 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3342   return isTypeLegal(VT.getScalarType());
3343 }
3344 
3345 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3346   // This currently forces unfolding various combinations of fsub into fma with
3347   // free fneg'd operands. As long as we have fast FMA (controlled by
3348   // isFMAFasterThanFMulAndFAdd), we should perform these.
3349 
3350   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3351   // most of these combines appear to be cycle neutral but save on instruction
3352   // count / code size.
3353   return true;
3354 }
3355 
3356 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3357                                          EVT VT) const {
3358   if (!VT.isVector()) {
3359     return MVT::i1;
3360   }
3361   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3362 }
3363 
3364 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3365   // TODO: Should i16 be used always if legal? For now it would force VALU
3366   // shifts.
3367   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3368 }
3369 
3370 // Answering this is somewhat tricky and depends on the specific device which
3371 // have different rates for fma or all f64 operations.
3372 //
3373 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3374 // regardless of which device (although the number of cycles differs between
3375 // devices), so it is always profitable for f64.
3376 //
3377 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3378 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3379 // which we can always do even without fused FP ops since it returns the same
3380 // result as the separate operations and since it is always full
3381 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3382 // however does not support denormals, so we do report fma as faster if we have
3383 // a fast fma device and require denormals.
3384 //
3385 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3386   VT = VT.getScalarType();
3387 
3388   switch (VT.getSimpleVT().SimpleTy) {
3389   case MVT::f32: {
3390     // This is as fast on some subtargets. However, we always have full rate f32
3391     // mad available which returns the same result as the separate operations
3392     // which we should prefer over fma. We can't use this if we want to support
3393     // denormals, so only report this in these cases.
3394     if (Subtarget->hasFP32Denormals())
3395       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3396 
3397     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3398     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3399   }
3400   case MVT::f64:
3401     return true;
3402   case MVT::f16:
3403     return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3404   default:
3405     break;
3406   }
3407 
3408   return false;
3409 }
3410 
3411 //===----------------------------------------------------------------------===//
3412 // Custom DAG Lowering Operations
3413 //===----------------------------------------------------------------------===//
3414 
3415 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3416 // wider vector type is legal.
3417 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3418                                              SelectionDAG &DAG) const {
3419   unsigned Opc = Op.getOpcode();
3420   EVT VT = Op.getValueType();
3421   assert(VT == MVT::v4f16);
3422 
3423   SDValue Lo, Hi;
3424   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3425 
3426   SDLoc SL(Op);
3427   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3428                              Op->getFlags());
3429   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3430                              Op->getFlags());
3431 
3432   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3433 }
3434 
3435 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3436 // wider vector type is legal.
3437 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3438                                               SelectionDAG &DAG) const {
3439   unsigned Opc = Op.getOpcode();
3440   EVT VT = Op.getValueType();
3441   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3442 
3443   SDValue Lo0, Hi0;
3444   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3445   SDValue Lo1, Hi1;
3446   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3447 
3448   SDLoc SL(Op);
3449 
3450   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3451                              Op->getFlags());
3452   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3453                              Op->getFlags());
3454 
3455   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3456 }
3457 
3458 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3459   switch (Op.getOpcode()) {
3460   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3461   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3462   case ISD::LOAD: {
3463     SDValue Result = LowerLOAD(Op, DAG);
3464     assert((!Result.getNode() ||
3465             Result.getNode()->getNumValues() == 2) &&
3466            "Load should return a value and a chain");
3467     return Result;
3468   }
3469 
3470   case ISD::FSIN:
3471   case ISD::FCOS:
3472     return LowerTrig(Op, DAG);
3473   case ISD::SELECT: return LowerSELECT(Op, DAG);
3474   case ISD::FDIV: return LowerFDIV(Op, DAG);
3475   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3476   case ISD::STORE: return LowerSTORE(Op, DAG);
3477   case ISD::GlobalAddress: {
3478     MachineFunction &MF = DAG.getMachineFunction();
3479     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3480     return LowerGlobalAddress(MFI, Op, DAG);
3481   }
3482   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3483   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3484   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3485   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3486   case ISD::INSERT_VECTOR_ELT:
3487     return lowerINSERT_VECTOR_ELT(Op, DAG);
3488   case ISD::EXTRACT_VECTOR_ELT:
3489     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3490   case ISD::BUILD_VECTOR:
3491     return lowerBUILD_VECTOR(Op, DAG);
3492   case ISD::FP_ROUND:
3493     return lowerFP_ROUND(Op, DAG);
3494   case ISD::TRAP:
3495     return lowerTRAP(Op, DAG);
3496   case ISD::DEBUGTRAP:
3497     return lowerDEBUGTRAP(Op, DAG);
3498   case ISD::FABS:
3499   case ISD::FNEG:
3500     return splitUnaryVectorOp(Op, DAG);
3501   case ISD::SHL:
3502   case ISD::SRA:
3503   case ISD::SRL:
3504   case ISD::ADD:
3505   case ISD::SUB:
3506   case ISD::MUL:
3507   case ISD::SMIN:
3508   case ISD::SMAX:
3509   case ISD::UMIN:
3510   case ISD::UMAX:
3511   case ISD::FMINNUM:
3512   case ISD::FMAXNUM:
3513   case ISD::FADD:
3514   case ISD::FMUL:
3515     return splitBinaryVectorOp(Op, DAG);
3516   }
3517   return SDValue();
3518 }
3519 
3520 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
3521                                        const SDLoc &DL,
3522                                        SelectionDAG &DAG, bool Unpacked) {
3523   if (!LoadVT.isVector())
3524     return Result;
3525 
3526   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
3527     // Truncate to v2i16/v4i16.
3528     EVT IntLoadVT = LoadVT.changeTypeToInteger();
3529 
3530     // Workaround legalizer not scalarizing truncate after vector op
3531     // legalization byt not creating intermediate vector trunc.
3532     SmallVector<SDValue, 4> Elts;
3533     DAG.ExtractVectorElements(Result, Elts);
3534     for (SDValue &Elt : Elts)
3535       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
3536 
3537     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
3538 
3539     // Bitcast to original type (v2f16/v4f16).
3540     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3541   }
3542 
3543   // Cast back to the original packed type.
3544   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3545 }
3546 
3547 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
3548                                               MemSDNode *M,
3549                                               SelectionDAG &DAG,
3550                                               bool IsIntrinsic) const {
3551   SDLoc DL(M);
3552   SmallVector<SDValue, 10> Ops;
3553   Ops.reserve(M->getNumOperands());
3554 
3555   Ops.push_back(M->getOperand(0));
3556   if (IsIntrinsic)
3557     Ops.push_back(DAG.getConstant(Opcode, DL, MVT::i32));
3558 
3559   // Skip 1, as it is the intrinsic ID.
3560   for (unsigned I = 2, E = M->getNumOperands(); I != E; ++I)
3561     Ops.push_back(M->getOperand(I));
3562 
3563   bool Unpacked = Subtarget->hasUnpackedD16VMem();
3564   EVT LoadVT = M->getValueType(0);
3565 
3566   EVT EquivLoadVT = LoadVT;
3567   if (Unpacked && LoadVT.isVector()) {
3568     EquivLoadVT = LoadVT.isVector() ?
3569       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3570                        LoadVT.getVectorNumElements()) : LoadVT;
3571   }
3572 
3573   // Change from v4f16/v2f16 to EquivLoadVT.
3574   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
3575 
3576   SDValue Load
3577     = DAG.getMemIntrinsicNode(
3578       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
3579       VTList, Ops, M->getMemoryVT(),
3580       M->getMemOperand());
3581   if (!Unpacked) // Just adjusted the opcode.
3582     return Load;
3583 
3584   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
3585 
3586   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
3587 }
3588 
3589 void SITargetLowering::ReplaceNodeResults(SDNode *N,
3590                                           SmallVectorImpl<SDValue> &Results,
3591                                           SelectionDAG &DAG) const {
3592   switch (N->getOpcode()) {
3593   case ISD::INSERT_VECTOR_ELT: {
3594     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3595       Results.push_back(Res);
3596     return;
3597   }
3598   case ISD::EXTRACT_VECTOR_ELT: {
3599     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3600       Results.push_back(Res);
3601     return;
3602   }
3603   case ISD::INTRINSIC_WO_CHAIN: {
3604     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3605     switch (IID) {
3606     case Intrinsic::amdgcn_cvt_pkrtz: {
3607       SDValue Src0 = N->getOperand(1);
3608       SDValue Src1 = N->getOperand(2);
3609       SDLoc SL(N);
3610       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
3611                                 Src0, Src1);
3612       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3613       return;
3614     }
3615     case Intrinsic::amdgcn_cvt_pknorm_i16:
3616     case Intrinsic::amdgcn_cvt_pknorm_u16:
3617     case Intrinsic::amdgcn_cvt_pk_i16:
3618     case Intrinsic::amdgcn_cvt_pk_u16: {
3619       SDValue Src0 = N->getOperand(1);
3620       SDValue Src1 = N->getOperand(2);
3621       SDLoc SL(N);
3622       unsigned Opcode;
3623 
3624       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
3625         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
3626       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
3627         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
3628       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
3629         Opcode = AMDGPUISD::CVT_PK_I16_I32;
3630       else
3631         Opcode = AMDGPUISD::CVT_PK_U16_U32;
3632 
3633       SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
3634       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
3635       return;
3636     }
3637     }
3638     break;
3639   }
3640   case ISD::INTRINSIC_W_CHAIN: {
3641     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
3642       Results.push_back(Res);
3643       Results.push_back(Res.getValue(1));
3644       return;
3645     }
3646 
3647     break;
3648   }
3649   case ISD::SELECT: {
3650     SDLoc SL(N);
3651     EVT VT = N->getValueType(0);
3652     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
3653     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
3654     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
3655 
3656     EVT SelectVT = NewVT;
3657     if (NewVT.bitsLT(MVT::i32)) {
3658       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
3659       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
3660       SelectVT = MVT::i32;
3661     }
3662 
3663     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
3664                                     N->getOperand(0), LHS, RHS);
3665 
3666     if (NewVT != SelectVT)
3667       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
3668     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
3669     return;
3670   }
3671   case ISD::FNEG: {
3672     if (N->getValueType(0) != MVT::v2f16)
3673       break;
3674 
3675     SDLoc SL(N);
3676     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3677 
3678     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
3679                              BC,
3680                              DAG.getConstant(0x80008000, SL, MVT::i32));
3681     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3682     return;
3683   }
3684   case ISD::FABS: {
3685     if (N->getValueType(0) != MVT::v2f16)
3686       break;
3687 
3688     SDLoc SL(N);
3689     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
3690 
3691     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
3692                              BC,
3693                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
3694     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
3695     return;
3696   }
3697   default:
3698     break;
3699   }
3700 }
3701 
3702 /// Helper function for LowerBRCOND
3703 static SDNode *findUser(SDValue Value, unsigned Opcode) {
3704 
3705   SDNode *Parent = Value.getNode();
3706   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
3707        I != E; ++I) {
3708 
3709     if (I.getUse().get() != Value)
3710       continue;
3711 
3712     if (I->getOpcode() == Opcode)
3713       return *I;
3714   }
3715   return nullptr;
3716 }
3717 
3718 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
3719   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
3720     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
3721     case Intrinsic::amdgcn_if:
3722       return AMDGPUISD::IF;
3723     case Intrinsic::amdgcn_else:
3724       return AMDGPUISD::ELSE;
3725     case Intrinsic::amdgcn_loop:
3726       return AMDGPUISD::LOOP;
3727     case Intrinsic::amdgcn_end_cf:
3728       llvm_unreachable("should not occur");
3729     default:
3730       return 0;
3731     }
3732   }
3733 
3734   // break, if_break, else_break are all only used as inputs to loop, not
3735   // directly as branch conditions.
3736   return 0;
3737 }
3738 
3739 void SITargetLowering::createDebuggerPrologueStackObjects(
3740     MachineFunction &MF) const {
3741   // Create stack objects that are used for emitting debugger prologue.
3742   //
3743   // Debugger prologue writes work group IDs and work item IDs to scratch memory
3744   // at fixed location in the following format:
3745   //   offset 0:  work group ID x
3746   //   offset 4:  work group ID y
3747   //   offset 8:  work group ID z
3748   //   offset 16: work item ID x
3749   //   offset 20: work item ID y
3750   //   offset 24: work item ID z
3751   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3752   int ObjectIdx = 0;
3753 
3754   // For each dimension:
3755   for (unsigned i = 0; i < 3; ++i) {
3756     // Create fixed stack object for work group ID.
3757     ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4, true);
3758     Info->setDebuggerWorkGroupIDStackObjectIndex(i, ObjectIdx);
3759     // Create fixed stack object for work item ID.
3760     ObjectIdx = MF.getFrameInfo().CreateFixedObject(4, i * 4 + 16, true);
3761     Info->setDebuggerWorkItemIDStackObjectIndex(i, ObjectIdx);
3762   }
3763 }
3764 
3765 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
3766   const Triple &TT = getTargetMachine().getTargetTriple();
3767   return (GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
3768           GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
3769          AMDGPU::shouldEmitConstantsToTextSection(TT);
3770 }
3771 
3772 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
3773   return (GV->getType()->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
3774           GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
3775           GV->getType()->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
3776          !shouldEmitFixup(GV) &&
3777          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
3778 }
3779 
3780 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
3781   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
3782 }
3783 
3784 /// This transforms the control flow intrinsics to get the branch destination as
3785 /// last parameter, also switches branch target with BR if the need arise
3786 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
3787                                       SelectionDAG &DAG) const {
3788   SDLoc DL(BRCOND);
3789 
3790   SDNode *Intr = BRCOND.getOperand(1).getNode();
3791   SDValue Target = BRCOND.getOperand(2);
3792   SDNode *BR = nullptr;
3793   SDNode *SetCC = nullptr;
3794 
3795   if (Intr->getOpcode() == ISD::SETCC) {
3796     // As long as we negate the condition everything is fine
3797     SetCC = Intr;
3798     Intr = SetCC->getOperand(0).getNode();
3799 
3800   } else {
3801     // Get the target from BR if we don't negate the condition
3802     BR = findUser(BRCOND, ISD::BR);
3803     Target = BR->getOperand(1);
3804   }
3805 
3806   // FIXME: This changes the types of the intrinsics instead of introducing new
3807   // nodes with the correct types.
3808   // e.g. llvm.amdgcn.loop
3809 
3810   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
3811   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
3812 
3813   unsigned CFNode = isCFIntrinsic(Intr);
3814   if (CFNode == 0) {
3815     // This is a uniform branch so we don't need to legalize.
3816     return BRCOND;
3817   }
3818 
3819   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
3820                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
3821 
3822   assert(!SetCC ||
3823         (SetCC->getConstantOperandVal(1) == 1 &&
3824          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
3825                                                              ISD::SETNE));
3826 
3827   // operands of the new intrinsic call
3828   SmallVector<SDValue, 4> Ops;
3829   if (HaveChain)
3830     Ops.push_back(BRCOND.getOperand(0));
3831 
3832   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
3833   Ops.push_back(Target);
3834 
3835   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
3836 
3837   // build the new intrinsic call
3838   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
3839 
3840   if (!HaveChain) {
3841     SDValue Ops[] =  {
3842       SDValue(Result, 0),
3843       BRCOND.getOperand(0)
3844     };
3845 
3846     Result = DAG.getMergeValues(Ops, DL).getNode();
3847   }
3848 
3849   if (BR) {
3850     // Give the branch instruction our target
3851     SDValue Ops[] = {
3852       BR->getOperand(0),
3853       BRCOND.getOperand(2)
3854     };
3855     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
3856     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
3857     BR = NewBR.getNode();
3858   }
3859 
3860   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
3861 
3862   // Copy the intrinsic results to registers
3863   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
3864     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
3865     if (!CopyToReg)
3866       continue;
3867 
3868     Chain = DAG.getCopyToReg(
3869       Chain, DL,
3870       CopyToReg->getOperand(1),
3871       SDValue(Result, i - 1),
3872       SDValue());
3873 
3874     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
3875   }
3876 
3877   // Remove the old intrinsic from the chain
3878   DAG.ReplaceAllUsesOfValueWith(
3879     SDValue(Intr, Intr->getNumValues() - 1),
3880     Intr->getOperand(0));
3881 
3882   return Chain;
3883 }
3884 
3885 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
3886                                             SDValue Op,
3887                                             const SDLoc &DL,
3888                                             EVT VT) const {
3889   return Op.getValueType().bitsLE(VT) ?
3890       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
3891       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
3892 }
3893 
3894 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
3895   assert(Op.getValueType() == MVT::f16 &&
3896          "Do not know how to custom lower FP_ROUND for non-f16 type");
3897 
3898   SDValue Src = Op.getOperand(0);
3899   EVT SrcVT = Src.getValueType();
3900   if (SrcVT != MVT::f64)
3901     return Op;
3902 
3903   SDLoc DL(Op);
3904 
3905   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
3906   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
3907   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
3908 }
3909 
3910 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
3911   SDLoc SL(Op);
3912   SDValue Chain = Op.getOperand(0);
3913 
3914   if (Subtarget->getTrapHandlerAbi() != SISubtarget::TrapHandlerAbiHsa ||
3915       !Subtarget->isTrapHandlerEnabled())
3916     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
3917 
3918   MachineFunction &MF = DAG.getMachineFunction();
3919   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3920   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
3921   assert(UserSGPR != AMDGPU::NoRegister);
3922   SDValue QueuePtr = CreateLiveInRegister(
3923     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
3924   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
3925   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
3926                                    QueuePtr, SDValue());
3927   SDValue Ops[] = {
3928     ToReg,
3929     DAG.getTargetConstant(SISubtarget::TrapIDLLVMTrap, SL, MVT::i16),
3930     SGPR01,
3931     ToReg.getValue(1)
3932   };
3933   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
3934 }
3935 
3936 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
3937   SDLoc SL(Op);
3938   SDValue Chain = Op.getOperand(0);
3939   MachineFunction &MF = DAG.getMachineFunction();
3940 
3941   if (Subtarget->getTrapHandlerAbi() != SISubtarget::TrapHandlerAbiHsa ||
3942       !Subtarget->isTrapHandlerEnabled()) {
3943     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
3944                                      "debugtrap handler not supported",
3945                                      Op.getDebugLoc(),
3946                                      DS_Warning);
3947     LLVMContext &Ctx = MF.getFunction().getContext();
3948     Ctx.diagnose(NoTrap);
3949     return Chain;
3950   }
3951 
3952   SDValue Ops[] = {
3953     Chain,
3954     DAG.getTargetConstant(SISubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
3955   };
3956   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
3957 }
3958 
3959 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
3960                                              SelectionDAG &DAG) const {
3961   // FIXME: Use inline constants (src_{shared, private}_base) instead.
3962   if (Subtarget->hasApertureRegs()) {
3963     unsigned Offset = AS == AMDGPUASI.LOCAL_ADDRESS ?
3964         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
3965         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
3966     unsigned WidthM1 = AS == AMDGPUASI.LOCAL_ADDRESS ?
3967         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
3968         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
3969     unsigned Encoding =
3970         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
3971         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
3972         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
3973 
3974     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
3975     SDValue ApertureReg = SDValue(
3976         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
3977     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
3978     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
3979   }
3980 
3981   MachineFunction &MF = DAG.getMachineFunction();
3982   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3983   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
3984   assert(UserSGPR != AMDGPU::NoRegister);
3985 
3986   SDValue QueuePtr = CreateLiveInRegister(
3987     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
3988 
3989   // Offset into amd_queue_t for group_segment_aperture_base_hi /
3990   // private_segment_aperture_base_hi.
3991   uint32_t StructOffset = (AS == AMDGPUASI.LOCAL_ADDRESS) ? 0x40 : 0x44;
3992 
3993   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
3994 
3995   // TODO: Use custom target PseudoSourceValue.
3996   // TODO: We should use the value from the IR intrinsic call, but it might not
3997   // be available and how do we get it?
3998   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
3999                                               AMDGPUASI.CONSTANT_ADDRESS));
4000 
4001   MachinePointerInfo PtrInfo(V, StructOffset);
4002   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4003                      MinAlign(64, StructOffset),
4004                      MachineMemOperand::MODereferenceable |
4005                          MachineMemOperand::MOInvariant);
4006 }
4007 
4008 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4009                                              SelectionDAG &DAG) const {
4010   SDLoc SL(Op);
4011   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4012 
4013   SDValue Src = ASC->getOperand(0);
4014   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4015 
4016   const AMDGPUTargetMachine &TM =
4017     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4018 
4019   // flat -> local/private
4020   if (ASC->getSrcAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
4021     unsigned DestAS = ASC->getDestAddressSpace();
4022 
4023     if (DestAS == AMDGPUASI.LOCAL_ADDRESS ||
4024         DestAS == AMDGPUASI.PRIVATE_ADDRESS) {
4025       unsigned NullVal = TM.getNullPointerValue(DestAS);
4026       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4027       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4028       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4029 
4030       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4031                          NonNull, Ptr, SegmentNullPtr);
4032     }
4033   }
4034 
4035   // local/private -> flat
4036   if (ASC->getDestAddressSpace() == AMDGPUASI.FLAT_ADDRESS) {
4037     unsigned SrcAS = ASC->getSrcAddressSpace();
4038 
4039     if (SrcAS == AMDGPUASI.LOCAL_ADDRESS ||
4040         SrcAS == AMDGPUASI.PRIVATE_ADDRESS) {
4041       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4042       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4043 
4044       SDValue NonNull
4045         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4046 
4047       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4048       SDValue CvtPtr
4049         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4050 
4051       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4052                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4053                          FlatNullPtr);
4054     }
4055   }
4056 
4057   // global <-> flat are no-ops and never emitted.
4058 
4059   const MachineFunction &MF = DAG.getMachineFunction();
4060   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4061     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4062   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4063 
4064   return DAG.getUNDEF(ASC->getValueType(0));
4065 }
4066 
4067 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4068                                                  SelectionDAG &DAG) const {
4069   SDValue Vec = Op.getOperand(0);
4070   SDValue InsVal = Op.getOperand(1);
4071   SDValue Idx = Op.getOperand(2);
4072   EVT VecVT = Vec.getValueType();
4073   EVT EltVT = VecVT.getVectorElementType();
4074   unsigned VecSize = VecVT.getSizeInBits();
4075   unsigned EltSize = EltVT.getSizeInBits();
4076 
4077 
4078   assert(VecSize <= 64);
4079 
4080   unsigned NumElts = VecVT.getVectorNumElements();
4081   SDLoc SL(Op);
4082   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4083 
4084   if (NumElts == 4 && EltSize == 16 && KIdx) {
4085     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4086 
4087     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4088                                  DAG.getConstant(0, SL, MVT::i32));
4089     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4090                                  DAG.getConstant(1, SL, MVT::i32));
4091 
4092     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4093     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4094 
4095     unsigned Idx = KIdx->getZExtValue();
4096     bool InsertLo = Idx < 2;
4097     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4098       InsertLo ? LoVec : HiVec,
4099       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4100       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4101 
4102     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4103 
4104     SDValue Concat = InsertLo ?
4105       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4106       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4107 
4108     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4109   }
4110 
4111   if (isa<ConstantSDNode>(Idx))
4112     return SDValue();
4113 
4114   MVT IntVT = MVT::getIntegerVT(VecSize);
4115 
4116   // Avoid stack access for dynamic indexing.
4117   SDValue Val = InsVal;
4118   if (InsVal.getValueType() == MVT::f16)
4119       Val = DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal);
4120 
4121   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4122   SDValue ExtVal = DAG.getNode(ISD::ZERO_EXTEND, SL, IntVT, Val);
4123 
4124   assert(isPowerOf2_32(EltSize));
4125   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4126 
4127   // Convert vector index to bit-index.
4128   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4129 
4130   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4131   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4132                             DAG.getConstant(0xffff, SL, IntVT),
4133                             ScaledIdx);
4134 
4135   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4136   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4137                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4138 
4139   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4140   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4141 }
4142 
4143 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4144                                                   SelectionDAG &DAG) const {
4145   SDLoc SL(Op);
4146 
4147   EVT ResultVT = Op.getValueType();
4148   SDValue Vec = Op.getOperand(0);
4149   SDValue Idx = Op.getOperand(1);
4150   EVT VecVT = Vec.getValueType();
4151   unsigned VecSize = VecVT.getSizeInBits();
4152   EVT EltVT = VecVT.getVectorElementType();
4153   assert(VecSize <= 64);
4154 
4155   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4156 
4157   // Make sure we do any optimizations that will make it easier to fold
4158   // source modifiers before obscuring it with bit operations.
4159 
4160   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4161   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4162     return Combined;
4163 
4164   unsigned EltSize = EltVT.getSizeInBits();
4165   assert(isPowerOf2_32(EltSize));
4166 
4167   MVT IntVT = MVT::getIntegerVT(VecSize);
4168   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4169 
4170   // Convert vector index to bit-index (* EltSize)
4171   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4172 
4173   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4174   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4175 
4176   if (ResultVT == MVT::f16) {
4177     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4178     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4179   }
4180 
4181   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4182 }
4183 
4184 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4185                                             SelectionDAG &DAG) const {
4186   SDLoc SL(Op);
4187   EVT VT = Op.getValueType();
4188 
4189   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4190     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4191 
4192     // Turn into pair of packed build_vectors.
4193     // TODO: Special case for constants that can be materialized with s_mov_b64.
4194     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4195                                     { Op.getOperand(0), Op.getOperand(1) });
4196     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4197                                     { Op.getOperand(2), Op.getOperand(3) });
4198 
4199     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4200     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4201 
4202     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4203     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4204   }
4205 
4206   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4207 
4208   SDValue Lo = Op.getOperand(0);
4209   SDValue Hi = Op.getOperand(1);
4210 
4211   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4212   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4213 
4214   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4215   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4216 
4217   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4218                               DAG.getConstant(16, SL, MVT::i32));
4219 
4220   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4221 
4222   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4223 }
4224 
4225 bool
4226 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4227   // We can fold offsets for anything that doesn't require a GOT relocation.
4228   return (GA->getAddressSpace() == AMDGPUASI.GLOBAL_ADDRESS ||
4229           GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS ||
4230           GA->getAddressSpace() == AMDGPUASI.CONSTANT_ADDRESS_32BIT) &&
4231          !shouldEmitGOTReloc(GA->getGlobal());
4232 }
4233 
4234 static SDValue
4235 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4236                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
4237                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
4238   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4239   // lowered to the following code sequence:
4240   //
4241   // For constant address space:
4242   //   s_getpc_b64 s[0:1]
4243   //   s_add_u32 s0, s0, $symbol
4244   //   s_addc_u32 s1, s1, 0
4245   //
4246   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4247   //   a fixup or relocation is emitted to replace $symbol with a literal
4248   //   constant, which is a pc-relative offset from the encoding of the $symbol
4249   //   operand to the global variable.
4250   //
4251   // For global address space:
4252   //   s_getpc_b64 s[0:1]
4253   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4254   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4255   //
4256   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4257   //   fixups or relocations are emitted to replace $symbol@*@lo and
4258   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
4259   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
4260   //   operand to the global variable.
4261   //
4262   // What we want here is an offset from the value returned by s_getpc
4263   // (which is the address of the s_add_u32 instruction) to the global
4264   // variable, but since the encoding of $symbol starts 4 bytes after the start
4265   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
4266   // small. This requires us to add 4 to the global variable offset in order to
4267   // compute the correct address.
4268   SDValue PtrLo = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4269                                              GAFlags);
4270   SDValue PtrHi = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4,
4271                                              GAFlags == SIInstrInfo::MO_NONE ?
4272                                              GAFlags : GAFlags + 1);
4273   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
4274 }
4275 
4276 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
4277                                              SDValue Op,
4278                                              SelectionDAG &DAG) const {
4279   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
4280   const GlobalValue *GV = GSD->getGlobal();
4281 
4282   if (GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS &&
4283       GSD->getAddressSpace() != AMDGPUASI.CONSTANT_ADDRESS_32BIT &&
4284       GSD->getAddressSpace() != AMDGPUASI.GLOBAL_ADDRESS &&
4285       // FIXME: It isn't correct to rely on the type of the pointer. This should
4286       // be removed when address space 0 is 64-bit.
4287       !GV->getType()->getElementType()->isFunctionTy())
4288     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
4289 
4290   SDLoc DL(GSD);
4291   EVT PtrVT = Op.getValueType();
4292 
4293   if (shouldEmitFixup(GV))
4294     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
4295   else if (shouldEmitPCReloc(GV))
4296     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
4297                                    SIInstrInfo::MO_REL32);
4298 
4299   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
4300                                             SIInstrInfo::MO_GOTPCREL32);
4301 
4302   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
4303   PointerType *PtrTy = PointerType::get(Ty, AMDGPUASI.CONSTANT_ADDRESS);
4304   const DataLayout &DataLayout = DAG.getDataLayout();
4305   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
4306   // FIXME: Use a PseudoSourceValue once those can be assigned an address space.
4307   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
4308 
4309   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
4310                      MachineMemOperand::MODereferenceable |
4311                          MachineMemOperand::MOInvariant);
4312 }
4313 
4314 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
4315                                    const SDLoc &DL, SDValue V) const {
4316   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
4317   // the destination register.
4318   //
4319   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
4320   // so we will end up with redundant moves to m0.
4321   //
4322   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
4323 
4324   // A Null SDValue creates a glue result.
4325   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
4326                                   V, Chain);
4327   return SDValue(M0, 0);
4328 }
4329 
4330 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
4331                                                  SDValue Op,
4332                                                  MVT VT,
4333                                                  unsigned Offset) const {
4334   SDLoc SL(Op);
4335   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
4336                                            DAG.getEntryNode(), Offset, 4, false);
4337   // The local size values will have the hi 16-bits as zero.
4338   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
4339                      DAG.getValueType(VT));
4340 }
4341 
4342 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4343                                         EVT VT) {
4344   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4345                                       "non-hsa intrinsic with hsa target",
4346                                       DL.getDebugLoc());
4347   DAG.getContext()->diagnose(BadIntrin);
4348   return DAG.getUNDEF(VT);
4349 }
4350 
4351 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4352                                          EVT VT) {
4353   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4354                                       "intrinsic not supported on subtarget",
4355                                       DL.getDebugLoc());
4356   DAG.getContext()->diagnose(BadIntrin);
4357   return DAG.getUNDEF(VT);
4358 }
4359 
4360 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
4361                                     ArrayRef<SDValue> Elts) {
4362   assert(!Elts.empty());
4363   MVT Type;
4364   unsigned NumElts;
4365 
4366   if (Elts.size() == 1) {
4367     Type = MVT::f32;
4368     NumElts = 1;
4369   } else if (Elts.size() == 2) {
4370     Type = MVT::v2f32;
4371     NumElts = 2;
4372   } else if (Elts.size() <= 4) {
4373     Type = MVT::v4f32;
4374     NumElts = 4;
4375   } else if (Elts.size() <= 8) {
4376     Type = MVT::v8f32;
4377     NumElts = 8;
4378   } else {
4379     assert(Elts.size() <= 16);
4380     Type = MVT::v16f32;
4381     NumElts = 16;
4382   }
4383 
4384   SmallVector<SDValue, 16> VecElts(NumElts);
4385   for (unsigned i = 0; i < Elts.size(); ++i) {
4386     SDValue Elt = Elts[i];
4387     if (Elt.getValueType() != MVT::f32)
4388       Elt = DAG.getBitcast(MVT::f32, Elt);
4389     VecElts[i] = Elt;
4390   }
4391   for (unsigned i = Elts.size(); i < NumElts; ++i)
4392     VecElts[i] = DAG.getUNDEF(MVT::f32);
4393 
4394   if (NumElts == 1)
4395     return VecElts[0];
4396   return DAG.getBuildVector(Type, DL, VecElts);
4397 }
4398 
4399 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
4400                              SDValue *GLC, SDValue *SLC) {
4401   auto CachePolicyConst = dyn_cast<ConstantSDNode>(CachePolicy.getNode());
4402   if (!CachePolicyConst)
4403     return false;
4404 
4405   uint64_t Value = CachePolicyConst->getZExtValue();
4406   SDLoc DL(CachePolicy);
4407   if (GLC) {
4408     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
4409     Value &= ~(uint64_t)0x1;
4410   }
4411   if (SLC) {
4412     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
4413     Value &= ~(uint64_t)0x2;
4414   }
4415 
4416   return Value == 0;
4417 }
4418 
4419 SDValue SITargetLowering::lowerImage(SDValue Op,
4420                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
4421                                      SelectionDAG &DAG) const {
4422   SDLoc DL(Op);
4423   MachineFunction &MF = DAG.getMachineFunction();
4424   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4425       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
4426   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
4427 
4428   SmallVector<EVT, 2> ResultTypes(Op->value_begin(), Op->value_end());
4429   bool IsD16 = false;
4430   SDValue VData;
4431   int NumVDataDwords;
4432   unsigned AddrIdx; // Index of first address argument
4433   unsigned DMask;
4434 
4435   if (BaseOpcode->Atomic) {
4436     VData = Op.getOperand(2);
4437 
4438     bool Is64Bit = VData.getValueType() == MVT::i64;
4439     if (BaseOpcode->AtomicX2) {
4440       SDValue VData2 = Op.getOperand(3);
4441       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
4442                                  {VData, VData2});
4443       if (Is64Bit)
4444         VData = DAG.getBitcast(MVT::v4i32, VData);
4445 
4446       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
4447       DMask = Is64Bit ? 0xf : 0x3;
4448       NumVDataDwords = Is64Bit ? 4 : 2;
4449       AddrIdx = 4;
4450     } else {
4451       DMask = Is64Bit ? 0x3 : 0x1;
4452       NumVDataDwords = Is64Bit ? 2 : 1;
4453       AddrIdx = 3;
4454     }
4455   } else {
4456     unsigned DMaskIdx;
4457 
4458     if (BaseOpcode->Store) {
4459       VData = Op.getOperand(2);
4460 
4461       MVT StoreVT = VData.getSimpleValueType();
4462       if (StoreVT.getScalarType() == MVT::f16) {
4463         if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS ||
4464             !BaseOpcode->HasD16)
4465           return Op; // D16 is unsupported for this instruction
4466 
4467         IsD16 = true;
4468         VData = handleD16VData(VData, DAG);
4469       }
4470 
4471       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
4472       DMaskIdx = 3;
4473     } else {
4474       MVT LoadVT = Op.getSimpleValueType();
4475       if (LoadVT.getScalarType() == MVT::f16) {
4476         if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS ||
4477             !BaseOpcode->HasD16)
4478           return Op; // D16 is unsupported for this instruction
4479 
4480         IsD16 = true;
4481         if (LoadVT.isVector() && Subtarget->hasUnpackedD16VMem())
4482           ResultTypes[0] = (LoadVT == MVT::v2f16) ? MVT::v2i32 : MVT::v4i32;
4483       }
4484 
4485       NumVDataDwords = (ResultTypes[0].getSizeInBits() + 31) / 32;
4486       DMaskIdx = isa<MemSDNode>(Op) ? 2 : 1;
4487     }
4488 
4489     auto DMaskConst = dyn_cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
4490     if (!DMaskConst)
4491       return Op;
4492 
4493     AddrIdx = DMaskIdx + 1;
4494     DMask = DMaskConst->getZExtValue();
4495     if (!DMask && !BaseOpcode->Store) {
4496       // Eliminate no-op loads. Stores with dmask == 0 are *not* no-op: they
4497       // store the channels' default values.
4498       SDValue Undef = DAG.getUNDEF(Op.getValueType());
4499       if (isa<MemSDNode>(Op))
4500         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
4501       return Undef;
4502     }
4503   }
4504 
4505   unsigned NumVAddrs = BaseOpcode->NumExtraArgs +
4506                        (BaseOpcode->Gradients ? DimInfo->NumGradients : 0) +
4507                        (BaseOpcode->Coordinates ? DimInfo->NumCoords : 0) +
4508                        (BaseOpcode->LodOrClampOrMip ? 1 : 0);
4509   SmallVector<SDValue, 4> VAddrs;
4510   for (unsigned i = 0; i < NumVAddrs; ++i)
4511     VAddrs.push_back(Op.getOperand(AddrIdx + i));
4512   SDValue VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
4513 
4514   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
4515   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
4516   unsigned CtrlIdx; // Index of texfailctrl argument
4517   SDValue Unorm;
4518   if (!BaseOpcode->Sampler) {
4519     Unorm = True;
4520     CtrlIdx = AddrIdx + NumVAddrs + 1;
4521   } else {
4522     auto UnormConst =
4523         dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
4524     if (!UnormConst)
4525       return Op;
4526 
4527     Unorm = UnormConst->getZExtValue() ? True : False;
4528     CtrlIdx = AddrIdx + NumVAddrs + 3;
4529   }
4530 
4531   SDValue TexFail = Op.getOperand(CtrlIdx);
4532   auto TexFailConst = dyn_cast<ConstantSDNode>(TexFail.getNode());
4533   if (!TexFailConst || TexFailConst->getZExtValue() != 0)
4534     return Op;
4535 
4536   SDValue GLC;
4537   SDValue SLC;
4538   if (BaseOpcode->Atomic) {
4539     GLC = True; // TODO no-return optimization
4540     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC))
4541       return Op;
4542   } else {
4543     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC))
4544       return Op;
4545   }
4546 
4547   SmallVector<SDValue, 14> Ops;
4548   if (BaseOpcode->Store || BaseOpcode->Atomic)
4549     Ops.push_back(VData); // vdata
4550   Ops.push_back(VAddr);
4551   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
4552   if (BaseOpcode->Sampler)
4553     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
4554   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
4555   Ops.push_back(Unorm);
4556   Ops.push_back(GLC);
4557   Ops.push_back(SLC);
4558   Ops.push_back(False); // r128
4559   Ops.push_back(False); // tfe
4560   Ops.push_back(False); // lwe
4561   Ops.push_back(DimInfo->DA ? True : False);
4562   if (BaseOpcode->HasD16)
4563     Ops.push_back(IsD16 ? True : False);
4564   if (isa<MemSDNode>(Op))
4565     Ops.push_back(Op.getOperand(0)); // chain
4566 
4567   int NumVAddrDwords = VAddr.getValueType().getSizeInBits() / 32;
4568   int Opcode = -1;
4569 
4570   if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
4571     Opcode = AMDGPU::getMIMGOpcode(Intr->BaseOpcode, AMDGPU::MIMGEncGfx8,
4572                                    NumVDataDwords, NumVAddrDwords);
4573   if (Opcode == -1)
4574     Opcode = AMDGPU::getMIMGOpcode(Intr->BaseOpcode, AMDGPU::MIMGEncGfx6,
4575                                    NumVDataDwords, NumVAddrDwords);
4576   assert(Opcode != -1);
4577 
4578   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
4579   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
4580     MachineInstr::mmo_iterator MemRefs = MF.allocateMemRefsArray(1);
4581     *MemRefs = MemOp->getMemOperand();
4582     NewNode->setMemRefs(MemRefs, MemRefs + 1);
4583   }
4584 
4585   if (BaseOpcode->AtomicX2) {
4586     SmallVector<SDValue, 1> Elt;
4587     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
4588     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
4589   } else if (IsD16 && !BaseOpcode->Store) {
4590     MVT LoadVT = Op.getSimpleValueType();
4591     SDValue Adjusted = adjustLoadValueTypeImpl(
4592         SDValue(NewNode, 0), LoadVT, DL, DAG, Subtarget->hasUnpackedD16VMem());
4593     return DAG.getMergeValues({Adjusted, SDValue(NewNode, 1)}, DL);
4594   }
4595 
4596   return SDValue(NewNode, 0);
4597 }
4598 
4599 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
4600                                                   SelectionDAG &DAG) const {
4601   MachineFunction &MF = DAG.getMachineFunction();
4602   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
4603 
4604   EVT VT = Op.getValueType();
4605   SDLoc DL(Op);
4606   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
4607 
4608   // TODO: Should this propagate fast-math-flags?
4609 
4610   switch (IntrinsicID) {
4611   case Intrinsic::amdgcn_implicit_buffer_ptr: {
4612     if (getSubtarget()->isAmdCodeObjectV2(MF.getFunction()))
4613       return emitNonHSAIntrinsicError(DAG, DL, VT);
4614     return getPreloadedValue(DAG, *MFI, VT,
4615                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
4616   }
4617   case Intrinsic::amdgcn_dispatch_ptr:
4618   case Intrinsic::amdgcn_queue_ptr: {
4619     if (!Subtarget->isAmdCodeObjectV2(MF.getFunction())) {
4620       DiagnosticInfoUnsupported BadIntrin(
4621           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
4622           DL.getDebugLoc());
4623       DAG.getContext()->diagnose(BadIntrin);
4624       return DAG.getUNDEF(VT);
4625     }
4626 
4627     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
4628       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
4629     return getPreloadedValue(DAG, *MFI, VT, RegID);
4630   }
4631   case Intrinsic::amdgcn_implicitarg_ptr: {
4632     if (MFI->isEntryFunction())
4633       return getImplicitArgPtr(DAG, DL);
4634     return getPreloadedValue(DAG, *MFI, VT,
4635                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
4636   }
4637   case Intrinsic::amdgcn_kernarg_segment_ptr: {
4638     return getPreloadedValue(DAG, *MFI, VT,
4639                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
4640   }
4641   case Intrinsic::amdgcn_dispatch_id: {
4642     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
4643   }
4644   case Intrinsic::amdgcn_rcp:
4645     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
4646   case Intrinsic::amdgcn_rsq:
4647     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4648   case Intrinsic::amdgcn_rsq_legacy:
4649     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
4650       return emitRemovedIntrinsicError(DAG, DL, VT);
4651 
4652     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
4653   case Intrinsic::amdgcn_rcp_legacy:
4654     if (Subtarget->getGeneration() >= SISubtarget::VOLCANIC_ISLANDS)
4655       return emitRemovedIntrinsicError(DAG, DL, VT);
4656     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
4657   case Intrinsic::amdgcn_rsq_clamp: {
4658     if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
4659       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
4660 
4661     Type *Type = VT.getTypeForEVT(*DAG.getContext());
4662     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
4663     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
4664 
4665     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
4666     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
4667                               DAG.getConstantFP(Max, DL, VT));
4668     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
4669                        DAG.getConstantFP(Min, DL, VT));
4670   }
4671   case Intrinsic::r600_read_ngroups_x:
4672     if (Subtarget->isAmdHsaOS())
4673       return emitNonHSAIntrinsicError(DAG, DL, VT);
4674 
4675     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4676                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
4677   case Intrinsic::r600_read_ngroups_y:
4678     if (Subtarget->isAmdHsaOS())
4679       return emitNonHSAIntrinsicError(DAG, DL, VT);
4680 
4681     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4682                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
4683   case Intrinsic::r600_read_ngroups_z:
4684     if (Subtarget->isAmdHsaOS())
4685       return emitNonHSAIntrinsicError(DAG, DL, VT);
4686 
4687     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4688                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
4689   case Intrinsic::r600_read_global_size_x:
4690     if (Subtarget->isAmdHsaOS())
4691       return emitNonHSAIntrinsicError(DAG, DL, VT);
4692 
4693     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4694                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
4695   case Intrinsic::r600_read_global_size_y:
4696     if (Subtarget->isAmdHsaOS())
4697       return emitNonHSAIntrinsicError(DAG, DL, VT);
4698 
4699     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4700                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
4701   case Intrinsic::r600_read_global_size_z:
4702     if (Subtarget->isAmdHsaOS())
4703       return emitNonHSAIntrinsicError(DAG, DL, VT);
4704 
4705     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
4706                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
4707   case Intrinsic::r600_read_local_size_x:
4708     if (Subtarget->isAmdHsaOS())
4709       return emitNonHSAIntrinsicError(DAG, DL, VT);
4710 
4711     return lowerImplicitZextParam(DAG, Op, MVT::i16,
4712                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
4713   case Intrinsic::r600_read_local_size_y:
4714     if (Subtarget->isAmdHsaOS())
4715       return emitNonHSAIntrinsicError(DAG, DL, VT);
4716 
4717     return lowerImplicitZextParam(DAG, Op, MVT::i16,
4718                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
4719   case Intrinsic::r600_read_local_size_z:
4720     if (Subtarget->isAmdHsaOS())
4721       return emitNonHSAIntrinsicError(DAG, DL, VT);
4722 
4723     return lowerImplicitZextParam(DAG, Op, MVT::i16,
4724                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
4725   case Intrinsic::amdgcn_workgroup_id_x:
4726   case Intrinsic::r600_read_tgid_x:
4727     return getPreloadedValue(DAG, *MFI, VT,
4728                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
4729   case Intrinsic::amdgcn_workgroup_id_y:
4730   case Intrinsic::r600_read_tgid_y:
4731     return getPreloadedValue(DAG, *MFI, VT,
4732                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
4733   case Intrinsic::amdgcn_workgroup_id_z:
4734   case Intrinsic::r600_read_tgid_z:
4735     return getPreloadedValue(DAG, *MFI, VT,
4736                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
4737   case Intrinsic::amdgcn_workitem_id_x: {
4738   case Intrinsic::r600_read_tidig_x:
4739     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4740                           SDLoc(DAG.getEntryNode()),
4741                           MFI->getArgInfo().WorkItemIDX);
4742   }
4743   case Intrinsic::amdgcn_workitem_id_y:
4744   case Intrinsic::r600_read_tidig_y:
4745     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4746                           SDLoc(DAG.getEntryNode()),
4747                           MFI->getArgInfo().WorkItemIDY);
4748   case Intrinsic::amdgcn_workitem_id_z:
4749   case Intrinsic::r600_read_tidig_z:
4750     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
4751                           SDLoc(DAG.getEntryNode()),
4752                           MFI->getArgInfo().WorkItemIDZ);
4753   case AMDGPUIntrinsic::SI_load_const: {
4754     SDValue Ops[] = {
4755       Op.getOperand(1),
4756       Op.getOperand(2)
4757     };
4758 
4759     MachineMemOperand *MMO = MF.getMachineMemOperand(
4760         MachinePointerInfo(),
4761         MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
4762             MachineMemOperand::MOInvariant,
4763         VT.getStoreSize(), 4);
4764     return DAG.getMemIntrinsicNode(AMDGPUISD::LOAD_CONSTANT, DL,
4765                                    Op->getVTList(), Ops, VT, MMO);
4766   }
4767   case Intrinsic::amdgcn_fdiv_fast:
4768     return lowerFDIV_FAST(Op, DAG);
4769   case Intrinsic::amdgcn_interp_mov: {
4770     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4771     SDValue Glue = M0.getValue(1);
4772     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
4773                        Op.getOperand(2), Op.getOperand(3), Glue);
4774   }
4775   case Intrinsic::amdgcn_interp_p1: {
4776     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
4777     SDValue Glue = M0.getValue(1);
4778     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
4779                        Op.getOperand(2), Op.getOperand(3), Glue);
4780   }
4781   case Intrinsic::amdgcn_interp_p2: {
4782     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
4783     SDValue Glue = SDValue(M0.getNode(), 1);
4784     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
4785                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
4786                        Glue);
4787   }
4788   case Intrinsic::amdgcn_sin:
4789     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
4790 
4791   case Intrinsic::amdgcn_cos:
4792     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
4793 
4794   case Intrinsic::amdgcn_log_clamp: {
4795     if (Subtarget->getGeneration() < SISubtarget::VOLCANIC_ISLANDS)
4796       return SDValue();
4797 
4798     DiagnosticInfoUnsupported BadIntrin(
4799       MF.getFunction(), "intrinsic not supported on subtarget",
4800       DL.getDebugLoc());
4801       DAG.getContext()->diagnose(BadIntrin);
4802       return DAG.getUNDEF(VT);
4803   }
4804   case Intrinsic::amdgcn_ldexp:
4805     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
4806                        Op.getOperand(1), Op.getOperand(2));
4807 
4808   case Intrinsic::amdgcn_fract:
4809     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
4810 
4811   case Intrinsic::amdgcn_class:
4812     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
4813                        Op.getOperand(1), Op.getOperand(2));
4814   case Intrinsic::amdgcn_div_fmas:
4815     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
4816                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
4817                        Op.getOperand(4));
4818 
4819   case Intrinsic::amdgcn_div_fixup:
4820     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
4821                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4822 
4823   case Intrinsic::amdgcn_trig_preop:
4824     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
4825                        Op.getOperand(1), Op.getOperand(2));
4826   case Intrinsic::amdgcn_div_scale: {
4827     // 3rd parameter required to be a constant.
4828     const ConstantSDNode *Param = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4829     if (!Param)
4830       return DAG.getMergeValues({ DAG.getUNDEF(VT), DAG.getUNDEF(MVT::i1) }, DL);
4831 
4832     // Translate to the operands expected by the machine instruction. The
4833     // first parameter must be the same as the first instruction.
4834     SDValue Numerator = Op.getOperand(1);
4835     SDValue Denominator = Op.getOperand(2);
4836 
4837     // Note this order is opposite of the machine instruction's operations,
4838     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
4839     // intrinsic has the numerator as the first operand to match a normal
4840     // division operation.
4841 
4842     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
4843 
4844     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
4845                        Denominator, Numerator);
4846   }
4847   case Intrinsic::amdgcn_icmp: {
4848     const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4849     if (!CD)
4850       return DAG.getUNDEF(VT);
4851 
4852     int CondCode = CD->getSExtValue();
4853     if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4854         CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4855       return DAG.getUNDEF(VT);
4856 
4857     ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4858     ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4859     return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4860                        Op.getOperand(2), DAG.getCondCode(CCOpcode));
4861   }
4862   case Intrinsic::amdgcn_fcmp: {
4863     const auto *CD = dyn_cast<ConstantSDNode>(Op.getOperand(3));
4864     if (!CD)
4865       return DAG.getUNDEF(VT);
4866 
4867     int CondCode = CD->getSExtValue();
4868     if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4869         CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE)
4870       return DAG.getUNDEF(VT);
4871 
4872     FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4873     ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4874     return DAG.getNode(AMDGPUISD::SETCC, DL, VT, Op.getOperand(1),
4875                        Op.getOperand(2), DAG.getCondCode(CCOpcode));
4876   }
4877   case Intrinsic::amdgcn_fmed3:
4878     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
4879                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4880   case Intrinsic::amdgcn_fmul_legacy:
4881     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
4882                        Op.getOperand(1), Op.getOperand(2));
4883   case Intrinsic::amdgcn_sffbh:
4884     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
4885   case Intrinsic::amdgcn_sbfe:
4886     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
4887                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4888   case Intrinsic::amdgcn_ubfe:
4889     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
4890                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
4891   case Intrinsic::amdgcn_cvt_pkrtz:
4892   case Intrinsic::amdgcn_cvt_pknorm_i16:
4893   case Intrinsic::amdgcn_cvt_pknorm_u16:
4894   case Intrinsic::amdgcn_cvt_pk_i16:
4895   case Intrinsic::amdgcn_cvt_pk_u16: {
4896     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
4897     EVT VT = Op.getValueType();
4898     unsigned Opcode;
4899 
4900     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
4901       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
4902     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
4903       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4904     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
4905       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4906     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
4907       Opcode = AMDGPUISD::CVT_PK_I16_I32;
4908     else
4909       Opcode = AMDGPUISD::CVT_PK_U16_U32;
4910 
4911     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
4912                                Op.getOperand(1), Op.getOperand(2));
4913     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
4914   }
4915   case Intrinsic::amdgcn_wqm: {
4916     SDValue Src = Op.getOperand(1);
4917     return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
4918                    0);
4919   }
4920   case Intrinsic::amdgcn_wwm: {
4921     SDValue Src = Op.getOperand(1);
4922     return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
4923                    0);
4924   }
4925   case Intrinsic::amdgcn_fmad_ftz:
4926     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
4927                        Op.getOperand(2), Op.getOperand(3));
4928   default:
4929     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
4930             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
4931       return lowerImage(Op, ImageDimIntr, DAG);
4932 
4933     return Op;
4934   }
4935 }
4936 
4937 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
4938                                                  SelectionDAG &DAG) const {
4939   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
4940   SDLoc DL(Op);
4941 
4942   switch (IntrID) {
4943   case Intrinsic::amdgcn_atomic_inc:
4944   case Intrinsic::amdgcn_atomic_dec:
4945   case Intrinsic::amdgcn_ds_fadd:
4946   case Intrinsic::amdgcn_ds_fmin:
4947   case Intrinsic::amdgcn_ds_fmax: {
4948     MemSDNode *M = cast<MemSDNode>(Op);
4949     unsigned Opc;
4950     switch (IntrID) {
4951     case Intrinsic::amdgcn_atomic_inc:
4952       Opc = AMDGPUISD::ATOMIC_INC;
4953       break;
4954     case Intrinsic::amdgcn_atomic_dec:
4955       Opc = AMDGPUISD::ATOMIC_DEC;
4956       break;
4957     case Intrinsic::amdgcn_ds_fadd:
4958       Opc = AMDGPUISD::ATOMIC_LOAD_FADD;
4959       break;
4960     case Intrinsic::amdgcn_ds_fmin:
4961       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
4962       break;
4963     case Intrinsic::amdgcn_ds_fmax:
4964       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
4965       break;
4966     default:
4967       llvm_unreachable("Unknown intrinsic!");
4968     }
4969     SDValue Ops[] = {
4970       M->getOperand(0), // Chain
4971       M->getOperand(2), // Ptr
4972       M->getOperand(3)  // Value
4973     };
4974 
4975     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
4976                                    M->getMemoryVT(), M->getMemOperand());
4977   }
4978   case Intrinsic::amdgcn_buffer_load:
4979   case Intrinsic::amdgcn_buffer_load_format: {
4980     SDValue Ops[] = {
4981       Op.getOperand(0), // Chain
4982       Op.getOperand(2), // rsrc
4983       Op.getOperand(3), // vindex
4984       Op.getOperand(4), // offset
4985       Op.getOperand(5), // glc
4986       Op.getOperand(6)  // slc
4987     };
4988 
4989     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
4990         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
4991     EVT VT = Op.getValueType();
4992     EVT IntVT = VT.changeTypeToInteger();
4993     auto *M = cast<MemSDNode>(Op);
4994     EVT LoadVT = Op.getValueType();
4995     bool IsD16 = LoadVT.getScalarType() == MVT::f16;
4996     if (IsD16)
4997       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG);
4998 
4999     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5000                                    M->getMemOperand());
5001   }
5002   case Intrinsic::amdgcn_tbuffer_load: {
5003     MemSDNode *M = cast<MemSDNode>(Op);
5004     EVT LoadVT = Op.getValueType();
5005     bool IsD16 = LoadVT.getScalarType() == MVT::f16;
5006     if (IsD16) {
5007       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16, M, DAG);
5008     }
5009 
5010     SDValue Ops[] = {
5011       Op.getOperand(0),  // Chain
5012       Op.getOperand(2),  // rsrc
5013       Op.getOperand(3),  // vindex
5014       Op.getOperand(4),  // voffset
5015       Op.getOperand(5),  // soffset
5016       Op.getOperand(6),  // offset
5017       Op.getOperand(7),  // dfmt
5018       Op.getOperand(8),  // nfmt
5019       Op.getOperand(9),  // glc
5020       Op.getOperand(10)   // slc
5021     };
5022 
5023     return DAG.getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5024                                    Op->getVTList(), Ops, LoadVT,
5025                                    M->getMemOperand());
5026   }
5027   case Intrinsic::amdgcn_buffer_atomic_swap:
5028   case Intrinsic::amdgcn_buffer_atomic_add:
5029   case Intrinsic::amdgcn_buffer_atomic_sub:
5030   case Intrinsic::amdgcn_buffer_atomic_smin:
5031   case Intrinsic::amdgcn_buffer_atomic_umin:
5032   case Intrinsic::amdgcn_buffer_atomic_smax:
5033   case Intrinsic::amdgcn_buffer_atomic_umax:
5034   case Intrinsic::amdgcn_buffer_atomic_and:
5035   case Intrinsic::amdgcn_buffer_atomic_or:
5036   case Intrinsic::amdgcn_buffer_atomic_xor: {
5037     SDValue Ops[] = {
5038       Op.getOperand(0), // Chain
5039       Op.getOperand(2), // vdata
5040       Op.getOperand(3), // rsrc
5041       Op.getOperand(4), // vindex
5042       Op.getOperand(5), // offset
5043       Op.getOperand(6)  // slc
5044     };
5045     EVT VT = Op.getValueType();
5046 
5047     auto *M = cast<MemSDNode>(Op);
5048     unsigned Opcode = 0;
5049 
5050     switch (IntrID) {
5051     case Intrinsic::amdgcn_buffer_atomic_swap:
5052       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
5053       break;
5054     case Intrinsic::amdgcn_buffer_atomic_add:
5055       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
5056       break;
5057     case Intrinsic::amdgcn_buffer_atomic_sub:
5058       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
5059       break;
5060     case Intrinsic::amdgcn_buffer_atomic_smin:
5061       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
5062       break;
5063     case Intrinsic::amdgcn_buffer_atomic_umin:
5064       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
5065       break;
5066     case Intrinsic::amdgcn_buffer_atomic_smax:
5067       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
5068       break;
5069     case Intrinsic::amdgcn_buffer_atomic_umax:
5070       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
5071       break;
5072     case Intrinsic::amdgcn_buffer_atomic_and:
5073       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
5074       break;
5075     case Intrinsic::amdgcn_buffer_atomic_or:
5076       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
5077       break;
5078     case Intrinsic::amdgcn_buffer_atomic_xor:
5079       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
5080       break;
5081     default:
5082       llvm_unreachable("unhandled atomic opcode");
5083     }
5084 
5085     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
5086                                    M->getMemOperand());
5087   }
5088 
5089   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
5090     SDValue Ops[] = {
5091       Op.getOperand(0), // Chain
5092       Op.getOperand(2), // src
5093       Op.getOperand(3), // cmp
5094       Op.getOperand(4), // rsrc
5095       Op.getOperand(5), // vindex
5096       Op.getOperand(6), // offset
5097       Op.getOperand(7)  // slc
5098     };
5099     EVT VT = Op.getValueType();
5100     auto *M = cast<MemSDNode>(Op);
5101 
5102     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
5103                                    Op->getVTList(), Ops, VT, M->getMemOperand());
5104   }
5105 
5106   default:
5107     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5108             AMDGPU::getImageDimIntrinsicInfo(IntrID))
5109       return lowerImage(Op, ImageDimIntr, DAG);
5110 
5111     return SDValue();
5112   }
5113 }
5114 
5115 SDValue SITargetLowering::handleD16VData(SDValue VData,
5116                                          SelectionDAG &DAG) const {
5117   EVT StoreVT = VData.getValueType();
5118 
5119   // No change for f16 and legal vector D16 types.
5120   if (!StoreVT.isVector())
5121     return VData;
5122 
5123   SDLoc DL(VData);
5124   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
5125 
5126   if (Subtarget->hasUnpackedD16VMem()) {
5127     // We need to unpack the packed data to store.
5128     EVT IntStoreVT = StoreVT.changeTypeToInteger();
5129     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
5130 
5131     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
5132                                         StoreVT.getVectorNumElements());
5133     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
5134     return DAG.UnrollVectorOp(ZExt.getNode());
5135   }
5136 
5137   assert(isTypeLegal(StoreVT));
5138   return VData;
5139 }
5140 
5141 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
5142                                               SelectionDAG &DAG) const {
5143   SDLoc DL(Op);
5144   SDValue Chain = Op.getOperand(0);
5145   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5146   MachineFunction &MF = DAG.getMachineFunction();
5147 
5148   switch (IntrinsicID) {
5149   case Intrinsic::amdgcn_exp: {
5150     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
5151     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
5152     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
5153     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
5154 
5155     const SDValue Ops[] = {
5156       Chain,
5157       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
5158       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
5159       Op.getOperand(4), // src0
5160       Op.getOperand(5), // src1
5161       Op.getOperand(6), // src2
5162       Op.getOperand(7), // src3
5163       DAG.getTargetConstant(0, DL, MVT::i1), // compr
5164       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
5165     };
5166 
5167     unsigned Opc = Done->isNullValue() ?
5168       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
5169     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
5170   }
5171   case Intrinsic::amdgcn_exp_compr: {
5172     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
5173     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
5174     SDValue Src0 = Op.getOperand(4);
5175     SDValue Src1 = Op.getOperand(5);
5176     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
5177     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
5178 
5179     SDValue Undef = DAG.getUNDEF(MVT::f32);
5180     const SDValue Ops[] = {
5181       Chain,
5182       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
5183       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
5184       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
5185       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
5186       Undef, // src2
5187       Undef, // src3
5188       DAG.getTargetConstant(1, DL, MVT::i1), // compr
5189       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
5190     };
5191 
5192     unsigned Opc = Done->isNullValue() ?
5193       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
5194     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
5195   }
5196   case Intrinsic::amdgcn_s_sendmsg:
5197   case Intrinsic::amdgcn_s_sendmsghalt: {
5198     unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
5199       AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
5200     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
5201     SDValue Glue = Chain.getValue(1);
5202     return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
5203                        Op.getOperand(2), Glue);
5204   }
5205   case Intrinsic::amdgcn_init_exec: {
5206     return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
5207                        Op.getOperand(2));
5208   }
5209   case Intrinsic::amdgcn_init_exec_from_input: {
5210     return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
5211                        Op.getOperand(2), Op.getOperand(3));
5212   }
5213   case AMDGPUIntrinsic::AMDGPU_kill: {
5214     SDValue Src = Op.getOperand(2);
5215     if (const ConstantFPSDNode *K = dyn_cast<ConstantFPSDNode>(Src)) {
5216       if (!K->isNegative())
5217         return Chain;
5218 
5219       SDValue NegOne = DAG.getTargetConstant(FloatToBits(-1.0f), DL, MVT::i32);
5220       return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, NegOne);
5221     }
5222 
5223     SDValue Cast = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Src);
5224     return DAG.getNode(AMDGPUISD::KILL, DL, MVT::Other, Chain, Cast);
5225   }
5226   case Intrinsic::amdgcn_s_barrier: {
5227     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
5228       const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
5229       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
5230       if (WGSize <= ST.getWavefrontSize())
5231         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
5232                                           Op.getOperand(0)), 0);
5233     }
5234     return SDValue();
5235   };
5236   case AMDGPUIntrinsic::SI_tbuffer_store: {
5237 
5238     // Extract vindex and voffset from vaddr as appropriate
5239     const ConstantSDNode *OffEn = cast<ConstantSDNode>(Op.getOperand(10));
5240     const ConstantSDNode *IdxEn = cast<ConstantSDNode>(Op.getOperand(11));
5241     SDValue VAddr = Op.getOperand(5);
5242 
5243     SDValue Zero = DAG.getTargetConstant(0, DL, MVT::i32);
5244 
5245     assert(!(OffEn->isOne() && IdxEn->isOne()) &&
5246            "Legacy intrinsic doesn't support both offset and index - use new version");
5247 
5248     SDValue VIndex = IdxEn->isOne() ? VAddr : Zero;
5249     SDValue VOffset = OffEn->isOne() ? VAddr : Zero;
5250 
5251     // Deal with the vec-3 case
5252     const ConstantSDNode *NumChannels = cast<ConstantSDNode>(Op.getOperand(4));
5253     auto Opcode = NumChannels->getZExtValue() == 3 ?
5254       AMDGPUISD::TBUFFER_STORE_FORMAT_X3 : AMDGPUISD::TBUFFER_STORE_FORMAT;
5255 
5256     SDValue Ops[] = {
5257      Chain,
5258      Op.getOperand(3),  // vdata
5259      Op.getOperand(2),  // rsrc
5260      VIndex,
5261      VOffset,
5262      Op.getOperand(6),  // soffset
5263      Op.getOperand(7),  // inst_offset
5264      Op.getOperand(8),  // dfmt
5265      Op.getOperand(9),  // nfmt
5266      Op.getOperand(12), // glc
5267      Op.getOperand(13), // slc
5268     };
5269 
5270     assert((cast<ConstantSDNode>(Op.getOperand(14)))->getZExtValue() == 0 &&
5271            "Value of tfe other than zero is unsupported");
5272 
5273     EVT VT = Op.getOperand(3).getValueType();
5274     MachineMemOperand *MMO = MF.getMachineMemOperand(
5275       MachinePointerInfo(),
5276       MachineMemOperand::MOStore,
5277       VT.getStoreSize(), 4);
5278     return DAG.getMemIntrinsicNode(Opcode, DL,
5279                                    Op->getVTList(), Ops, VT, MMO);
5280   }
5281 
5282   case Intrinsic::amdgcn_tbuffer_store: {
5283     SDValue VData = Op.getOperand(2);
5284     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5285     if (IsD16)
5286       VData = handleD16VData(VData, DAG);
5287     SDValue Ops[] = {
5288       Chain,
5289       VData,             // vdata
5290       Op.getOperand(3),  // rsrc
5291       Op.getOperand(4),  // vindex
5292       Op.getOperand(5),  // voffset
5293       Op.getOperand(6),  // soffset
5294       Op.getOperand(7),  // offset
5295       Op.getOperand(8),  // dfmt
5296       Op.getOperand(9),  // nfmt
5297       Op.getOperand(10), // glc
5298       Op.getOperand(11)  // slc
5299     };
5300     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
5301                            AMDGPUISD::TBUFFER_STORE_FORMAT;
5302     MemSDNode *M = cast<MemSDNode>(Op);
5303     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5304                                    M->getMemoryVT(), M->getMemOperand());
5305   }
5306 
5307   case Intrinsic::amdgcn_buffer_store:
5308   case Intrinsic::amdgcn_buffer_store_format: {
5309     SDValue VData = Op.getOperand(2);
5310     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
5311     if (IsD16)
5312       VData = handleD16VData(VData, DAG);
5313     SDValue Ops[] = {
5314       Chain,
5315       VData,            // vdata
5316       Op.getOperand(3), // rsrc
5317       Op.getOperand(4), // vindex
5318       Op.getOperand(5), // offset
5319       Op.getOperand(6), // glc
5320       Op.getOperand(7)  // slc
5321     };
5322     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
5323                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
5324     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
5325     MemSDNode *M = cast<MemSDNode>(Op);
5326     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
5327                                    M->getMemoryVT(), M->getMemOperand());
5328   }
5329   default: {
5330     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5331             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5332       return lowerImage(Op, ImageDimIntr, DAG);
5333 
5334     return Op;
5335   }
5336   }
5337 }
5338 
5339 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
5340                                  ISD::LoadExtType ExtType, SDValue Op,
5341                                  const SDLoc &SL, EVT VT) {
5342   if (VT.bitsLT(Op.getValueType()))
5343     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
5344 
5345   switch (ExtType) {
5346   case ISD::SEXTLOAD:
5347     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
5348   case ISD::ZEXTLOAD:
5349     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
5350   case ISD::EXTLOAD:
5351     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
5352   case ISD::NON_EXTLOAD:
5353     return Op;
5354   }
5355 
5356   llvm_unreachable("invalid ext type");
5357 }
5358 
5359 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
5360   SelectionDAG &DAG = DCI.DAG;
5361   if (Ld->getAlignment() < 4 || Ld->isDivergent())
5362     return SDValue();
5363 
5364   // FIXME: Constant loads should all be marked invariant.
5365   unsigned AS = Ld->getAddressSpace();
5366   if (AS != AMDGPUASI.CONSTANT_ADDRESS &&
5367       AS != AMDGPUASI.CONSTANT_ADDRESS_32BIT &&
5368       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
5369     return SDValue();
5370 
5371   // Don't do this early, since it may interfere with adjacent load merging for
5372   // illegal types. We can avoid losing alignment information for exotic types
5373   // pre-legalize.
5374   EVT MemVT = Ld->getMemoryVT();
5375   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
5376       MemVT.getSizeInBits() >= 32)
5377     return SDValue();
5378 
5379   SDLoc SL(Ld);
5380 
5381   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
5382          "unexpected vector extload");
5383 
5384   // TODO: Drop only high part of range.
5385   SDValue Ptr = Ld->getBasePtr();
5386   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
5387                                 MVT::i32, SL, Ld->getChain(), Ptr,
5388                                 Ld->getOffset(),
5389                                 Ld->getPointerInfo(), MVT::i32,
5390                                 Ld->getAlignment(),
5391                                 Ld->getMemOperand()->getFlags(),
5392                                 Ld->getAAInfo(),
5393                                 nullptr); // Drop ranges
5394 
5395   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
5396   if (MemVT.isFloatingPoint()) {
5397     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
5398            "unexpected fp extload");
5399     TruncVT = MemVT.changeTypeToInteger();
5400   }
5401 
5402   SDValue Cvt = NewLoad;
5403   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
5404     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
5405                       DAG.getValueType(TruncVT));
5406   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
5407              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
5408     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
5409   } else {
5410     assert(Ld->getExtensionType() == ISD::EXTLOAD);
5411   }
5412 
5413   EVT VT = Ld->getValueType(0);
5414   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
5415 
5416   DCI.AddToWorklist(Cvt.getNode());
5417 
5418   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
5419   // the appropriate extension from the 32-bit load.
5420   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
5421   DCI.AddToWorklist(Cvt.getNode());
5422 
5423   // Handle conversion back to floating point if necessary.
5424   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
5425 
5426   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
5427 }
5428 
5429 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
5430   SDLoc DL(Op);
5431   LoadSDNode *Load = cast<LoadSDNode>(Op);
5432   ISD::LoadExtType ExtType = Load->getExtensionType();
5433   EVT MemVT = Load->getMemoryVT();
5434 
5435   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
5436     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
5437       return SDValue();
5438 
5439     // FIXME: Copied from PPC
5440     // First, load into 32 bits, then truncate to 1 bit.
5441 
5442     SDValue Chain = Load->getChain();
5443     SDValue BasePtr = Load->getBasePtr();
5444     MachineMemOperand *MMO = Load->getMemOperand();
5445 
5446     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
5447 
5448     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
5449                                    BasePtr, RealMemVT, MMO);
5450 
5451     SDValue Ops[] = {
5452       DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
5453       NewLD.getValue(1)
5454     };
5455 
5456     return DAG.getMergeValues(Ops, DL);
5457   }
5458 
5459   if (!MemVT.isVector())
5460     return SDValue();
5461 
5462   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
5463          "Custom lowering for non-i32 vectors hasn't been implemented.");
5464 
5465   unsigned Alignment = Load->getAlignment();
5466   unsigned AS = Load->getAddressSpace();
5467   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
5468                           AS, Alignment)) {
5469     SDValue Ops[2];
5470     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
5471     return DAG.getMergeValues(Ops, DL);
5472   }
5473 
5474   MachineFunction &MF = DAG.getMachineFunction();
5475   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5476   // If there is a possibilty that flat instruction access scratch memory
5477   // then we need to use the same legalization rules we use for private.
5478   if (AS == AMDGPUASI.FLAT_ADDRESS)
5479     AS = MFI->hasFlatScratchInit() ?
5480          AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5481 
5482   unsigned NumElements = MemVT.getVectorNumElements();
5483 
5484   if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5485       AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT) {
5486     if (!Op->isDivergent() && Alignment >= 4)
5487       return SDValue();
5488     // Non-uniform loads will be selected to MUBUF instructions, so they
5489     // have the same legalization requirements as global and private
5490     // loads.
5491     //
5492   }
5493 
5494   if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5495       AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT ||
5496       AS == AMDGPUASI.GLOBAL_ADDRESS) {
5497     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
5498         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
5499         Alignment >= 4)
5500       return SDValue();
5501     // Non-uniform loads will be selected to MUBUF instructions, so they
5502     // have the same legalization requirements as global and private
5503     // loads.
5504     //
5505   }
5506   if (AS == AMDGPUASI.CONSTANT_ADDRESS ||
5507       AS == AMDGPUASI.CONSTANT_ADDRESS_32BIT ||
5508       AS == AMDGPUASI.GLOBAL_ADDRESS ||
5509       AS == AMDGPUASI.FLAT_ADDRESS) {
5510     if (NumElements > 4)
5511       return SplitVectorLoad(Op, DAG);
5512     // v4 loads are supported for private and global memory.
5513     return SDValue();
5514   }
5515   if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5516     // Depending on the setting of the private_element_size field in the
5517     // resource descriptor, we can only make private accesses up to a certain
5518     // size.
5519     switch (Subtarget->getMaxPrivateElementSize()) {
5520     case 4:
5521       return scalarizeVectorLoad(Load, DAG);
5522     case 8:
5523       if (NumElements > 2)
5524         return SplitVectorLoad(Op, DAG);
5525       return SDValue();
5526     case 16:
5527       // Same as global/flat
5528       if (NumElements > 4)
5529         return SplitVectorLoad(Op, DAG);
5530       return SDValue();
5531     default:
5532       llvm_unreachable("unsupported private_element_size");
5533     }
5534   } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
5535     // Use ds_read_b128 if possible.
5536     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
5537         MemVT.getStoreSize() == 16)
5538       return SDValue();
5539 
5540     if (NumElements > 2)
5541       return SplitVectorLoad(Op, DAG);
5542   }
5543   return SDValue();
5544 }
5545 
5546 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
5547   EVT VT = Op.getValueType();
5548   assert(VT.getSizeInBits() == 64);
5549 
5550   SDLoc DL(Op);
5551   SDValue Cond = Op.getOperand(0);
5552 
5553   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
5554   SDValue One = DAG.getConstant(1, DL, MVT::i32);
5555 
5556   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
5557   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
5558 
5559   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
5560   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
5561 
5562   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
5563 
5564   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
5565   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
5566 
5567   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
5568 
5569   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
5570   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
5571 }
5572 
5573 // Catch division cases where we can use shortcuts with rcp and rsq
5574 // instructions.
5575 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
5576                                               SelectionDAG &DAG) const {
5577   SDLoc SL(Op);
5578   SDValue LHS = Op.getOperand(0);
5579   SDValue RHS = Op.getOperand(1);
5580   EVT VT = Op.getValueType();
5581   const SDNodeFlags Flags = Op->getFlags();
5582   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
5583 
5584   if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
5585     return SDValue();
5586 
5587   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
5588     if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
5589       if (CLHS->isExactlyValue(1.0)) {
5590         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
5591         // the CI documentation has a worst case error of 1 ulp.
5592         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
5593         // use it as long as we aren't trying to use denormals.
5594         //
5595         // v_rcp_f16 and v_rsq_f16 DO support denormals.
5596 
5597         // 1.0 / sqrt(x) -> rsq(x)
5598 
5599         // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
5600         // error seems really high at 2^29 ULP.
5601         if (RHS.getOpcode() == ISD::FSQRT)
5602           return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
5603 
5604         // 1.0 / x -> rcp(x)
5605         return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5606       }
5607 
5608       // Same as for 1.0, but expand the sign out of the constant.
5609       if (CLHS->isExactlyValue(-1.0)) {
5610         // -1.0 / x -> rcp (fneg x)
5611         SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
5612         return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
5613       }
5614     }
5615   }
5616 
5617   if (Unsafe) {
5618     // Turn into multiply by the reciprocal.
5619     // x / y -> x * (1.0 / y)
5620     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
5621     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
5622   }
5623 
5624   return SDValue();
5625 }
5626 
5627 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5628                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
5629   if (GlueChain->getNumValues() <= 1) {
5630     return DAG.getNode(Opcode, SL, VT, A, B);
5631   }
5632 
5633   assert(GlueChain->getNumValues() == 3);
5634 
5635   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5636   switch (Opcode) {
5637   default: llvm_unreachable("no chain equivalent for opcode");
5638   case ISD::FMUL:
5639     Opcode = AMDGPUISD::FMUL_W_CHAIN;
5640     break;
5641   }
5642 
5643   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
5644                      GlueChain.getValue(2));
5645 }
5646 
5647 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
5648                            EVT VT, SDValue A, SDValue B, SDValue C,
5649                            SDValue GlueChain) {
5650   if (GlueChain->getNumValues() <= 1) {
5651     return DAG.getNode(Opcode, SL, VT, A, B, C);
5652   }
5653 
5654   assert(GlueChain->getNumValues() == 3);
5655 
5656   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
5657   switch (Opcode) {
5658   default: llvm_unreachable("no chain equivalent for opcode");
5659   case ISD::FMA:
5660     Opcode = AMDGPUISD::FMA_W_CHAIN;
5661     break;
5662   }
5663 
5664   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
5665                      GlueChain.getValue(2));
5666 }
5667 
5668 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
5669   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5670     return FastLowered;
5671 
5672   SDLoc SL(Op);
5673   SDValue Src0 = Op.getOperand(0);
5674   SDValue Src1 = Op.getOperand(1);
5675 
5676   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
5677   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
5678 
5679   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
5680   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
5681 
5682   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
5683   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
5684 
5685   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
5686 }
5687 
5688 // Faster 2.5 ULP division that does not support denormals.
5689 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
5690   SDLoc SL(Op);
5691   SDValue LHS = Op.getOperand(1);
5692   SDValue RHS = Op.getOperand(2);
5693 
5694   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
5695 
5696   const APFloat K0Val(BitsToFloat(0x6f800000));
5697   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
5698 
5699   const APFloat K1Val(BitsToFloat(0x2f800000));
5700   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
5701 
5702   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5703 
5704   EVT SetCCVT =
5705     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
5706 
5707   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
5708 
5709   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
5710 
5711   // TODO: Should this propagate fast-math-flags?
5712   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
5713 
5714   // rcp does not support denormals.
5715   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
5716 
5717   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
5718 
5719   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
5720 }
5721 
5722 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
5723   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
5724     return FastLowered;
5725 
5726   SDLoc SL(Op);
5727   SDValue LHS = Op.getOperand(0);
5728   SDValue RHS = Op.getOperand(1);
5729 
5730   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
5731 
5732   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
5733 
5734   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5735                                           RHS, RHS, LHS);
5736   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
5737                                         LHS, RHS, LHS);
5738 
5739   // Denominator is scaled to not be denormal, so using rcp is ok.
5740   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
5741                                   DenominatorScaled);
5742   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
5743                                      DenominatorScaled);
5744 
5745   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
5746                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
5747                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
5748 
5749   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
5750 
5751   if (!Subtarget->hasFP32Denormals()) {
5752     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
5753     const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
5754                                                       SL, MVT::i32);
5755     SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
5756                                        DAG.getEntryNode(),
5757                                        EnableDenormValue, BitField);
5758     SDValue Ops[3] = {
5759       NegDivScale0,
5760       EnableDenorm.getValue(0),
5761       EnableDenorm.getValue(1)
5762     };
5763 
5764     NegDivScale0 = DAG.getMergeValues(Ops, SL);
5765   }
5766 
5767   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
5768                              ApproxRcp, One, NegDivScale0);
5769 
5770   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
5771                              ApproxRcp, Fma0);
5772 
5773   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
5774                            Fma1, Fma1);
5775 
5776   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
5777                              NumeratorScaled, Mul);
5778 
5779   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
5780 
5781   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
5782                              NumeratorScaled, Fma3);
5783 
5784   if (!Subtarget->hasFP32Denormals()) {
5785     const SDValue DisableDenormValue =
5786         DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
5787     SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
5788                                         Fma4.getValue(1),
5789                                         DisableDenormValue,
5790                                         BitField,
5791                                         Fma4.getValue(2));
5792 
5793     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
5794                                       DisableDenorm, DAG.getRoot());
5795     DAG.setRoot(OutputChain);
5796   }
5797 
5798   SDValue Scale = NumeratorScaled.getValue(1);
5799   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
5800                              Fma4, Fma1, Fma3, Scale);
5801 
5802   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
5803 }
5804 
5805 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
5806   if (DAG.getTarget().Options.UnsafeFPMath)
5807     return lowerFastUnsafeFDIV(Op, DAG);
5808 
5809   SDLoc SL(Op);
5810   SDValue X = Op.getOperand(0);
5811   SDValue Y = Op.getOperand(1);
5812 
5813   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
5814 
5815   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
5816 
5817   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
5818 
5819   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
5820 
5821   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
5822 
5823   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
5824 
5825   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
5826 
5827   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
5828 
5829   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
5830 
5831   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
5832   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
5833 
5834   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
5835                              NegDivScale0, Mul, DivScale1);
5836 
5837   SDValue Scale;
5838 
5839   if (Subtarget->getGeneration() == SISubtarget::SOUTHERN_ISLANDS) {
5840     // Workaround a hardware bug on SI where the condition output from div_scale
5841     // is not usable.
5842 
5843     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
5844 
5845     // Figure out if the scale to use for div_fmas.
5846     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
5847     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
5848     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
5849     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
5850 
5851     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
5852     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
5853 
5854     SDValue Scale0Hi
5855       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
5856     SDValue Scale1Hi
5857       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
5858 
5859     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
5860     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
5861     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
5862   } else {
5863     Scale = DivScale1.getValue(1);
5864   }
5865 
5866   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
5867                              Fma4, Fma3, Mul, Scale);
5868 
5869   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
5870 }
5871 
5872 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
5873   EVT VT = Op.getValueType();
5874 
5875   if (VT == MVT::f32)
5876     return LowerFDIV32(Op, DAG);
5877 
5878   if (VT == MVT::f64)
5879     return LowerFDIV64(Op, DAG);
5880 
5881   if (VT == MVT::f16)
5882     return LowerFDIV16(Op, DAG);
5883 
5884   llvm_unreachable("Unexpected type for fdiv");
5885 }
5886 
5887 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
5888   SDLoc DL(Op);
5889   StoreSDNode *Store = cast<StoreSDNode>(Op);
5890   EVT VT = Store->getMemoryVT();
5891 
5892   if (VT == MVT::i1) {
5893     return DAG.getTruncStore(Store->getChain(), DL,
5894        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
5895        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
5896   }
5897 
5898   assert(VT.isVector() &&
5899          Store->getValue().getValueType().getScalarType() == MVT::i32);
5900 
5901   unsigned AS = Store->getAddressSpace();
5902   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
5903                           AS, Store->getAlignment())) {
5904     return expandUnalignedStore(Store, DAG);
5905   }
5906 
5907   MachineFunction &MF = DAG.getMachineFunction();
5908   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
5909   // If there is a possibilty that flat instruction access scratch memory
5910   // then we need to use the same legalization rules we use for private.
5911   if (AS == AMDGPUASI.FLAT_ADDRESS)
5912     AS = MFI->hasFlatScratchInit() ?
5913          AMDGPUASI.PRIVATE_ADDRESS : AMDGPUASI.GLOBAL_ADDRESS;
5914 
5915   unsigned NumElements = VT.getVectorNumElements();
5916   if (AS == AMDGPUASI.GLOBAL_ADDRESS ||
5917       AS == AMDGPUASI.FLAT_ADDRESS) {
5918     if (NumElements > 4)
5919       return SplitVectorStore(Op, DAG);
5920     return SDValue();
5921   } else if (AS == AMDGPUASI.PRIVATE_ADDRESS) {
5922     switch (Subtarget->getMaxPrivateElementSize()) {
5923     case 4:
5924       return scalarizeVectorStore(Store, DAG);
5925     case 8:
5926       if (NumElements > 2)
5927         return SplitVectorStore(Op, DAG);
5928       return SDValue();
5929     case 16:
5930       if (NumElements > 4)
5931         return SplitVectorStore(Op, DAG);
5932       return SDValue();
5933     default:
5934       llvm_unreachable("unsupported private_element_size");
5935     }
5936   } else if (AS == AMDGPUASI.LOCAL_ADDRESS) {
5937     // Use ds_write_b128 if possible.
5938     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
5939         VT.getStoreSize() == 16)
5940       return SDValue();
5941 
5942     if (NumElements > 2)
5943       return SplitVectorStore(Op, DAG);
5944     return SDValue();
5945   } else {
5946     llvm_unreachable("unhandled address space");
5947   }
5948 }
5949 
5950 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
5951   SDLoc DL(Op);
5952   EVT VT = Op.getValueType();
5953   SDValue Arg = Op.getOperand(0);
5954   // TODO: Should this propagate fast-math-flags?
5955   SDValue FractPart = DAG.getNode(AMDGPUISD::FRACT, DL, VT,
5956                                   DAG.getNode(ISD::FMUL, DL, VT, Arg,
5957                                               DAG.getConstantFP(0.5/M_PI, DL,
5958                                                                 VT)));
5959 
5960   switch (Op.getOpcode()) {
5961   case ISD::FCOS:
5962     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, FractPart);
5963   case ISD::FSIN:
5964     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, FractPart);
5965   default:
5966     llvm_unreachable("Wrong trig opcode");
5967   }
5968 }
5969 
5970 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
5971   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
5972   assert(AtomicNode->isCompareAndSwap());
5973   unsigned AS = AtomicNode->getAddressSpace();
5974 
5975   // No custom lowering required for local address space
5976   if (!isFlatGlobalAddrSpace(AS, AMDGPUASI))
5977     return Op;
5978 
5979   // Non-local address space requires custom lowering for atomic compare
5980   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
5981   SDLoc DL(Op);
5982   SDValue ChainIn = Op.getOperand(0);
5983   SDValue Addr = Op.getOperand(1);
5984   SDValue Old = Op.getOperand(2);
5985   SDValue New = Op.getOperand(3);
5986   EVT VT = Op.getValueType();
5987   MVT SimpleVT = VT.getSimpleVT();
5988   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
5989 
5990   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
5991   SDValue Ops[] = { ChainIn, Addr, NewOld };
5992 
5993   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
5994                                  Ops, VT, AtomicNode->getMemOperand());
5995 }
5996 
5997 //===----------------------------------------------------------------------===//
5998 // Custom DAG optimizations
5999 //===----------------------------------------------------------------------===//
6000 
6001 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
6002                                                      DAGCombinerInfo &DCI) const {
6003   EVT VT = N->getValueType(0);
6004   EVT ScalarVT = VT.getScalarType();
6005   if (ScalarVT != MVT::f32)
6006     return SDValue();
6007 
6008   SelectionDAG &DAG = DCI.DAG;
6009   SDLoc DL(N);
6010 
6011   SDValue Src = N->getOperand(0);
6012   EVT SrcVT = Src.getValueType();
6013 
6014   // TODO: We could try to match extracting the higher bytes, which would be
6015   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
6016   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
6017   // about in practice.
6018   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
6019     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
6020       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
6021       DCI.AddToWorklist(Cvt.getNode());
6022       return Cvt;
6023     }
6024   }
6025 
6026   return SDValue();
6027 }
6028 
6029 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
6030 
6031 // This is a variant of
6032 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
6033 //
6034 // The normal DAG combiner will do this, but only if the add has one use since
6035 // that would increase the number of instructions.
6036 //
6037 // This prevents us from seeing a constant offset that can be folded into a
6038 // memory instruction's addressing mode. If we know the resulting add offset of
6039 // a pointer can be folded into an addressing offset, we can replace the pointer
6040 // operand with the add of new constant offset. This eliminates one of the uses,
6041 // and may allow the remaining use to also be simplified.
6042 //
6043 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
6044                                                unsigned AddrSpace,
6045                                                EVT MemVT,
6046                                                DAGCombinerInfo &DCI) const {
6047   SDValue N0 = N->getOperand(0);
6048   SDValue N1 = N->getOperand(1);
6049 
6050   // We only do this to handle cases where it's profitable when there are
6051   // multiple uses of the add, so defer to the standard combine.
6052   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
6053       N0->hasOneUse())
6054     return SDValue();
6055 
6056   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
6057   if (!CN1)
6058     return SDValue();
6059 
6060   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6061   if (!CAdd)
6062     return SDValue();
6063 
6064   // If the resulting offset is too large, we can't fold it into the addressing
6065   // mode offset.
6066   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
6067   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
6068 
6069   AddrMode AM;
6070   AM.HasBaseReg = true;
6071   AM.BaseOffs = Offset.getSExtValue();
6072   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
6073     return SDValue();
6074 
6075   SelectionDAG &DAG = DCI.DAG;
6076   SDLoc SL(N);
6077   EVT VT = N->getValueType(0);
6078 
6079   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
6080   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
6081 
6082   SDNodeFlags Flags;
6083   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
6084                           (N0.getOpcode() == ISD::OR ||
6085                            N0->getFlags().hasNoUnsignedWrap()));
6086 
6087   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
6088 }
6089 
6090 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
6091                                                   DAGCombinerInfo &DCI) const {
6092   SDValue Ptr = N->getBasePtr();
6093   SelectionDAG &DAG = DCI.DAG;
6094   SDLoc SL(N);
6095 
6096   // TODO: We could also do this for multiplies.
6097   if (Ptr.getOpcode() == ISD::SHL) {
6098     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
6099                                           N->getMemoryVT(), DCI);
6100     if (NewPtr) {
6101       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
6102 
6103       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
6104       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
6105     }
6106   }
6107 
6108   return SDValue();
6109 }
6110 
6111 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
6112   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
6113          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
6114          (Opc == ISD::XOR && Val == 0);
6115 }
6116 
6117 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
6118 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
6119 // integer combine opportunities since most 64-bit operations are decomposed
6120 // this way.  TODO: We won't want this for SALU especially if it is an inline
6121 // immediate.
6122 SDValue SITargetLowering::splitBinaryBitConstantOp(
6123   DAGCombinerInfo &DCI,
6124   const SDLoc &SL,
6125   unsigned Opc, SDValue LHS,
6126   const ConstantSDNode *CRHS) const {
6127   uint64_t Val = CRHS->getZExtValue();
6128   uint32_t ValLo = Lo_32(Val);
6129   uint32_t ValHi = Hi_32(Val);
6130   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6131 
6132     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
6133          bitOpWithConstantIsReducible(Opc, ValHi)) ||
6134         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
6135     // If we need to materialize a 64-bit immediate, it will be split up later
6136     // anyway. Avoid creating the harder to understand 64-bit immediate
6137     // materialization.
6138     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
6139   }
6140 
6141   return SDValue();
6142 }
6143 
6144 // Returns true if argument is a boolean value which is not serialized into
6145 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
6146 static bool isBoolSGPR(SDValue V) {
6147   if (V.getValueType() != MVT::i1)
6148     return false;
6149   switch (V.getOpcode()) {
6150   default: break;
6151   case ISD::SETCC:
6152   case ISD::AND:
6153   case ISD::OR:
6154   case ISD::XOR:
6155   case AMDGPUISD::FP_CLASS:
6156     return true;
6157   }
6158   return false;
6159 }
6160 
6161 // If a constant has all zeroes or all ones within each byte return it.
6162 // Otherwise return 0.
6163 static uint32_t getConstantPermuteMask(uint32_t C) {
6164   // 0xff for any zero byte in the mask
6165   uint32_t ZeroByteMask = 0;
6166   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
6167   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
6168   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
6169   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
6170   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
6171   if ((NonZeroByteMask & C) != NonZeroByteMask)
6172     return 0; // Partial bytes selected.
6173   return C;
6174 }
6175 
6176 // Check if a node selects whole bytes from its operand 0 starting at a byte
6177 // boundary while masking the rest. Returns select mask as in the v_perm_b32
6178 // or -1 if not succeeded.
6179 // Note byte select encoding:
6180 // value 0-3 selects corresponding source byte;
6181 // value 0xc selects zero;
6182 // value 0xff selects 0xff.
6183 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
6184   assert(V.getValueSizeInBits() == 32);
6185 
6186   if (V.getNumOperands() != 2)
6187     return ~0;
6188 
6189   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
6190   if (!N1)
6191     return ~0;
6192 
6193   uint32_t C = N1->getZExtValue();
6194 
6195   switch (V.getOpcode()) {
6196   default:
6197     break;
6198   case ISD::AND:
6199     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
6200       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
6201     }
6202     break;
6203 
6204   case ISD::OR:
6205     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
6206       return (0x03020100 & ~ConstMask) | ConstMask;
6207     }
6208     break;
6209 
6210   case ISD::SHL:
6211     if (C % 8)
6212       return ~0;
6213 
6214     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
6215 
6216   case ISD::SRL:
6217     if (C % 8)
6218       return ~0;
6219 
6220     return uint32_t(0x0c0c0c0c03020100ull >> C);
6221   }
6222 
6223   return ~0;
6224 }
6225 
6226 SDValue SITargetLowering::performAndCombine(SDNode *N,
6227                                             DAGCombinerInfo &DCI) const {
6228   if (DCI.isBeforeLegalize())
6229     return SDValue();
6230 
6231   SelectionDAG &DAG = DCI.DAG;
6232   EVT VT = N->getValueType(0);
6233   SDValue LHS = N->getOperand(0);
6234   SDValue RHS = N->getOperand(1);
6235 
6236 
6237   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
6238   if (VT == MVT::i64 && CRHS) {
6239     if (SDValue Split
6240         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
6241       return Split;
6242   }
6243 
6244   if (CRHS && VT == MVT::i32) {
6245     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
6246     // nb = number of trailing zeroes in mask
6247     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
6248     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
6249     uint64_t Mask = CRHS->getZExtValue();
6250     unsigned Bits = countPopulation(Mask);
6251     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
6252         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
6253       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
6254         unsigned Shift = CShift->getZExtValue();
6255         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
6256         unsigned Offset = NB + Shift;
6257         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
6258           SDLoc SL(N);
6259           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
6260                                     LHS->getOperand(0),
6261                                     DAG.getConstant(Offset, SL, MVT::i32),
6262                                     DAG.getConstant(Bits, SL, MVT::i32));
6263           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
6264           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
6265                                     DAG.getValueType(NarrowVT));
6266           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
6267                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
6268           return Shl;
6269         }
6270       }
6271     }
6272 
6273     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
6274     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
6275         isa<ConstantSDNode>(LHS.getOperand(2))) {
6276       uint32_t Sel = getConstantPermuteMask(Mask);
6277       if (!Sel)
6278         return SDValue();
6279 
6280       // Select 0xc for all zero bytes
6281       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
6282       SDLoc DL(N);
6283       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
6284                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
6285     }
6286   }
6287 
6288   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
6289   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
6290   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
6291     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
6292     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
6293 
6294     SDValue X = LHS.getOperand(0);
6295     SDValue Y = RHS.getOperand(0);
6296     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
6297       return SDValue();
6298 
6299     if (LCC == ISD::SETO) {
6300       if (X != LHS.getOperand(1))
6301         return SDValue();
6302 
6303       if (RCC == ISD::SETUNE) {
6304         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
6305         if (!C1 || !C1->isInfinity() || C1->isNegative())
6306           return SDValue();
6307 
6308         const uint32_t Mask = SIInstrFlags::N_NORMAL |
6309                               SIInstrFlags::N_SUBNORMAL |
6310                               SIInstrFlags::N_ZERO |
6311                               SIInstrFlags::P_ZERO |
6312                               SIInstrFlags::P_SUBNORMAL |
6313                               SIInstrFlags::P_NORMAL;
6314 
6315         static_assert(((~(SIInstrFlags::S_NAN |
6316                           SIInstrFlags::Q_NAN |
6317                           SIInstrFlags::N_INFINITY |
6318                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
6319                       "mask not equal");
6320 
6321         SDLoc DL(N);
6322         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
6323                            X, DAG.getConstant(Mask, DL, MVT::i32));
6324       }
6325     }
6326   }
6327 
6328   if (VT == MVT::i32 &&
6329       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
6330     // and x, (sext cc from i1) => select cc, x, 0
6331     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
6332       std::swap(LHS, RHS);
6333     if (isBoolSGPR(RHS.getOperand(0)))
6334       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
6335                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
6336   }
6337 
6338   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
6339   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6340   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
6341       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
6342     uint32_t LHSMask = getPermuteMask(DAG, LHS);
6343     uint32_t RHSMask = getPermuteMask(DAG, RHS);
6344     if (LHSMask != ~0u && RHSMask != ~0u) {
6345       // Canonicalize the expression in an attempt to have fewer unique masks
6346       // and therefore fewer registers used to hold the masks.
6347       if (LHSMask > RHSMask) {
6348         std::swap(LHSMask, RHSMask);
6349         std::swap(LHS, RHS);
6350       }
6351 
6352       // Select 0xc for each lane used from source operand. Zero has 0xc mask
6353       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
6354       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6355       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6356 
6357       // Check of we need to combine values from two sources within a byte.
6358       if (!(LHSUsedLanes & RHSUsedLanes) &&
6359           // If we select high and lower word keep it for SDWA.
6360           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
6361           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
6362         // Each byte in each mask is either selector mask 0-3, or has higher
6363         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
6364         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
6365         // mask which is not 0xff wins. By anding both masks we have a correct
6366         // result except that 0x0c shall be corrected to give 0x0c only.
6367         uint32_t Mask = LHSMask & RHSMask;
6368         for (unsigned I = 0; I < 32; I += 8) {
6369           uint32_t ByteSel = 0xff << I;
6370           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
6371             Mask &= (0x0c << I) & 0xffffffff;
6372         }
6373 
6374         // Add 4 to each active LHS lane. It will not affect any existing 0xff
6375         // or 0x0c.
6376         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
6377         SDLoc DL(N);
6378 
6379         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
6380                            LHS.getOperand(0), RHS.getOperand(0),
6381                            DAG.getConstant(Sel, DL, MVT::i32));
6382       }
6383     }
6384   }
6385 
6386   return SDValue();
6387 }
6388 
6389 SDValue SITargetLowering::performOrCombine(SDNode *N,
6390                                            DAGCombinerInfo &DCI) const {
6391   SelectionDAG &DAG = DCI.DAG;
6392   SDValue LHS = N->getOperand(0);
6393   SDValue RHS = N->getOperand(1);
6394 
6395   EVT VT = N->getValueType(0);
6396   if (VT == MVT::i1) {
6397     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
6398     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
6399         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
6400       SDValue Src = LHS.getOperand(0);
6401       if (Src != RHS.getOperand(0))
6402         return SDValue();
6403 
6404       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
6405       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
6406       if (!CLHS || !CRHS)
6407         return SDValue();
6408 
6409       // Only 10 bits are used.
6410       static const uint32_t MaxMask = 0x3ff;
6411 
6412       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
6413       SDLoc DL(N);
6414       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
6415                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
6416     }
6417 
6418     return SDValue();
6419   }
6420 
6421   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
6422   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
6423       LHS.getOpcode() == AMDGPUISD::PERM &&
6424       isa<ConstantSDNode>(LHS.getOperand(2))) {
6425     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
6426     if (!Sel)
6427       return SDValue();
6428 
6429     Sel |= LHS.getConstantOperandVal(2);
6430     SDLoc DL(N);
6431     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
6432                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
6433   }
6434 
6435   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
6436   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
6437   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
6438       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
6439     uint32_t LHSMask = getPermuteMask(DAG, LHS);
6440     uint32_t RHSMask = getPermuteMask(DAG, RHS);
6441     if (LHSMask != ~0u && RHSMask != ~0u) {
6442       // Canonicalize the expression in an attempt to have fewer unique masks
6443       // and therefore fewer registers used to hold the masks.
6444       if (LHSMask > RHSMask) {
6445         std::swap(LHSMask, RHSMask);
6446         std::swap(LHS, RHS);
6447       }
6448 
6449       // Select 0xc for each lane used from source operand. Zero has 0xc mask
6450       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
6451       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6452       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
6453 
6454       // Check of we need to combine values from two sources within a byte.
6455       if (!(LHSUsedLanes & RHSUsedLanes) &&
6456           // If we select high and lower word keep it for SDWA.
6457           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
6458           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
6459         // Kill zero bytes selected by other mask. Zero value is 0xc.
6460         LHSMask &= ~RHSUsedLanes;
6461         RHSMask &= ~LHSUsedLanes;
6462         // Add 4 to each active LHS lane
6463         LHSMask |= LHSUsedLanes & 0x04040404;
6464         // Combine masks
6465         uint32_t Sel = LHSMask | RHSMask;
6466         SDLoc DL(N);
6467 
6468         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
6469                            LHS.getOperand(0), RHS.getOperand(0),
6470                            DAG.getConstant(Sel, DL, MVT::i32));
6471       }
6472     }
6473   }
6474 
6475   if (VT != MVT::i64)
6476     return SDValue();
6477 
6478   // TODO: This could be a generic combine with a predicate for extracting the
6479   // high half of an integer being free.
6480 
6481   // (or i64:x, (zero_extend i32:y)) ->
6482   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
6483   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
6484       RHS.getOpcode() != ISD::ZERO_EXTEND)
6485     std::swap(LHS, RHS);
6486 
6487   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
6488     SDValue ExtSrc = RHS.getOperand(0);
6489     EVT SrcVT = ExtSrc.getValueType();
6490     if (SrcVT == MVT::i32) {
6491       SDLoc SL(N);
6492       SDValue LowLHS, HiBits;
6493       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
6494       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
6495 
6496       DCI.AddToWorklist(LowOr.getNode());
6497       DCI.AddToWorklist(HiBits.getNode());
6498 
6499       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
6500                                 LowOr, HiBits);
6501       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
6502     }
6503   }
6504 
6505   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
6506   if (CRHS) {
6507     if (SDValue Split
6508           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
6509       return Split;
6510   }
6511 
6512   return SDValue();
6513 }
6514 
6515 SDValue SITargetLowering::performXorCombine(SDNode *N,
6516                                             DAGCombinerInfo &DCI) const {
6517   EVT VT = N->getValueType(0);
6518   if (VT != MVT::i64)
6519     return SDValue();
6520 
6521   SDValue LHS = N->getOperand(0);
6522   SDValue RHS = N->getOperand(1);
6523 
6524   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
6525   if (CRHS) {
6526     if (SDValue Split
6527           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
6528       return Split;
6529   }
6530 
6531   return SDValue();
6532 }
6533 
6534 // Instructions that will be lowered with a final instruction that zeros the
6535 // high result bits.
6536 // XXX - probably only need to list legal operations.
6537 static bool fp16SrcZerosHighBits(unsigned Opc) {
6538   switch (Opc) {
6539   case ISD::FADD:
6540   case ISD::FSUB:
6541   case ISD::FMUL:
6542   case ISD::FDIV:
6543   case ISD::FREM:
6544   case ISD::FMA:
6545   case ISD::FMAD:
6546   case ISD::FCANONICALIZE:
6547   case ISD::FP_ROUND:
6548   case ISD::UINT_TO_FP:
6549   case ISD::SINT_TO_FP:
6550   case ISD::FABS:
6551     // Fabs is lowered to a bit operation, but it's an and which will clear the
6552     // high bits anyway.
6553   case ISD::FSQRT:
6554   case ISD::FSIN:
6555   case ISD::FCOS:
6556   case ISD::FPOWI:
6557   case ISD::FPOW:
6558   case ISD::FLOG:
6559   case ISD::FLOG2:
6560   case ISD::FLOG10:
6561   case ISD::FEXP:
6562   case ISD::FEXP2:
6563   case ISD::FCEIL:
6564   case ISD::FTRUNC:
6565   case ISD::FRINT:
6566   case ISD::FNEARBYINT:
6567   case ISD::FROUND:
6568   case ISD::FFLOOR:
6569   case ISD::FMINNUM:
6570   case ISD::FMAXNUM:
6571   case AMDGPUISD::FRACT:
6572   case AMDGPUISD::CLAMP:
6573   case AMDGPUISD::COS_HW:
6574   case AMDGPUISD::SIN_HW:
6575   case AMDGPUISD::FMIN3:
6576   case AMDGPUISD::FMAX3:
6577   case AMDGPUISD::FMED3:
6578   case AMDGPUISD::FMAD_FTZ:
6579   case AMDGPUISD::RCP:
6580   case AMDGPUISD::RSQ:
6581   case AMDGPUISD::RCP_IFLAG:
6582   case AMDGPUISD::LDEXP:
6583     return true;
6584   default:
6585     // fcopysign, select and others may be lowered to 32-bit bit operations
6586     // which don't zero the high bits.
6587     return false;
6588   }
6589 }
6590 
6591 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
6592                                                    DAGCombinerInfo &DCI) const {
6593   if (!Subtarget->has16BitInsts() ||
6594       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
6595     return SDValue();
6596 
6597   EVT VT = N->getValueType(0);
6598   if (VT != MVT::i32)
6599     return SDValue();
6600 
6601   SDValue Src = N->getOperand(0);
6602   if (Src.getValueType() != MVT::i16)
6603     return SDValue();
6604 
6605   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
6606   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
6607   if (Src.getOpcode() == ISD::BITCAST) {
6608     SDValue BCSrc = Src.getOperand(0);
6609     if (BCSrc.getValueType() == MVT::f16 &&
6610         fp16SrcZerosHighBits(BCSrc.getOpcode()))
6611       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
6612   }
6613 
6614   return SDValue();
6615 }
6616 
6617 SDValue SITargetLowering::performClassCombine(SDNode *N,
6618                                               DAGCombinerInfo &DCI) const {
6619   SelectionDAG &DAG = DCI.DAG;
6620   SDValue Mask = N->getOperand(1);
6621 
6622   // fp_class x, 0 -> false
6623   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
6624     if (CMask->isNullValue())
6625       return DAG.getConstant(0, SDLoc(N), MVT::i1);
6626   }
6627 
6628   if (N->getOperand(0).isUndef())
6629     return DAG.getUNDEF(MVT::i1);
6630 
6631   return SDValue();
6632 }
6633 
6634 SDValue SITargetLowering::performRcpCombine(SDNode *N,
6635                                             DAGCombinerInfo &DCI) const {
6636   EVT VT = N->getValueType(0);
6637   SDValue N0 = N->getOperand(0);
6638 
6639   if (N0.isUndef())
6640     return N0;
6641 
6642   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
6643                          N0.getOpcode() == ISD::SINT_TO_FP)) {
6644     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
6645                            N->getFlags());
6646   }
6647 
6648   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
6649 }
6650 
6651 static bool isKnownNeverSNan(SelectionDAG &DAG, SDValue Op) {
6652   if (!DAG.getTargetLoweringInfo().hasFloatingPointExceptions())
6653     return true;
6654 
6655   return DAG.isKnownNeverNaN(Op);
6656 }
6657 
6658 static bool isCanonicalized(SelectionDAG &DAG, SDValue Op,
6659                             const SISubtarget *ST, unsigned MaxDepth=5) {
6660   // If source is a result of another standard FP operation it is already in
6661   // canonical form.
6662 
6663   switch (Op.getOpcode()) {
6664   default:
6665     break;
6666 
6667   // These will flush denorms if required.
6668   case ISD::FADD:
6669   case ISD::FSUB:
6670   case ISD::FMUL:
6671   case ISD::FSQRT:
6672   case ISD::FCEIL:
6673   case ISD::FFLOOR:
6674   case ISD::FMA:
6675   case ISD::FMAD:
6676 
6677   case ISD::FCANONICALIZE:
6678     return true;
6679 
6680   case ISD::FP_ROUND:
6681     return Op.getValueType().getScalarType() != MVT::f16 ||
6682            ST->hasFP16Denormals();
6683 
6684   case ISD::FP_EXTEND:
6685     return Op.getOperand(0).getValueType().getScalarType() != MVT::f16 ||
6686            ST->hasFP16Denormals();
6687 
6688   case ISD::FP16_TO_FP:
6689   case ISD::FP_TO_FP16:
6690     return ST->hasFP16Denormals();
6691 
6692   // It can/will be lowered or combined as a bit operation.
6693   // Need to check their input recursively to handle.
6694   case ISD::FNEG:
6695   case ISD::FABS:
6696     return (MaxDepth > 0) &&
6697            isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1);
6698 
6699   case ISD::FSIN:
6700   case ISD::FCOS:
6701   case ISD::FSINCOS:
6702     return Op.getValueType().getScalarType() != MVT::f16;
6703 
6704   // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms.
6705   // For such targets need to check their input recursively.
6706   case ISD::FMINNUM:
6707   case ISD::FMAXNUM:
6708   case ISD::FMINNAN:
6709   case ISD::FMAXNAN:
6710 
6711     if (ST->supportsMinMaxDenormModes() &&
6712         DAG.isKnownNeverNaN(Op.getOperand(0)) &&
6713         DAG.isKnownNeverNaN(Op.getOperand(1)))
6714       return true;
6715 
6716     return (MaxDepth > 0) &&
6717            isCanonicalized(DAG, Op.getOperand(0), ST, MaxDepth - 1) &&
6718            isCanonicalized(DAG, Op.getOperand(1), ST, MaxDepth - 1);
6719 
6720   case ISD::ConstantFP: {
6721     auto F = cast<ConstantFPSDNode>(Op)->getValueAPF();
6722     return !F.isDenormal() && !(F.isNaN() && F.isSignaling());
6723   }
6724   }
6725   return false;
6726 }
6727 
6728 // Constant fold canonicalize.
6729 SDValue SITargetLowering::performFCanonicalizeCombine(
6730   SDNode *N,
6731   DAGCombinerInfo &DCI) const {
6732   SelectionDAG &DAG = DCI.DAG;
6733   ConstantFPSDNode *CFP = isConstOrConstSplatFP(N->getOperand(0));
6734 
6735   if (!CFP) {
6736     SDValue N0 = N->getOperand(0);
6737     EVT VT = N0.getValueType().getScalarType();
6738     auto ST = getSubtarget();
6739 
6740     if (((VT == MVT::f32 && ST->hasFP32Denormals()) ||
6741          (VT == MVT::f64 && ST->hasFP64Denormals()) ||
6742          (VT == MVT::f16 && ST->hasFP16Denormals())) &&
6743         DAG.isKnownNeverNaN(N0))
6744       return N0;
6745 
6746     bool IsIEEEMode = Subtarget->enableIEEEBit(DAG.getMachineFunction());
6747 
6748     if ((IsIEEEMode || isKnownNeverSNan(DAG, N0)) &&
6749         isCanonicalized(DAG, N0, ST))
6750       return N0;
6751 
6752     return SDValue();
6753   }
6754 
6755   const APFloat &C = CFP->getValueAPF();
6756 
6757   // Flush denormals to 0 if not enabled.
6758   if (C.isDenormal()) {
6759     EVT VT = N->getValueType(0);
6760     EVT SVT = VT.getScalarType();
6761     if (SVT == MVT::f32 && !Subtarget->hasFP32Denormals())
6762       return DAG.getConstantFP(0.0, SDLoc(N), VT);
6763 
6764     if (SVT == MVT::f64 && !Subtarget->hasFP64Denormals())
6765       return DAG.getConstantFP(0.0, SDLoc(N), VT);
6766 
6767     if (SVT == MVT::f16 && !Subtarget->hasFP16Denormals())
6768       return DAG.getConstantFP(0.0, SDLoc(N), VT);
6769   }
6770 
6771   if (C.isNaN()) {
6772     EVT VT = N->getValueType(0);
6773     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
6774     if (C.isSignaling()) {
6775       // Quiet a signaling NaN.
6776       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6777     }
6778 
6779     // Make sure it is the canonical NaN bitpattern.
6780     //
6781     // TODO: Can we use -1 as the canonical NaN value since it's an inline
6782     // immediate?
6783     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
6784       return DAG.getConstantFP(CanonicalQNaN, SDLoc(N), VT);
6785   }
6786 
6787   return N->getOperand(0);
6788 }
6789 
6790 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
6791   switch (Opc) {
6792   case ISD::FMAXNUM:
6793     return AMDGPUISD::FMAX3;
6794   case ISD::SMAX:
6795     return AMDGPUISD::SMAX3;
6796   case ISD::UMAX:
6797     return AMDGPUISD::UMAX3;
6798   case ISD::FMINNUM:
6799     return AMDGPUISD::FMIN3;
6800   case ISD::SMIN:
6801     return AMDGPUISD::SMIN3;
6802   case ISD::UMIN:
6803     return AMDGPUISD::UMIN3;
6804   default:
6805     llvm_unreachable("Not a min/max opcode");
6806   }
6807 }
6808 
6809 SDValue SITargetLowering::performIntMed3ImmCombine(
6810   SelectionDAG &DAG, const SDLoc &SL,
6811   SDValue Op0, SDValue Op1, bool Signed) const {
6812   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
6813   if (!K1)
6814     return SDValue();
6815 
6816   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
6817   if (!K0)
6818     return SDValue();
6819 
6820   if (Signed) {
6821     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
6822       return SDValue();
6823   } else {
6824     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
6825       return SDValue();
6826   }
6827 
6828   EVT VT = K0->getValueType(0);
6829   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
6830   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
6831     return DAG.getNode(Med3Opc, SL, VT,
6832                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
6833   }
6834 
6835   // If there isn't a 16-bit med3 operation, convert to 32-bit.
6836   MVT NVT = MVT::i32;
6837   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
6838 
6839   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
6840   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
6841   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
6842 
6843   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
6844   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
6845 }
6846 
6847 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
6848   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
6849     return C;
6850 
6851   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
6852     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
6853       return C;
6854   }
6855 
6856   return nullptr;
6857 }
6858 
6859 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
6860                                                   const SDLoc &SL,
6861                                                   SDValue Op0,
6862                                                   SDValue Op1) const {
6863   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
6864   if (!K1)
6865     return SDValue();
6866 
6867   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
6868   if (!K0)
6869     return SDValue();
6870 
6871   // Ordered >= (although NaN inputs should have folded away by now).
6872   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
6873   if (Cmp == APFloat::cmpGreaterThan)
6874     return SDValue();
6875 
6876   // TODO: Check IEEE bit enabled?
6877   EVT VT = Op0.getValueType();
6878   if (Subtarget->enableDX10Clamp()) {
6879     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
6880     // hardware fmed3 behavior converting to a min.
6881     // FIXME: Should this be allowing -0.0?
6882     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
6883       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
6884   }
6885 
6886   // med3 for f16 is only available on gfx9+, and not available for v2f16.
6887   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
6888     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
6889     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
6890     // then give the other result, which is different from med3 with a NaN
6891     // input.
6892     SDValue Var = Op0.getOperand(0);
6893     if (!isKnownNeverSNan(DAG, Var))
6894       return SDValue();
6895 
6896     return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
6897                        Var, SDValue(K0, 0), SDValue(K1, 0));
6898   }
6899 
6900   return SDValue();
6901 }
6902 
6903 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
6904                                                DAGCombinerInfo &DCI) const {
6905   SelectionDAG &DAG = DCI.DAG;
6906 
6907   EVT VT = N->getValueType(0);
6908   unsigned Opc = N->getOpcode();
6909   SDValue Op0 = N->getOperand(0);
6910   SDValue Op1 = N->getOperand(1);
6911 
6912   // Only do this if the inner op has one use since this will just increases
6913   // register pressure for no benefit.
6914 
6915 
6916   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
6917       !VT.isVector() && VT != MVT::f64 &&
6918       ((VT != MVT::f16 && VT != MVT::i16) || Subtarget->hasMin3Max3_16())) {
6919     // max(max(a, b), c) -> max3(a, b, c)
6920     // min(min(a, b), c) -> min3(a, b, c)
6921     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
6922       SDLoc DL(N);
6923       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
6924                          DL,
6925                          N->getValueType(0),
6926                          Op0.getOperand(0),
6927                          Op0.getOperand(1),
6928                          Op1);
6929     }
6930 
6931     // Try commuted.
6932     // max(a, max(b, c)) -> max3(a, b, c)
6933     // min(a, min(b, c)) -> min3(a, b, c)
6934     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
6935       SDLoc DL(N);
6936       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
6937                          DL,
6938                          N->getValueType(0),
6939                          Op0,
6940                          Op1.getOperand(0),
6941                          Op1.getOperand(1));
6942     }
6943   }
6944 
6945   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
6946   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
6947     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
6948       return Med3;
6949   }
6950 
6951   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
6952     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
6953       return Med3;
6954   }
6955 
6956   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
6957   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
6958        (Opc == AMDGPUISD::FMIN_LEGACY &&
6959         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
6960       (VT == MVT::f32 || VT == MVT::f64 ||
6961        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
6962        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
6963       Op0.hasOneUse()) {
6964     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
6965       return Res;
6966   }
6967 
6968   return SDValue();
6969 }
6970 
6971 static bool isClampZeroToOne(SDValue A, SDValue B) {
6972   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
6973     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
6974       // FIXME: Should this be allowing -0.0?
6975       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
6976              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
6977     }
6978   }
6979 
6980   return false;
6981 }
6982 
6983 // FIXME: Should only worry about snans for version with chain.
6984 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
6985                                               DAGCombinerInfo &DCI) const {
6986   EVT VT = N->getValueType(0);
6987   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
6988   // NaNs. With a NaN input, the order of the operands may change the result.
6989 
6990   SelectionDAG &DAG = DCI.DAG;
6991   SDLoc SL(N);
6992 
6993   SDValue Src0 = N->getOperand(0);
6994   SDValue Src1 = N->getOperand(1);
6995   SDValue Src2 = N->getOperand(2);
6996 
6997   if (isClampZeroToOne(Src0, Src1)) {
6998     // const_a, const_b, x -> clamp is safe in all cases including signaling
6999     // nans.
7000     // FIXME: Should this be allowing -0.0?
7001     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
7002   }
7003 
7004   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
7005   // handling no dx10-clamp?
7006   if (Subtarget->enableDX10Clamp()) {
7007     // If NaNs is clamped to 0, we are free to reorder the inputs.
7008 
7009     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
7010       std::swap(Src0, Src1);
7011 
7012     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
7013       std::swap(Src1, Src2);
7014 
7015     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
7016       std::swap(Src0, Src1);
7017 
7018     if (isClampZeroToOne(Src1, Src2))
7019       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
7020   }
7021 
7022   return SDValue();
7023 }
7024 
7025 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
7026                                                  DAGCombinerInfo &DCI) const {
7027   SDValue Src0 = N->getOperand(0);
7028   SDValue Src1 = N->getOperand(1);
7029   if (Src0.isUndef() && Src1.isUndef())
7030     return DCI.DAG.getUNDEF(N->getValueType(0));
7031   return SDValue();
7032 }
7033 
7034 SDValue SITargetLowering::performExtractVectorEltCombine(
7035   SDNode *N, DAGCombinerInfo &DCI) const {
7036   SDValue Vec = N->getOperand(0);
7037   SelectionDAG &DAG = DCI.DAG;
7038 
7039   EVT VecVT = Vec.getValueType();
7040   EVT EltVT = VecVT.getVectorElementType();
7041 
7042   if ((Vec.getOpcode() == ISD::FNEG ||
7043        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
7044     SDLoc SL(N);
7045     EVT EltVT = N->getValueType(0);
7046     SDValue Idx = N->getOperand(1);
7047     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7048                               Vec.getOperand(0), Idx);
7049     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
7050   }
7051 
7052   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
7053   //    =>
7054   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
7055   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
7056   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
7057   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
7058     SDLoc SL(N);
7059     EVT EltVT = N->getValueType(0);
7060     SDValue Idx = N->getOperand(1);
7061     unsigned Opc = Vec.getOpcode();
7062 
7063     switch(Opc) {
7064     default:
7065       return SDValue();
7066       // TODO: Support other binary operations.
7067     case ISD::FADD:
7068     case ISD::ADD:
7069     case ISD::UMIN:
7070     case ISD::UMAX:
7071     case ISD::SMIN:
7072     case ISD::SMAX:
7073     case ISD::FMAXNUM:
7074     case ISD::FMINNUM:
7075       return DAG.getNode(Opc, SL, EltVT,
7076                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7077                                      Vec.getOperand(0), Idx),
7078                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
7079                                      Vec.getOperand(1), Idx));
7080     }
7081   }
7082 
7083   if (!DCI.isBeforeLegalize())
7084     return SDValue();
7085 
7086   unsigned VecSize = VecVT.getSizeInBits();
7087   unsigned EltSize = EltVT.getSizeInBits();
7088 
7089   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
7090   // elements. This exposes more load reduction opportunities by replacing
7091   // multiple small extract_vector_elements with a single 32-bit extract.
7092   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
7093   if (EltSize <= 16 &&
7094       EltVT.isByteSized() &&
7095       VecSize > 32 &&
7096       VecSize % 32 == 0 &&
7097       Idx) {
7098     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
7099 
7100     unsigned BitIndex = Idx->getZExtValue() * EltSize;
7101     unsigned EltIdx = BitIndex / 32;
7102     unsigned LeftoverBitIdx = BitIndex % 32;
7103     SDLoc SL(N);
7104 
7105     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
7106     DCI.AddToWorklist(Cast.getNode());
7107 
7108     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
7109                               DAG.getConstant(EltIdx, SL, MVT::i32));
7110     DCI.AddToWorklist(Elt.getNode());
7111     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
7112                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
7113     DCI.AddToWorklist(Srl.getNode());
7114 
7115     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
7116     DCI.AddToWorklist(Trunc.getNode());
7117     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
7118   }
7119 
7120   return SDValue();
7121 }
7122 
7123 static bool convertBuildVectorCastElt(SelectionDAG &DAG,
7124                                       SDValue &Lo, SDValue &Hi) {
7125   if (Hi.getOpcode() == ISD::BITCAST &&
7126       Hi.getOperand(0).getValueType() == MVT::f16 &&
7127       (isa<ConstantSDNode>(Lo) || Lo.isUndef())) {
7128     Lo = DAG.getNode(ISD::BITCAST, SDLoc(Lo), MVT::f16, Lo);
7129     Hi = Hi.getOperand(0);
7130     return true;
7131   }
7132 
7133   return false;
7134 }
7135 
7136 SDValue SITargetLowering::performBuildVectorCombine(
7137   SDNode *N, DAGCombinerInfo &DCI) const {
7138   SDLoc SL(N);
7139 
7140   if (!isTypeLegal(MVT::v2i16))
7141     return SDValue();
7142   SelectionDAG &DAG = DCI.DAG;
7143   EVT VT = N->getValueType(0);
7144 
7145   if (VT == MVT::v2i16) {
7146     SDValue Lo = N->getOperand(0);
7147     SDValue Hi = N->getOperand(1);
7148 
7149     // v2i16 build_vector (const|undef), (bitcast f16:$x)
7150     // -> bitcast (v2f16 build_vector const|undef, $x
7151     if (convertBuildVectorCastElt(DAG, Lo, Hi)) {
7152       SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Lo, Hi  });
7153       return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
7154     }
7155 
7156     if (convertBuildVectorCastElt(DAG, Hi, Lo)) {
7157       SDValue NewVec = DAG.getBuildVector(MVT::v2f16, SL, { Hi, Lo  });
7158       return DAG.getNode(ISD::BITCAST, SL, VT, NewVec);
7159     }
7160   }
7161 
7162   return SDValue();
7163 }
7164 
7165 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
7166                                           const SDNode *N0,
7167                                           const SDNode *N1) const {
7168   EVT VT = N0->getValueType(0);
7169 
7170   // Only do this if we are not trying to support denormals. v_mad_f32 does not
7171   // support denormals ever.
7172   if ((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
7173       (VT == MVT::f16 && !Subtarget->hasFP16Denormals()))
7174     return ISD::FMAD;
7175 
7176   const TargetOptions &Options = DAG.getTarget().Options;
7177   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
7178        (N0->getFlags().hasAllowContract() &&
7179         N1->getFlags().hasAllowContract())) &&
7180       isFMAFasterThanFMulAndFAdd(VT)) {
7181     return ISD::FMA;
7182   }
7183 
7184   return 0;
7185 }
7186 
7187 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
7188                            EVT VT,
7189                            SDValue N0, SDValue N1, SDValue N2,
7190                            bool Signed) {
7191   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
7192   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
7193   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
7194   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
7195 }
7196 
7197 SDValue SITargetLowering::performAddCombine(SDNode *N,
7198                                             DAGCombinerInfo &DCI) const {
7199   SelectionDAG &DAG = DCI.DAG;
7200   EVT VT = N->getValueType(0);
7201   SDLoc SL(N);
7202   SDValue LHS = N->getOperand(0);
7203   SDValue RHS = N->getOperand(1);
7204 
7205   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
7206       && Subtarget->hasMad64_32() &&
7207       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
7208       VT.getScalarSizeInBits() <= 64) {
7209     if (LHS.getOpcode() != ISD::MUL)
7210       std::swap(LHS, RHS);
7211 
7212     SDValue MulLHS = LHS.getOperand(0);
7213     SDValue MulRHS = LHS.getOperand(1);
7214     SDValue AddRHS = RHS;
7215 
7216     // TODO: Maybe restrict if SGPR inputs.
7217     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
7218         numBitsUnsigned(MulRHS, DAG) <= 32) {
7219       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
7220       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
7221       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
7222       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
7223     }
7224 
7225     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
7226       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
7227       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
7228       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
7229       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
7230     }
7231 
7232     return SDValue();
7233   }
7234 
7235   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
7236     return SDValue();
7237 
7238   // add x, zext (setcc) => addcarry x, 0, setcc
7239   // add x, sext (setcc) => subcarry x, 0, setcc
7240   unsigned Opc = LHS.getOpcode();
7241   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
7242       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
7243     std::swap(RHS, LHS);
7244 
7245   Opc = RHS.getOpcode();
7246   switch (Opc) {
7247   default: break;
7248   case ISD::ZERO_EXTEND:
7249   case ISD::SIGN_EXTEND:
7250   case ISD::ANY_EXTEND: {
7251     auto Cond = RHS.getOperand(0);
7252     if (!isBoolSGPR(Cond))
7253       break;
7254     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
7255     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
7256     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
7257     return DAG.getNode(Opc, SL, VTList, Args);
7258   }
7259   case ISD::ADDCARRY: {
7260     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
7261     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
7262     if (!C || C->getZExtValue() != 0) break;
7263     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
7264     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
7265   }
7266   }
7267   return SDValue();
7268 }
7269 
7270 SDValue SITargetLowering::performSubCombine(SDNode *N,
7271                                             DAGCombinerInfo &DCI) const {
7272   SelectionDAG &DAG = DCI.DAG;
7273   EVT VT = N->getValueType(0);
7274 
7275   if (VT != MVT::i32)
7276     return SDValue();
7277 
7278   SDLoc SL(N);
7279   SDValue LHS = N->getOperand(0);
7280   SDValue RHS = N->getOperand(1);
7281 
7282   unsigned Opc = LHS.getOpcode();
7283   if (Opc != ISD::SUBCARRY)
7284     std::swap(RHS, LHS);
7285 
7286   if (LHS.getOpcode() == ISD::SUBCARRY) {
7287     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
7288     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
7289     if (!C || C->getZExtValue() != 0)
7290       return SDValue();
7291     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
7292     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
7293   }
7294   return SDValue();
7295 }
7296 
7297 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
7298   DAGCombinerInfo &DCI) const {
7299 
7300   if (N->getValueType(0) != MVT::i32)
7301     return SDValue();
7302 
7303   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
7304   if (!C || C->getZExtValue() != 0)
7305     return SDValue();
7306 
7307   SelectionDAG &DAG = DCI.DAG;
7308   SDValue LHS = N->getOperand(0);
7309 
7310   // addcarry (add x, y), 0, cc => addcarry x, y, cc
7311   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
7312   unsigned LHSOpc = LHS.getOpcode();
7313   unsigned Opc = N->getOpcode();
7314   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
7315       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
7316     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
7317     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
7318   }
7319   return SDValue();
7320 }
7321 
7322 SDValue SITargetLowering::performFAddCombine(SDNode *N,
7323                                              DAGCombinerInfo &DCI) const {
7324   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
7325     return SDValue();
7326 
7327   SelectionDAG &DAG = DCI.DAG;
7328   EVT VT = N->getValueType(0);
7329 
7330   SDLoc SL(N);
7331   SDValue LHS = N->getOperand(0);
7332   SDValue RHS = N->getOperand(1);
7333 
7334   // These should really be instruction patterns, but writing patterns with
7335   // source modiifiers is a pain.
7336 
7337   // fadd (fadd (a, a), b) -> mad 2.0, a, b
7338   if (LHS.getOpcode() == ISD::FADD) {
7339     SDValue A = LHS.getOperand(0);
7340     if (A == LHS.getOperand(1)) {
7341       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
7342       if (FusedOp != 0) {
7343         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7344         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
7345       }
7346     }
7347   }
7348 
7349   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
7350   if (RHS.getOpcode() == ISD::FADD) {
7351     SDValue A = RHS.getOperand(0);
7352     if (A == RHS.getOperand(1)) {
7353       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
7354       if (FusedOp != 0) {
7355         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7356         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
7357       }
7358     }
7359   }
7360 
7361   return SDValue();
7362 }
7363 
7364 SDValue SITargetLowering::performFSubCombine(SDNode *N,
7365                                              DAGCombinerInfo &DCI) const {
7366   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
7367     return SDValue();
7368 
7369   SelectionDAG &DAG = DCI.DAG;
7370   SDLoc SL(N);
7371   EVT VT = N->getValueType(0);
7372   assert(!VT.isVector());
7373 
7374   // Try to get the fneg to fold into the source modifier. This undoes generic
7375   // DAG combines and folds them into the mad.
7376   //
7377   // Only do this if we are not trying to support denormals. v_mad_f32 does
7378   // not support denormals ever.
7379   SDValue LHS = N->getOperand(0);
7380   SDValue RHS = N->getOperand(1);
7381   if (LHS.getOpcode() == ISD::FADD) {
7382     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
7383     SDValue A = LHS.getOperand(0);
7384     if (A == LHS.getOperand(1)) {
7385       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
7386       if (FusedOp != 0){
7387         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
7388         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7389 
7390         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
7391       }
7392     }
7393   }
7394 
7395   if (RHS.getOpcode() == ISD::FADD) {
7396     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
7397 
7398     SDValue A = RHS.getOperand(0);
7399     if (A == RHS.getOperand(1)) {
7400       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
7401       if (FusedOp != 0){
7402         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
7403         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
7404       }
7405     }
7406   }
7407 
7408   return SDValue();
7409 }
7410 
7411 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
7412                                               DAGCombinerInfo &DCI) const {
7413   SelectionDAG &DAG = DCI.DAG;
7414   SDLoc SL(N);
7415 
7416   SDValue LHS = N->getOperand(0);
7417   SDValue RHS = N->getOperand(1);
7418   EVT VT = LHS.getValueType();
7419   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
7420 
7421   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
7422   if (!CRHS) {
7423     CRHS = dyn_cast<ConstantSDNode>(LHS);
7424     if (CRHS) {
7425       std::swap(LHS, RHS);
7426       CC = getSetCCSwappedOperands(CC);
7427     }
7428   }
7429 
7430   if (CRHS) {
7431     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
7432         isBoolSGPR(LHS.getOperand(0))) {
7433       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
7434       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
7435       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
7436       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
7437       if ((CRHS->isAllOnesValue() &&
7438            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
7439           (CRHS->isNullValue() &&
7440            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
7441         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
7442                            DAG.getConstant(-1, SL, MVT::i1));
7443       if ((CRHS->isAllOnesValue() &&
7444            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
7445           (CRHS->isNullValue() &&
7446            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
7447         return LHS.getOperand(0);
7448     }
7449 
7450     uint64_t CRHSVal = CRHS->getZExtValue();
7451     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
7452         LHS.getOpcode() == ISD::SELECT &&
7453         isa<ConstantSDNode>(LHS.getOperand(1)) &&
7454         isa<ConstantSDNode>(LHS.getOperand(2)) &&
7455         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
7456         isBoolSGPR(LHS.getOperand(0))) {
7457       // Given CT != FT:
7458       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
7459       // setcc (select cc, CT, CF), CF, ne => cc
7460       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
7461       // setcc (select cc, CT, CF), CT, eq => cc
7462       uint64_t CT = LHS.getConstantOperandVal(1);
7463       uint64_t CF = LHS.getConstantOperandVal(2);
7464 
7465       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
7466           (CT == CRHSVal && CC == ISD::SETNE))
7467         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
7468                            DAG.getConstant(-1, SL, MVT::i1));
7469       if ((CF == CRHSVal && CC == ISD::SETNE) ||
7470           (CT == CRHSVal && CC == ISD::SETEQ))
7471         return LHS.getOperand(0);
7472     }
7473   }
7474 
7475   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
7476                                            VT != MVT::f16))
7477     return SDValue();
7478 
7479   // Match isinf pattern
7480   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
7481   if (CC == ISD::SETOEQ && LHS.getOpcode() == ISD::FABS) {
7482     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
7483     if (!CRHS)
7484       return SDValue();
7485 
7486     const APFloat &APF = CRHS->getValueAPF();
7487     if (APF.isInfinity() && !APF.isNegative()) {
7488       unsigned Mask = SIInstrFlags::P_INFINITY | SIInstrFlags::N_INFINITY;
7489       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
7490                          DAG.getConstant(Mask, SL, MVT::i32));
7491     }
7492   }
7493 
7494   return SDValue();
7495 }
7496 
7497 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
7498                                                      DAGCombinerInfo &DCI) const {
7499   SelectionDAG &DAG = DCI.DAG;
7500   SDLoc SL(N);
7501   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
7502 
7503   SDValue Src = N->getOperand(0);
7504   SDValue Srl = N->getOperand(0);
7505   if (Srl.getOpcode() == ISD::ZERO_EXTEND)
7506     Srl = Srl.getOperand(0);
7507 
7508   // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
7509   if (Srl.getOpcode() == ISD::SRL) {
7510     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
7511     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
7512     // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
7513 
7514     if (const ConstantSDNode *C =
7515         dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
7516       Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
7517                                EVT(MVT::i32));
7518 
7519       unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
7520       if (SrcOffset < 32 && SrcOffset % 8 == 0) {
7521         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
7522                            MVT::f32, Srl);
7523       }
7524     }
7525   }
7526 
7527   APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
7528 
7529   KnownBits Known;
7530   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
7531                                         !DCI.isBeforeLegalizeOps());
7532   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
7533   if (TLI.ShrinkDemandedConstant(Src, Demanded, TLO) ||
7534       TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
7535     DCI.CommitTargetLoweringOpt(TLO);
7536   }
7537 
7538   return SDValue();
7539 }
7540 
7541 SDValue SITargetLowering::performClampCombine(SDNode *N,
7542                                               DAGCombinerInfo &DCI) const {
7543   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
7544   if (!CSrc)
7545     return SDValue();
7546 
7547   const APFloat &F = CSrc->getValueAPF();
7548   APFloat Zero = APFloat::getZero(F.getSemantics());
7549   APFloat::cmpResult Cmp0 = F.compare(Zero);
7550   if (Cmp0 == APFloat::cmpLessThan ||
7551       (Cmp0 == APFloat::cmpUnordered && Subtarget->enableDX10Clamp())) {
7552     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
7553   }
7554 
7555   APFloat One(F.getSemantics(), "1.0");
7556   APFloat::cmpResult Cmp1 = F.compare(One);
7557   if (Cmp1 == APFloat::cmpGreaterThan)
7558     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
7559 
7560   return SDValue(CSrc, 0);
7561 }
7562 
7563 
7564 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
7565                                             DAGCombinerInfo &DCI) const {
7566   switch (N->getOpcode()) {
7567   default:
7568     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
7569   case ISD::ADD:
7570     return performAddCombine(N, DCI);
7571   case ISD::SUB:
7572     return performSubCombine(N, DCI);
7573   case ISD::ADDCARRY:
7574   case ISD::SUBCARRY:
7575     return performAddCarrySubCarryCombine(N, DCI);
7576   case ISD::FADD:
7577     return performFAddCombine(N, DCI);
7578   case ISD::FSUB:
7579     return performFSubCombine(N, DCI);
7580   case ISD::SETCC:
7581     return performSetCCCombine(N, DCI);
7582   case ISD::FMAXNUM:
7583   case ISD::FMINNUM:
7584   case ISD::SMAX:
7585   case ISD::SMIN:
7586   case ISD::UMAX:
7587   case ISD::UMIN:
7588   case AMDGPUISD::FMIN_LEGACY:
7589   case AMDGPUISD::FMAX_LEGACY: {
7590     if (DCI.getDAGCombineLevel() >= AfterLegalizeDAG &&
7591         getTargetMachine().getOptLevel() > CodeGenOpt::None)
7592       return performMinMaxCombine(N, DCI);
7593     break;
7594   }
7595   case ISD::LOAD: {
7596     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
7597       return Widended;
7598     LLVM_FALLTHROUGH;
7599   }
7600   case ISD::STORE:
7601   case ISD::ATOMIC_LOAD:
7602   case ISD::ATOMIC_STORE:
7603   case ISD::ATOMIC_CMP_SWAP:
7604   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
7605   case ISD::ATOMIC_SWAP:
7606   case ISD::ATOMIC_LOAD_ADD:
7607   case ISD::ATOMIC_LOAD_SUB:
7608   case ISD::ATOMIC_LOAD_AND:
7609   case ISD::ATOMIC_LOAD_OR:
7610   case ISD::ATOMIC_LOAD_XOR:
7611   case ISD::ATOMIC_LOAD_NAND:
7612   case ISD::ATOMIC_LOAD_MIN:
7613   case ISD::ATOMIC_LOAD_MAX:
7614   case ISD::ATOMIC_LOAD_UMIN:
7615   case ISD::ATOMIC_LOAD_UMAX:
7616   case AMDGPUISD::ATOMIC_INC:
7617   case AMDGPUISD::ATOMIC_DEC:
7618   case AMDGPUISD::ATOMIC_LOAD_FADD:
7619   case AMDGPUISD::ATOMIC_LOAD_FMIN:
7620   case AMDGPUISD::ATOMIC_LOAD_FMAX:  // TODO: Target mem intrinsics.
7621     if (DCI.isBeforeLegalize())
7622       break;
7623     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
7624   case ISD::AND:
7625     return performAndCombine(N, DCI);
7626   case ISD::OR:
7627     return performOrCombine(N, DCI);
7628   case ISD::XOR:
7629     return performXorCombine(N, DCI);
7630   case ISD::ZERO_EXTEND:
7631     return performZeroExtendCombine(N, DCI);
7632   case AMDGPUISD::FP_CLASS:
7633     return performClassCombine(N, DCI);
7634   case ISD::FCANONICALIZE:
7635     return performFCanonicalizeCombine(N, DCI);
7636   case AMDGPUISD::RCP:
7637     return performRcpCombine(N, DCI);
7638   case AMDGPUISD::FRACT:
7639   case AMDGPUISD::RSQ:
7640   case AMDGPUISD::RCP_LEGACY:
7641   case AMDGPUISD::RSQ_LEGACY:
7642   case AMDGPUISD::RCP_IFLAG:
7643   case AMDGPUISD::RSQ_CLAMP:
7644   case AMDGPUISD::LDEXP: {
7645     SDValue Src = N->getOperand(0);
7646     if (Src.isUndef())
7647       return Src;
7648     break;
7649   }
7650   case ISD::SINT_TO_FP:
7651   case ISD::UINT_TO_FP:
7652     return performUCharToFloatCombine(N, DCI);
7653   case AMDGPUISD::CVT_F32_UBYTE0:
7654   case AMDGPUISD::CVT_F32_UBYTE1:
7655   case AMDGPUISD::CVT_F32_UBYTE2:
7656   case AMDGPUISD::CVT_F32_UBYTE3:
7657     return performCvtF32UByteNCombine(N, DCI);
7658   case AMDGPUISD::FMED3:
7659     return performFMed3Combine(N, DCI);
7660   case AMDGPUISD::CVT_PKRTZ_F16_F32:
7661     return performCvtPkRTZCombine(N, DCI);
7662   case AMDGPUISD::CLAMP:
7663     return performClampCombine(N, DCI);
7664   case ISD::SCALAR_TO_VECTOR: {
7665     SelectionDAG &DAG = DCI.DAG;
7666     EVT VT = N->getValueType(0);
7667 
7668     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
7669     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
7670       SDLoc SL(N);
7671       SDValue Src = N->getOperand(0);
7672       EVT EltVT = Src.getValueType();
7673       if (EltVT == MVT::f16)
7674         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
7675 
7676       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
7677       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
7678     }
7679 
7680     break;
7681   }
7682   case ISD::EXTRACT_VECTOR_ELT:
7683     return performExtractVectorEltCombine(N, DCI);
7684   case ISD::BUILD_VECTOR:
7685     return performBuildVectorCombine(N, DCI);
7686   }
7687   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
7688 }
7689 
7690 /// Helper function for adjustWritemask
7691 static unsigned SubIdx2Lane(unsigned Idx) {
7692   switch (Idx) {
7693   default: return 0;
7694   case AMDGPU::sub0: return 0;
7695   case AMDGPU::sub1: return 1;
7696   case AMDGPU::sub2: return 2;
7697   case AMDGPU::sub3: return 3;
7698   }
7699 }
7700 
7701 /// Adjust the writemask of MIMG instructions
7702 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
7703                                           SelectionDAG &DAG) const {
7704   unsigned Opcode = Node->getMachineOpcode();
7705 
7706   // Subtract 1 because the vdata output is not a MachineSDNode operand.
7707   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
7708   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
7709     return Node; // not implemented for D16
7710 
7711   SDNode *Users[4] = { nullptr };
7712   unsigned Lane = 0;
7713   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
7714   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
7715   unsigned NewDmask = 0;
7716   bool HasChain = Node->getNumValues() > 1;
7717 
7718   if (OldDmask == 0) {
7719     // These are folded out, but on the chance it happens don't assert.
7720     return Node;
7721   }
7722 
7723   // Try to figure out the used register components
7724   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
7725        I != E; ++I) {
7726 
7727     // Don't look at users of the chain.
7728     if (I.getUse().getResNo() != 0)
7729       continue;
7730 
7731     // Abort if we can't understand the usage
7732     if (!I->isMachineOpcode() ||
7733         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
7734       return Node;
7735 
7736     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
7737     // Note that subregs are packed, i.e. Lane==0 is the first bit set
7738     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
7739     // set, etc.
7740     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
7741 
7742     // Set which texture component corresponds to the lane.
7743     unsigned Comp;
7744     for (unsigned i = 0, Dmask = OldDmask; i <= Lane; i++) {
7745       Comp = countTrailingZeros(Dmask);
7746       Dmask &= ~(1 << Comp);
7747     }
7748 
7749     // Abort if we have more than one user per component
7750     if (Users[Lane])
7751       return Node;
7752 
7753     Users[Lane] = *I;
7754     NewDmask |= 1 << Comp;
7755   }
7756 
7757   // Abort if there's no change
7758   if (NewDmask == OldDmask)
7759     return Node;
7760 
7761   unsigned BitsSet = countPopulation(NewDmask);
7762 
7763   int NewOpcode = AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), BitsSet);
7764   assert(NewOpcode != -1 &&
7765          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
7766          "failed to find equivalent MIMG op");
7767 
7768   // Adjust the writemask in the node
7769   SmallVector<SDValue, 12> Ops;
7770   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
7771   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
7772   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
7773 
7774   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
7775 
7776   MVT ResultVT = BitsSet == 1 ?
7777     SVT : MVT::getVectorVT(SVT, BitsSet == 3 ? 4 : BitsSet);
7778   SDVTList NewVTList = HasChain ?
7779     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
7780 
7781 
7782   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
7783                                               NewVTList, Ops);
7784 
7785   if (HasChain) {
7786     // Update chain.
7787     NewNode->setMemRefs(Node->memoperands_begin(), Node->memoperands_end());
7788     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
7789   }
7790 
7791   if (BitsSet == 1) {
7792     assert(Node->hasNUsesOfValue(1, 0));
7793     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
7794                                       SDLoc(Node), Users[Lane]->getValueType(0),
7795                                       SDValue(NewNode, 0));
7796     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
7797     return nullptr;
7798   }
7799 
7800   // Update the users of the node with the new indices
7801   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 4; ++i) {
7802     SDNode *User = Users[i];
7803     if (!User)
7804       continue;
7805 
7806     SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
7807     DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
7808 
7809     switch (Idx) {
7810     default: break;
7811     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
7812     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
7813     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
7814     }
7815   }
7816 
7817   DAG.RemoveDeadNode(Node);
7818   return nullptr;
7819 }
7820 
7821 static bool isFrameIndexOp(SDValue Op) {
7822   if (Op.getOpcode() == ISD::AssertZext)
7823     Op = Op.getOperand(0);
7824 
7825   return isa<FrameIndexSDNode>(Op);
7826 }
7827 
7828 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
7829 /// with frame index operands.
7830 /// LLVM assumes that inputs are to these instructions are registers.
7831 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
7832                                                         SelectionDAG &DAG) const {
7833   if (Node->getOpcode() == ISD::CopyToReg) {
7834     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
7835     SDValue SrcVal = Node->getOperand(2);
7836 
7837     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
7838     // to try understanding copies to physical registers.
7839     if (SrcVal.getValueType() == MVT::i1 &&
7840         TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
7841       SDLoc SL(Node);
7842       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
7843       SDValue VReg = DAG.getRegister(
7844         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
7845 
7846       SDNode *Glued = Node->getGluedNode();
7847       SDValue ToVReg
7848         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
7849                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
7850       SDValue ToResultReg
7851         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
7852                            VReg, ToVReg.getValue(1));
7853       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
7854       DAG.RemoveDeadNode(Node);
7855       return ToResultReg.getNode();
7856     }
7857   }
7858 
7859   SmallVector<SDValue, 8> Ops;
7860   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
7861     if (!isFrameIndexOp(Node->getOperand(i))) {
7862       Ops.push_back(Node->getOperand(i));
7863       continue;
7864     }
7865 
7866     SDLoc DL(Node);
7867     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
7868                                      Node->getOperand(i).getValueType(),
7869                                      Node->getOperand(i)), 0));
7870   }
7871 
7872   return DAG.UpdateNodeOperands(Node, Ops);
7873 }
7874 
7875 /// Fold the instructions after selecting them.
7876 /// Returns null if users were already updated.
7877 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
7878                                           SelectionDAG &DAG) const {
7879   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7880   unsigned Opcode = Node->getMachineOpcode();
7881 
7882   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
7883       !TII->isGather4(Opcode)) {
7884     return adjustWritemask(Node, DAG);
7885   }
7886 
7887   if (Opcode == AMDGPU::INSERT_SUBREG ||
7888       Opcode == AMDGPU::REG_SEQUENCE) {
7889     legalizeTargetIndependentNode(Node, DAG);
7890     return Node;
7891   }
7892 
7893   switch (Opcode) {
7894   case AMDGPU::V_DIV_SCALE_F32:
7895   case AMDGPU::V_DIV_SCALE_F64: {
7896     // Satisfy the operand register constraint when one of the inputs is
7897     // undefined. Ordinarily each undef value will have its own implicit_def of
7898     // a vreg, so force these to use a single register.
7899     SDValue Src0 = Node->getOperand(0);
7900     SDValue Src1 = Node->getOperand(1);
7901     SDValue Src2 = Node->getOperand(2);
7902 
7903     if ((Src0.isMachineOpcode() &&
7904          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
7905         (Src0 == Src1 || Src0 == Src2))
7906       break;
7907 
7908     MVT VT = Src0.getValueType().getSimpleVT();
7909     const TargetRegisterClass *RC = getRegClassFor(VT);
7910 
7911     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
7912     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
7913 
7914     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
7915                                       UndefReg, Src0, SDValue());
7916 
7917     // src0 must be the same register as src1 or src2, even if the value is
7918     // undefined, so make sure we don't violate this constraint.
7919     if (Src0.isMachineOpcode() &&
7920         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
7921       if (Src1.isMachineOpcode() &&
7922           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
7923         Src0 = Src1;
7924       else if (Src2.isMachineOpcode() &&
7925                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
7926         Src0 = Src2;
7927       else {
7928         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
7929         Src0 = UndefReg;
7930         Src1 = UndefReg;
7931       }
7932     } else
7933       break;
7934 
7935     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
7936     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
7937       Ops.push_back(Node->getOperand(I));
7938 
7939     Ops.push_back(ImpDef.getValue(1));
7940     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
7941   }
7942   default:
7943     break;
7944   }
7945 
7946   return Node;
7947 }
7948 
7949 /// Assign the register class depending on the number of
7950 /// bits set in the writemask
7951 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
7952                                                      SDNode *Node) const {
7953   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7954 
7955   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
7956 
7957   if (TII->isVOP3(MI.getOpcode())) {
7958     // Make sure constant bus requirements are respected.
7959     TII->legalizeOperandsVOP3(MRI, MI);
7960     return;
7961   }
7962 
7963   // Replace unused atomics with the no return version.
7964   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
7965   if (NoRetAtomicOp != -1) {
7966     if (!Node->hasAnyUseOfValue(0)) {
7967       MI.setDesc(TII->get(NoRetAtomicOp));
7968       MI.RemoveOperand(0);
7969       return;
7970     }
7971 
7972     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
7973     // instruction, because the return type of these instructions is a vec2 of
7974     // the memory type, so it can be tied to the input operand.
7975     // This means these instructions always have a use, so we need to add a
7976     // special case to check if the atomic has only one extract_subreg use,
7977     // which itself has no uses.
7978     if ((Node->hasNUsesOfValue(1, 0) &&
7979          Node->use_begin()->isMachineOpcode() &&
7980          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
7981          !Node->use_begin()->hasAnyUseOfValue(0))) {
7982       unsigned Def = MI.getOperand(0).getReg();
7983 
7984       // Change this into a noret atomic.
7985       MI.setDesc(TII->get(NoRetAtomicOp));
7986       MI.RemoveOperand(0);
7987 
7988       // If we only remove the def operand from the atomic instruction, the
7989       // extract_subreg will be left with a use of a vreg without a def.
7990       // So we need to insert an implicit_def to avoid machine verifier
7991       // errors.
7992       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
7993               TII->get(AMDGPU::IMPLICIT_DEF), Def);
7994     }
7995     return;
7996   }
7997 }
7998 
7999 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
8000                               uint64_t Val) {
8001   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
8002   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
8003 }
8004 
8005 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
8006                                                 const SDLoc &DL,
8007                                                 SDValue Ptr) const {
8008   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8009 
8010   // Build the half of the subregister with the constants before building the
8011   // full 128-bit register. If we are building multiple resource descriptors,
8012   // this will allow CSEing of the 2-component register.
8013   const SDValue Ops0[] = {
8014     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
8015     buildSMovImm32(DAG, DL, 0),
8016     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
8017     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
8018     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
8019   };
8020 
8021   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
8022                                                 MVT::v2i32, Ops0), 0);
8023 
8024   // Combine the constants and the pointer.
8025   const SDValue Ops1[] = {
8026     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
8027     Ptr,
8028     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
8029     SubRegHi,
8030     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
8031   };
8032 
8033   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
8034 }
8035 
8036 /// Return a resource descriptor with the 'Add TID' bit enabled
8037 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
8038 ///        of the resource descriptor) to create an offset, which is added to
8039 ///        the resource pointer.
8040 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
8041                                            SDValue Ptr, uint32_t RsrcDword1,
8042                                            uint64_t RsrcDword2And3) const {
8043   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
8044   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
8045   if (RsrcDword1) {
8046     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
8047                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
8048                     0);
8049   }
8050 
8051   SDValue DataLo = buildSMovImm32(DAG, DL,
8052                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
8053   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
8054 
8055   const SDValue Ops[] = {
8056     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
8057     PtrLo,
8058     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
8059     PtrHi,
8060     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
8061     DataLo,
8062     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
8063     DataHi,
8064     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
8065   };
8066 
8067   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
8068 }
8069 
8070 //===----------------------------------------------------------------------===//
8071 //                         SI Inline Assembly Support
8072 //===----------------------------------------------------------------------===//
8073 
8074 std::pair<unsigned, const TargetRegisterClass *>
8075 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
8076                                                StringRef Constraint,
8077                                                MVT VT) const {
8078   const TargetRegisterClass *RC = nullptr;
8079   if (Constraint.size() == 1) {
8080     switch (Constraint[0]) {
8081     default:
8082       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8083     case 's':
8084     case 'r':
8085       switch (VT.getSizeInBits()) {
8086       default:
8087         return std::make_pair(0U, nullptr);
8088       case 32:
8089       case 16:
8090         RC = &AMDGPU::SReg_32_XM0RegClass;
8091         break;
8092       case 64:
8093         RC = &AMDGPU::SGPR_64RegClass;
8094         break;
8095       case 128:
8096         RC = &AMDGPU::SReg_128RegClass;
8097         break;
8098       case 256:
8099         RC = &AMDGPU::SReg_256RegClass;
8100         break;
8101       case 512:
8102         RC = &AMDGPU::SReg_512RegClass;
8103         break;
8104       }
8105       break;
8106     case 'v':
8107       switch (VT.getSizeInBits()) {
8108       default:
8109         return std::make_pair(0U, nullptr);
8110       case 32:
8111       case 16:
8112         RC = &AMDGPU::VGPR_32RegClass;
8113         break;
8114       case 64:
8115         RC = &AMDGPU::VReg_64RegClass;
8116         break;
8117       case 96:
8118         RC = &AMDGPU::VReg_96RegClass;
8119         break;
8120       case 128:
8121         RC = &AMDGPU::VReg_128RegClass;
8122         break;
8123       case 256:
8124         RC = &AMDGPU::VReg_256RegClass;
8125         break;
8126       case 512:
8127         RC = &AMDGPU::VReg_512RegClass;
8128         break;
8129       }
8130       break;
8131     }
8132     // We actually support i128, i16 and f16 as inline parameters
8133     // even if they are not reported as legal
8134     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
8135                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
8136       return std::make_pair(0U, RC);
8137   }
8138 
8139   if (Constraint.size() > 1) {
8140     if (Constraint[1] == 'v') {
8141       RC = &AMDGPU::VGPR_32RegClass;
8142     } else if (Constraint[1] == 's') {
8143       RC = &AMDGPU::SGPR_32RegClass;
8144     }
8145 
8146     if (RC) {
8147       uint32_t Idx;
8148       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
8149       if (!Failed && Idx < RC->getNumRegs())
8150         return std::make_pair(RC->getRegister(Idx), RC);
8151     }
8152   }
8153   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
8154 }
8155 
8156 SITargetLowering::ConstraintType
8157 SITargetLowering::getConstraintType(StringRef Constraint) const {
8158   if (Constraint.size() == 1) {
8159     switch (Constraint[0]) {
8160     default: break;
8161     case 's':
8162     case 'v':
8163       return C_RegisterClass;
8164     }
8165   }
8166   return TargetLowering::getConstraintType(Constraint);
8167 }
8168 
8169 // Figure out which registers should be reserved for stack access. Only after
8170 // the function is legalized do we know all of the non-spill stack objects or if
8171 // calls are present.
8172 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
8173   MachineRegisterInfo &MRI = MF.getRegInfo();
8174   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8175   const MachineFrameInfo &MFI = MF.getFrameInfo();
8176   const SISubtarget &ST = MF.getSubtarget<SISubtarget>();
8177   const SIRegisterInfo *TRI = ST.getRegisterInfo();
8178 
8179   if (Info->isEntryFunction()) {
8180     // Callable functions have fixed registers used for stack access.
8181     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
8182   }
8183 
8184   // We have to assume the SP is needed in case there are calls in the function
8185   // during lowering. Calls are only detected after the function is
8186   // lowered. We're about to reserve registers, so don't bother using it if we
8187   // aren't really going to use it.
8188   bool NeedSP = !Info->isEntryFunction() ||
8189     MFI.hasVarSizedObjects() ||
8190     MFI.hasCalls();
8191 
8192   if (NeedSP) {
8193     unsigned ReservedStackPtrOffsetReg = TRI->reservedStackPtrOffsetReg(MF);
8194     Info->setStackPtrOffsetReg(ReservedStackPtrOffsetReg);
8195 
8196     assert(Info->getStackPtrOffsetReg() != Info->getFrameOffsetReg());
8197     assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
8198                                Info->getStackPtrOffsetReg()));
8199     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
8200   }
8201 
8202   MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
8203   MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
8204   MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
8205                      Info->getScratchWaveOffsetReg());
8206 
8207   Info->limitOccupancy(MF);
8208 
8209   TargetLoweringBase::finalizeLowering(MF);
8210 }
8211 
8212 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
8213                                                      KnownBits &Known,
8214                                                      const APInt &DemandedElts,
8215                                                      const SelectionDAG &DAG,
8216                                                      unsigned Depth) const {
8217   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
8218                                                 DAG, Depth);
8219 
8220   if (getSubtarget()->enableHugePrivateBuffer())
8221     return;
8222 
8223   // Technically it may be possible to have a dispatch with a single workitem
8224   // that uses the full private memory size, but that's not really useful. We
8225   // can't use vaddr in MUBUF instructions if we don't know the address
8226   // calculation won't overflow, so assume the sign bit is never set.
8227   Known.Zero.setHighBits(AssumeFrameIndexHighZeroBits);
8228 }
8229 
8230 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
8231   FunctionLoweringInfo * FLI, DivergenceAnalysis * DA) const
8232 {
8233   switch (N->getOpcode()) {
8234     case ISD::Register:
8235     case ISD::CopyFromReg:
8236     {
8237       const RegisterSDNode *R = nullptr;
8238       if (N->getOpcode() == ISD::Register) {
8239         R = dyn_cast<RegisterSDNode>(N);
8240       }
8241       else {
8242         R = dyn_cast<RegisterSDNode>(N->getOperand(1));
8243       }
8244       if (R)
8245       {
8246         const MachineFunction * MF = FLI->MF;
8247         const SISubtarget &ST = MF->getSubtarget<SISubtarget>();
8248         const MachineRegisterInfo &MRI = MF->getRegInfo();
8249         const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
8250         unsigned Reg = R->getReg();
8251         if (TRI.isPhysicalRegister(Reg))
8252           return TRI.isVGPR(MRI, Reg);
8253 
8254         if (MRI.isLiveIn(Reg)) {
8255           // workitem.id.x workitem.id.y workitem.id.z
8256           // Any VGPR formal argument is also considered divergent
8257           if (TRI.isVGPR(MRI, Reg))
8258               return true;
8259           // Formal arguments of non-entry functions
8260           // are conservatively considered divergent
8261           else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
8262             return true;
8263         }
8264         return !DA || DA->isDivergent(FLI->getValueFromVirtualReg(Reg));
8265       }
8266     }
8267     break;
8268     case ISD::LOAD: {
8269       const LoadSDNode *L = dyn_cast<LoadSDNode>(N);
8270       if (L->getMemOperand()->getAddrSpace() ==
8271           Subtarget->getAMDGPUAS().PRIVATE_ADDRESS)
8272         return true;
8273     } break;
8274     case ISD::CALLSEQ_END:
8275     return true;
8276     break;
8277     case ISD::INTRINSIC_WO_CHAIN:
8278     {
8279 
8280     }
8281       return AMDGPU::isIntrinsicSourceOfDivergence(
8282       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
8283     case ISD::INTRINSIC_W_CHAIN:
8284       return AMDGPU::isIntrinsicSourceOfDivergence(
8285       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
8286     // In some cases intrinsics that are a source of divergence have been
8287     // lowered to AMDGPUISD so we also need to check those too.
8288     case AMDGPUISD::INTERP_MOV:
8289     case AMDGPUISD::INTERP_P1:
8290     case AMDGPUISD::INTERP_P2:
8291       return true;
8292   }
8293   return false;
8294 }
8295