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