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