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