OSDN Git Service

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