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