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