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