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<bool> DisableLoopAlignment(
97   "amdgpu-disable-loop-alignment",
98   cl::desc("Do not align and prefetch loops"),
99   cl::init(false));
100 
101 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
102   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
103   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
104     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
105       return AMDGPU::SGPR0 + Reg;
106     }
107   }
108   llvm_unreachable("Cannot allocate sgpr");
109 }
110 
111 SITargetLowering::SITargetLowering(const TargetMachine &TM,
112                                    const GCNSubtarget &STI)
113     : AMDGPUTargetLowering(TM, STI),
114       Subtarget(&STI) {
115   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
116   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
117 
118   addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
119   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
120 
121   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
122   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
123   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
124 
125   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
126   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
127 
128   addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
129   addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
130 
131   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
132   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
133 
134   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
135   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
136 
137   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
138   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
139 
140   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
141   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
142 
143   if (Subtarget->has16BitInsts()) {
144     addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
145     addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
146 
147     // Unless there are also VOP3P operations, not operations are really legal.
148     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
149     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
150     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
151     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
152   }
153 
154   computeRegisterProperties(Subtarget->getRegisterInfo());
155 
156   // We need to custom lower vector stores from local memory
157   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
163   setOperationAction(ISD::LOAD, MVT::i1, Custom);
164   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
165 
166   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
167   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
172   setOperationAction(ISD::STORE, MVT::i1, Custom);
173   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
174 
175   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
176   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
177   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
178   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
179   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
180   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
181   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
182   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
183   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
184   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
185 
186   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
187   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
188 
189   setOperationAction(ISD::SELECT, MVT::i1, Promote);
190   setOperationAction(ISD::SELECT, MVT::i64, Custom);
191   setOperationAction(ISD::SELECT, MVT::f64, Promote);
192   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
193 
194   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
195   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
196   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
197   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
198   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
199 
200   setOperationAction(ISD::SETCC, MVT::i1, Promote);
201   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
202   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
203   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
204 
205   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
206   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
207 
208   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
209   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
210   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
211   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
212   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
213   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
215 
216   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
217   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
218   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
219   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
220   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
221   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
222   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
223 
224   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
225   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
226   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
227   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
228   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
229   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
230 
231   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
232   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
233   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
234   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
235   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
236   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
237 
238   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
239   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
240   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
241   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
242   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
243   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
244 
245   setOperationAction(ISD::UADDO, MVT::i32, Legal);
246   setOperationAction(ISD::USUBO, MVT::i32, Legal);
247 
248   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
249   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
250 
251   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
252   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
253   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
254 
255 #if 0
256   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
257   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
258 #endif
259 
260   // We only support LOAD/STORE and vector manipulation ops for vectors
261   // with > 4 elements.
262   for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
263         MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, MVT::v32i32 }) {
264     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
265       switch (Op) {
266       case ISD::LOAD:
267       case ISD::STORE:
268       case ISD::BUILD_VECTOR:
269       case ISD::BITCAST:
270       case ISD::EXTRACT_VECTOR_ELT:
271       case ISD::INSERT_VECTOR_ELT:
272       case ISD::INSERT_SUBVECTOR:
273       case ISD::EXTRACT_SUBVECTOR:
274       case ISD::SCALAR_TO_VECTOR:
275         break;
276       case ISD::CONCAT_VECTORS:
277         setOperationAction(Op, VT, Custom);
278         break;
279       default:
280         setOperationAction(Op, VT, Expand);
281         break;
282       }
283     }
284   }
285 
286   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
287 
288   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
289   // is expanded to avoid having two separate loops in case the index is a VGPR.
290 
291   // Most operations are naturally 32-bit vector operations. We only support
292   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
293   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
294     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
295     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
296 
297     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
298     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
299 
300     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
301     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
302 
303     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
304     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
305   }
306 
307   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
308   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
309   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
310   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
311 
312   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
313   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
314 
315   // Avoid stack access for these.
316   // TODO: Generalize to more vector types.
317   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
318   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
319   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
320   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
321 
322   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
323   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
324   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
325   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
326   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
327 
328   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
329   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
330   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
331 
332   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
333   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
334   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
335   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
336 
337   // Deal with vec3 vector operations when widened to vec4.
338   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
339   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
340   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
341   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
342 
343   // Deal with vec5 vector operations when widened to vec8.
344   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
345   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
346   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
347   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
348 
349   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
350   // and output demarshalling
351   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
352   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
353 
354   // We can't return success/failure, only the old value,
355   // let LLVM add the comparison
356   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
357   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
358 
359   if (Subtarget->hasFlatAddressSpace()) {
360     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
361     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
362   }
363 
364   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
365   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
366 
367   // On SI this is s_memtime and s_memrealtime on VI.
368   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
369   setOperationAction(ISD::TRAP, MVT::Other, Custom);
370   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
371 
372   if (Subtarget->has16BitInsts()) {
373     setOperationAction(ISD::FLOG, MVT::f16, Custom);
374     setOperationAction(ISD::FEXP, MVT::f16, Custom);
375     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
376   }
377 
378   // v_mad_f32 does not support denormals according to some sources.
379   if (!Subtarget->hasFP32Denormals())
380     setOperationAction(ISD::FMAD, MVT::f32, Legal);
381 
382   if (!Subtarget->hasBFI()) {
383     // fcopysign can be done in a single instruction with BFI.
384     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
385     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
386   }
387 
388   if (!Subtarget->hasBCNT(32))
389     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
390 
391   if (!Subtarget->hasBCNT(64))
392     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
393 
394   if (Subtarget->hasFFBH())
395     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
396 
397   if (Subtarget->hasFFBL())
398     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
399 
400   // We only really have 32-bit BFE instructions (and 16-bit on VI).
401   //
402   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
403   // effort to match them now. We want this to be false for i64 cases when the
404   // extraction isn't restricted to the upper or lower half. Ideally we would
405   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
406   // span the midpoint are probably relatively rare, so don't worry about them
407   // for now.
408   if (Subtarget->hasBFE())
409     setHasExtractBitsInsn(true);
410 
411   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
412   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
413   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
414   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
415 
416 
417   // These are really only legal for ieee_mode functions. We should be avoiding
418   // them for functions that don't have ieee_mode enabled, so just say they are
419   // legal.
420   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
421   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
422   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
423   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
424 
425 
426   if (Subtarget->haveRoundOpsF64()) {
427     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
428     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
429     setOperationAction(ISD::FRINT, MVT::f64, Legal);
430   } else {
431     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
432     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
433     setOperationAction(ISD::FRINT, MVT::f64, Custom);
434     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
435   }
436 
437   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
438 
439   setOperationAction(ISD::FSIN, MVT::f32, Custom);
440   setOperationAction(ISD::FCOS, MVT::f32, Custom);
441   setOperationAction(ISD::FDIV, MVT::f32, Custom);
442   setOperationAction(ISD::FDIV, MVT::f64, Custom);
443 
444   if (Subtarget->has16BitInsts()) {
445     setOperationAction(ISD::Constant, MVT::i16, Legal);
446 
447     setOperationAction(ISD::SMIN, MVT::i16, Legal);
448     setOperationAction(ISD::SMAX, MVT::i16, Legal);
449 
450     setOperationAction(ISD::UMIN, MVT::i16, Legal);
451     setOperationAction(ISD::UMAX, MVT::i16, Legal);
452 
453     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
454     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
455 
456     setOperationAction(ISD::ROTR, MVT::i16, Promote);
457     setOperationAction(ISD::ROTL, MVT::i16, Promote);
458 
459     setOperationAction(ISD::SDIV, MVT::i16, Promote);
460     setOperationAction(ISD::UDIV, MVT::i16, Promote);
461     setOperationAction(ISD::SREM, MVT::i16, Promote);
462     setOperationAction(ISD::UREM, MVT::i16, Promote);
463 
464     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
465     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
466 
467     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
468     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
469     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
470     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
471     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
472 
473     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
474 
475     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
476 
477     setOperationAction(ISD::LOAD, MVT::i16, Custom);
478 
479     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
480 
481     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
482     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
483     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
484     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
485 
486     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
487     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
488     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
489     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
490 
491     // F16 - Constant Actions.
492     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
493 
494     // F16 - Load/Store Actions.
495     setOperationAction(ISD::LOAD, MVT::f16, Promote);
496     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
497     setOperationAction(ISD::STORE, MVT::f16, Promote);
498     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
499 
500     // F16 - VOP1 Actions.
501     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
502     setOperationAction(ISD::FCOS, MVT::f16, Promote);
503     setOperationAction(ISD::FSIN, MVT::f16, Promote);
504     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
505     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
506     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
507     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
508     setOperationAction(ISD::FROUND, MVT::f16, Custom);
509 
510     // F16 - VOP2 Actions.
511     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
512     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
513 
514     setOperationAction(ISD::FDIV, MVT::f16, Custom);
515 
516     // F16 - VOP3 Actions.
517     setOperationAction(ISD::FMA, MVT::f16, Legal);
518     if (!Subtarget->hasFP16Denormals() && STI.hasMadF16())
519       setOperationAction(ISD::FMAD, MVT::f16, Legal);
520 
521     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
522       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
523         switch (Op) {
524         case ISD::LOAD:
525         case ISD::STORE:
526         case ISD::BUILD_VECTOR:
527         case ISD::BITCAST:
528         case ISD::EXTRACT_VECTOR_ELT:
529         case ISD::INSERT_VECTOR_ELT:
530         case ISD::INSERT_SUBVECTOR:
531         case ISD::EXTRACT_SUBVECTOR:
532         case ISD::SCALAR_TO_VECTOR:
533           break;
534         case ISD::CONCAT_VECTORS:
535           setOperationAction(Op, VT, Custom);
536           break;
537         default:
538           setOperationAction(Op, VT, Expand);
539           break;
540         }
541       }
542     }
543 
544     // XXX - Do these do anything? Vector constants turn into build_vector.
545     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
546     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
547 
548     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
549     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
550 
551     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
552     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
553     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
554     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
555 
556     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
557     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
558     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
559     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
560 
561     setOperationAction(ISD::AND, MVT::v2i16, Promote);
562     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
563     setOperationAction(ISD::OR, MVT::v2i16, Promote);
564     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
565     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
566     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
567 
568     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
569     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
570     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
571     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
572 
573     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
574     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
575     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
576     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
577 
578     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
579     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
580     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
581     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
582 
583     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
584     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
585     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
586 
587     if (!Subtarget->hasVOP3PInsts()) {
588       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
589       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
590     }
591 
592     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
593     // This isn't really legal, but this avoids the legalizer unrolling it (and
594     // allows matching fneg (fabs x) patterns)
595     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
596 
597     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
598     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
599     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
600     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
601 
602     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
603     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
604 
605     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
606     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
607   }
608 
609   if (Subtarget->hasVOP3PInsts()) {
610     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
611     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
612     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
613     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
614     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
615     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
616     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
617     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
618     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
619     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
620 
621     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
622     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
623     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
624 
625     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
626     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
627 
628     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
629 
630     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
631     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
632 
633     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
634     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
635 
636     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
637     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
638     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
639     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
640     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
641     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
642 
643     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
644     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
645     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
646     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
647 
648     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
649     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
650 
651     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
652     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
653 
654     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
655     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
656     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
657 
658     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
659     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
660     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
661   }
662 
663   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
664   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
665 
666   if (Subtarget->has16BitInsts()) {
667     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
668     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
669     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
670     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
671   } else {
672     // Legalization hack.
673     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
674     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
675 
676     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
677     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
678   }
679 
680   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
681     setOperationAction(ISD::SELECT, VT, Custom);
682   }
683 
684   setTargetDAGCombine(ISD::ADD);
685   setTargetDAGCombine(ISD::ADDCARRY);
686   setTargetDAGCombine(ISD::SUB);
687   setTargetDAGCombine(ISD::SUBCARRY);
688   setTargetDAGCombine(ISD::FADD);
689   setTargetDAGCombine(ISD::FSUB);
690   setTargetDAGCombine(ISD::FMINNUM);
691   setTargetDAGCombine(ISD::FMAXNUM);
692   setTargetDAGCombine(ISD::FMINNUM_IEEE);
693   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
694   setTargetDAGCombine(ISD::FMA);
695   setTargetDAGCombine(ISD::SMIN);
696   setTargetDAGCombine(ISD::SMAX);
697   setTargetDAGCombine(ISD::UMIN);
698   setTargetDAGCombine(ISD::UMAX);
699   setTargetDAGCombine(ISD::SETCC);
700   setTargetDAGCombine(ISD::AND);
701   setTargetDAGCombine(ISD::OR);
702   setTargetDAGCombine(ISD::XOR);
703   setTargetDAGCombine(ISD::SINT_TO_FP);
704   setTargetDAGCombine(ISD::UINT_TO_FP);
705   setTargetDAGCombine(ISD::FCANONICALIZE);
706   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
707   setTargetDAGCombine(ISD::ZERO_EXTEND);
708   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
709   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
710   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
711 
712   // All memory operations. Some folding on the pointer operand is done to help
713   // matching the constant offsets in the addressing modes.
714   setTargetDAGCombine(ISD::LOAD);
715   setTargetDAGCombine(ISD::STORE);
716   setTargetDAGCombine(ISD::ATOMIC_LOAD);
717   setTargetDAGCombine(ISD::ATOMIC_STORE);
718   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
719   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
720   setTargetDAGCombine(ISD::ATOMIC_SWAP);
721   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
722   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
723   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
724   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
725   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
726   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
727   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
728   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
729   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
730   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
731   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
732 
733   setSchedulingPreference(Sched::RegPressure);
734 }
735 
736 const GCNSubtarget *SITargetLowering::getSubtarget() const {
737   return Subtarget;
738 }
739 
740 //===----------------------------------------------------------------------===//
741 // TargetLowering queries
742 //===----------------------------------------------------------------------===//
743 
744 // v_mad_mix* support a conversion from f16 to f32.
745 //
746 // There is only one special case when denormals are enabled we don't currently,
747 // where this is OK to use.
748 bool SITargetLowering::isFPExtFoldable(unsigned Opcode,
749                                            EVT DestVT, EVT SrcVT) const {
750   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
751           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
752          DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
753          SrcVT.getScalarType() == MVT::f16;
754 }
755 
756 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
757   // SI has some legal vector types, but no legal vector operations. Say no
758   // shuffles are legal in order to prefer scalarizing some vector operations.
759   return false;
760 }
761 
762 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
763                                                     CallingConv::ID CC,
764                                                     EVT VT) const {
765   // TODO: Consider splitting all arguments into 32-bit pieces.
766   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
767     EVT ScalarVT = VT.getScalarType();
768     unsigned Size = ScalarVT.getSizeInBits();
769     if (Size == 32)
770       return ScalarVT.getSimpleVT();
771 
772     if (Size == 64)
773       return MVT::i32;
774 
775     if (Size == 16 && Subtarget->has16BitInsts())
776       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
777   }
778 
779   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
780 }
781 
782 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
783                                                          CallingConv::ID CC,
784                                                          EVT VT) const {
785   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
786     unsigned NumElts = VT.getVectorNumElements();
787     EVT ScalarVT = VT.getScalarType();
788     unsigned Size = ScalarVT.getSizeInBits();
789 
790     if (Size == 32)
791       return NumElts;
792 
793     if (Size == 64)
794       return 2 * NumElts;
795 
796     if (Size == 16 && Subtarget->has16BitInsts())
797       return (VT.getVectorNumElements() + 1) / 2;
798   }
799 
800   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
801 }
802 
803 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
804   LLVMContext &Context, CallingConv::ID CC,
805   EVT VT, EVT &IntermediateVT,
806   unsigned &NumIntermediates, MVT &RegisterVT) const {
807   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
808     unsigned NumElts = VT.getVectorNumElements();
809     EVT ScalarVT = VT.getScalarType();
810     unsigned Size = ScalarVT.getSizeInBits();
811     if (Size == 32) {
812       RegisterVT = ScalarVT.getSimpleVT();
813       IntermediateVT = RegisterVT;
814       NumIntermediates = NumElts;
815       return NumIntermediates;
816     }
817 
818     if (Size == 64) {
819       RegisterVT = MVT::i32;
820       IntermediateVT = RegisterVT;
821       NumIntermediates = 2 * NumElts;
822       return NumIntermediates;
823     }
824 
825     // FIXME: We should fix the ABI to be the same on targets without 16-bit
826     // support, but unless we can properly handle 3-vectors, it will be still be
827     // inconsistent.
828     if (Size == 16 && Subtarget->has16BitInsts()) {
829       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
830       IntermediateVT = RegisterVT;
831       NumIntermediates = (NumElts + 1) / 2;
832       return NumIntermediates;
833     }
834   }
835 
836   return TargetLowering::getVectorTypeBreakdownForCallingConv(
837     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
838 }
839 
840 static MVT memVTFromAggregate(Type *Ty) {
841   // Only limited forms of aggregate type currently expected.
842   assert(Ty->isStructTy() && "Expected struct type");
843 
844 
845   Type *ElementType = nullptr;
846   unsigned NumElts;
847   if (Ty->getContainedType(0)->isVectorTy()) {
848     VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0));
849     ElementType = VecComponent->getElementType();
850     NumElts = VecComponent->getNumElements();
851   } else {
852     ElementType = Ty->getContainedType(0);
853     NumElts = 1;
854   }
855 
856   assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type");
857 
858   // Calculate the size of the memVT type from the aggregate
859   unsigned Pow2Elts = 0;
860   unsigned ElementSize;
861   switch (ElementType->getTypeID()) {
862     default:
863       llvm_unreachable("Unknown type!");
864     case Type::IntegerTyID:
865       ElementSize = cast<IntegerType>(ElementType)->getBitWidth();
866       break;
867     case Type::HalfTyID:
868       ElementSize = 16;
869       break;
870     case Type::FloatTyID:
871       ElementSize = 32;
872       break;
873   }
874   unsigned AdditionalElts = ElementSize == 16 ? 2 : 1;
875   Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts);
876 
877   return MVT::getVectorVT(MVT::getVT(ElementType, false),
878                           Pow2Elts);
879 }
880 
881 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
882                                           const CallInst &CI,
883                                           MachineFunction &MF,
884                                           unsigned IntrID) const {
885   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
886           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
887     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
888                                                   (Intrinsic::ID)IntrID);
889     if (Attr.hasFnAttribute(Attribute::ReadNone))
890       return false;
891 
892     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
893 
894     if (RsrcIntr->IsImage) {
895       Info.ptrVal = MFI->getImagePSV(
896         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
897         CI.getArgOperand(RsrcIntr->RsrcArg));
898       Info.align = 0;
899     } else {
900       Info.ptrVal = MFI->getBufferPSV(
901         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
902         CI.getArgOperand(RsrcIntr->RsrcArg));
903     }
904 
905     Info.flags = MachineMemOperand::MODereferenceable;
906     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
907       Info.opc = ISD::INTRINSIC_W_CHAIN;
908       Info.memVT = MVT::getVT(CI.getType(), true);
909       if (Info.memVT == MVT::Other) {
910         // Some intrinsics return an aggregate type - special case to work out
911         // the correct memVT
912         Info.memVT = memVTFromAggregate(CI.getType());
913       }
914       Info.flags |= MachineMemOperand::MOLoad;
915     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
916       Info.opc = ISD::INTRINSIC_VOID;
917       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
918       Info.flags |= MachineMemOperand::MOStore;
919     } else {
920       // Atomic
921       Info.opc = ISD::INTRINSIC_W_CHAIN;
922       Info.memVT = MVT::getVT(CI.getType());
923       Info.flags = MachineMemOperand::MOLoad |
924                    MachineMemOperand::MOStore |
925                    MachineMemOperand::MODereferenceable;
926 
927       // XXX - Should this be volatile without known ordering?
928       Info.flags |= MachineMemOperand::MOVolatile;
929     }
930     return true;
931   }
932 
933   switch (IntrID) {
934   case Intrinsic::amdgcn_atomic_inc:
935   case Intrinsic::amdgcn_atomic_dec:
936   case Intrinsic::amdgcn_ds_ordered_add:
937   case Intrinsic::amdgcn_ds_ordered_swap:
938   case Intrinsic::amdgcn_ds_fadd:
939   case Intrinsic::amdgcn_ds_fmin:
940   case Intrinsic::amdgcn_ds_fmax: {
941     Info.opc = ISD::INTRINSIC_W_CHAIN;
942     Info.memVT = MVT::getVT(CI.getType());
943     Info.ptrVal = CI.getOperand(0);
944     Info.align = 0;
945     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
946 
947     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
948     if (!Vol->isZero())
949       Info.flags |= MachineMemOperand::MOVolatile;
950 
951     return true;
952   }
953   case Intrinsic::amdgcn_ds_append:
954   case Intrinsic::amdgcn_ds_consume: {
955     Info.opc = ISD::INTRINSIC_W_CHAIN;
956     Info.memVT = MVT::getVT(CI.getType());
957     Info.ptrVal = CI.getOperand(0);
958     Info.align = 0;
959     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
960 
961     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
962     if (!Vol->isZero())
963       Info.flags |= MachineMemOperand::MOVolatile;
964 
965     return true;
966   }
967   case Intrinsic::amdgcn_ds_gws_init:
968   case Intrinsic::amdgcn_ds_gws_barrier:
969   case Intrinsic::amdgcn_ds_gws_sema_v:
970   case Intrinsic::amdgcn_ds_gws_sema_br:
971   case Intrinsic::amdgcn_ds_gws_sema_p:
972   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
973     Info.opc = ISD::INTRINSIC_VOID;
974 
975     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
976     Info.ptrVal =
977         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
978 
979     // This is an abstract access, but we need to specify a type and size.
980     Info.memVT = MVT::i32;
981     Info.size = 4;
982     Info.align = 4;
983 
984     Info.flags = MachineMemOperand::MOStore;
985     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
986       Info.flags = MachineMemOperand::MOLoad;
987     return true;
988   }
989   default:
990     return false;
991   }
992 }
993 
994 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
995                                             SmallVectorImpl<Value*> &Ops,
996                                             Type *&AccessTy) const {
997   switch (II->getIntrinsicID()) {
998   case Intrinsic::amdgcn_atomic_inc:
999   case Intrinsic::amdgcn_atomic_dec:
1000   case Intrinsic::amdgcn_ds_ordered_add:
1001   case Intrinsic::amdgcn_ds_ordered_swap:
1002   case Intrinsic::amdgcn_ds_fadd:
1003   case Intrinsic::amdgcn_ds_fmin:
1004   case Intrinsic::amdgcn_ds_fmax: {
1005     Value *Ptr = II->getArgOperand(0);
1006     AccessTy = II->getType();
1007     Ops.push_back(Ptr);
1008     return true;
1009   }
1010   default:
1011     return false;
1012   }
1013 }
1014 
1015 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1016   if (!Subtarget->hasFlatInstOffsets()) {
1017     // Flat instructions do not have offsets, and only have the register
1018     // address.
1019     return AM.BaseOffs == 0 && AM.Scale == 0;
1020   }
1021 
1022   // GFX9 added a 13-bit signed offset. When using regular flat instructions,
1023   // the sign bit is ignored and is treated as a 12-bit unsigned offset.
1024 
1025   // GFX10 shrinked signed offset to 12 bits. When using regular flat
1026   // instructions, the sign bit is also ignored and is treated as 11-bit
1027   // unsigned offset.
1028 
1029   if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
1030     return isUInt<11>(AM.BaseOffs) && AM.Scale == 0;
1031 
1032   // Just r + i
1033   return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
1034 }
1035 
1036 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1037   if (Subtarget->hasFlatGlobalInsts())
1038     return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
1039 
1040   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1041       // Assume the we will use FLAT for all global memory accesses
1042       // on VI.
1043       // FIXME: This assumption is currently wrong.  On VI we still use
1044       // MUBUF instructions for the r + i addressing mode.  As currently
1045       // implemented, the MUBUF instructions only work on buffer < 4GB.
1046       // It may be possible to support > 4GB buffers with MUBUF instructions,
1047       // by setting the stride value in the resource descriptor which would
1048       // increase the size limit to (stride * 4GB).  However, this is risky,
1049       // because it has never been validated.
1050     return isLegalFlatAddressingMode(AM);
1051   }
1052 
1053   return isLegalMUBUFAddressingMode(AM);
1054 }
1055 
1056 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1057   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1058   // additionally can do r + r + i with addr64. 32-bit has more addressing
1059   // mode options. Depending on the resource constant, it can also do
1060   // (i64 r0) + (i32 r1) * (i14 i).
1061   //
1062   // Private arrays end up using a scratch buffer most of the time, so also
1063   // assume those use MUBUF instructions. Scratch loads / stores are currently
1064   // implemented as mubuf instructions with offen bit set, so slightly
1065   // different than the normal addr64.
1066   if (!isUInt<12>(AM.BaseOffs))
1067     return false;
1068 
1069   // FIXME: Since we can split immediate into soffset and immediate offset,
1070   // would it make sense to allow any immediate?
1071 
1072   switch (AM.Scale) {
1073   case 0: // r + i or just i, depending on HasBaseReg.
1074     return true;
1075   case 1:
1076     return true; // We have r + r or r + i.
1077   case 2:
1078     if (AM.HasBaseReg) {
1079       // Reject 2 * r + r.
1080       return false;
1081     }
1082 
1083     // Allow 2 * r as r + r
1084     // Or  2 * r + i is allowed as r + r + i.
1085     return true;
1086   default: // Don't allow n * r
1087     return false;
1088   }
1089 }
1090 
1091 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1092                                              const AddrMode &AM, Type *Ty,
1093                                              unsigned AS, Instruction *I) const {
1094   // No global is ever allowed as a base.
1095   if (AM.BaseGV)
1096     return false;
1097 
1098   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1099     return isLegalGlobalAddressingMode(AM);
1100 
1101   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1102       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1103       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1104     // If the offset isn't a multiple of 4, it probably isn't going to be
1105     // correctly aligned.
1106     // FIXME: Can we get the real alignment here?
1107     if (AM.BaseOffs % 4 != 0)
1108       return isLegalMUBUFAddressingMode(AM);
1109 
1110     // There are no SMRD extloads, so if we have to do a small type access we
1111     // will use a MUBUF load.
1112     // FIXME?: We also need to do this if unaligned, but we don't know the
1113     // alignment here.
1114     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1115       return isLegalGlobalAddressingMode(AM);
1116 
1117     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1118       // SMRD instructions have an 8-bit, dword offset on SI.
1119       if (!isUInt<8>(AM.BaseOffs / 4))
1120         return false;
1121     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1122       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1123       // in 8-bits, it can use a smaller encoding.
1124       if (!isUInt<32>(AM.BaseOffs / 4))
1125         return false;
1126     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1127       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1128       if (!isUInt<20>(AM.BaseOffs))
1129         return false;
1130     } else
1131       llvm_unreachable("unhandled generation");
1132 
1133     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1134       return true;
1135 
1136     if (AM.Scale == 1 && AM.HasBaseReg)
1137       return true;
1138 
1139     return false;
1140 
1141   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1142     return isLegalMUBUFAddressingMode(AM);
1143   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1144              AS == AMDGPUAS::REGION_ADDRESS) {
1145     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1146     // field.
1147     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1148     // an 8-bit dword offset but we don't know the alignment here.
1149     if (!isUInt<16>(AM.BaseOffs))
1150       return false;
1151 
1152     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1153       return true;
1154 
1155     if (AM.Scale == 1 && AM.HasBaseReg)
1156       return true;
1157 
1158     return false;
1159   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1160              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1161     // For an unknown address space, this usually means that this is for some
1162     // reason being used for pure arithmetic, and not based on some addressing
1163     // computation. We don't have instructions that compute pointers with any
1164     // addressing modes, so treat them as having no offset like flat
1165     // instructions.
1166     return isLegalFlatAddressingMode(AM);
1167   } else {
1168     llvm_unreachable("unhandled address space");
1169   }
1170 }
1171 
1172 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1173                                         const SelectionDAG &DAG) const {
1174   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1175     return (MemVT.getSizeInBits() <= 4 * 32);
1176   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1177     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1178     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1179   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1180     return (MemVT.getSizeInBits() <= 2 * 32);
1181   }
1182   return true;
1183 }
1184 
1185 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1186     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1187     bool *IsFast) const {
1188   if (IsFast)
1189     *IsFast = false;
1190 
1191   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1192   // which isn't a simple VT.
1193   // Until MVT is extended to handle this, simply check for the size and
1194   // rely on the condition below: allow accesses if the size is a multiple of 4.
1195   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1196                            VT.getStoreSize() > 16)) {
1197     return false;
1198   }
1199 
1200   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1201       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1202     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1203     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1204     // with adjacent offsets.
1205     bool AlignedBy4 = (Align % 4 == 0);
1206     if (IsFast)
1207       *IsFast = AlignedBy4;
1208 
1209     return AlignedBy4;
1210   }
1211 
1212   // FIXME: We have to be conservative here and assume that flat operations
1213   // will access scratch.  If we had access to the IR function, then we
1214   // could determine if any private memory was used in the function.
1215   if (!Subtarget->hasUnalignedScratchAccess() &&
1216       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1217        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1218     bool AlignedBy4 = Align >= 4;
1219     if (IsFast)
1220       *IsFast = AlignedBy4;
1221 
1222     return AlignedBy4;
1223   }
1224 
1225   if (Subtarget->hasUnalignedBufferAccess()) {
1226     // If we have an uniform constant load, it still requires using a slow
1227     // buffer instruction if unaligned.
1228     if (IsFast) {
1229       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1230                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1231         (Align % 4 == 0) : true;
1232     }
1233 
1234     return true;
1235   }
1236 
1237   // Smaller than dword value must be aligned.
1238   if (VT.bitsLT(MVT::i32))
1239     return false;
1240 
1241   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1242   // byte-address are ignored, thus forcing Dword alignment.
1243   // This applies to private, global, and constant memory.
1244   if (IsFast)
1245     *IsFast = true;
1246 
1247   return VT.bitsGT(MVT::i32) && Align % 4 == 0;
1248 }
1249 
1250 EVT SITargetLowering::getOptimalMemOpType(
1251     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
1252     bool ZeroMemset, bool MemcpyStrSrc,
1253     const AttributeList &FuncAttributes) const {
1254   // FIXME: Should account for address space here.
1255 
1256   // The default fallback uses the private pointer size as a guess for a type to
1257   // use. Make sure we switch these to 64-bit accesses.
1258 
1259   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1260     return MVT::v4i32;
1261 
1262   if (Size >= 8 && DstAlign >= 4)
1263     return MVT::v2i32;
1264 
1265   // Use the default.
1266   return MVT::Other;
1267 }
1268 
1269 static bool isFlatGlobalAddrSpace(unsigned AS) {
1270   return AS == AMDGPUAS::GLOBAL_ADDRESS ||
1271          AS == AMDGPUAS::FLAT_ADDRESS ||
1272          AS == AMDGPUAS::CONSTANT_ADDRESS ||
1273          AS > AMDGPUAS::MAX_AMDGPU_ADDRESS;
1274 }
1275 
1276 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1277                                            unsigned DestAS) const {
1278   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1279 }
1280 
1281 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1282   const MemSDNode *MemNode = cast<MemSDNode>(N);
1283   const Value *Ptr = MemNode->getMemOperand()->getValue();
1284   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1285   return I && I->getMetadata("amdgpu.noclobber");
1286 }
1287 
1288 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1289                                            unsigned DestAS) const {
1290   // Flat -> private/local is a simple truncate.
1291   // Flat -> global is no-op
1292   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1293     return true;
1294 
1295   return isNoopAddrSpaceCast(SrcAS, DestAS);
1296 }
1297 
1298 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1299   const MemSDNode *MemNode = cast<MemSDNode>(N);
1300 
1301   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1302 }
1303 
1304 TargetLoweringBase::LegalizeTypeAction
1305 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1306   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1307     return TypeSplitVector;
1308 
1309   return TargetLoweringBase::getPreferredVectorAction(VT);
1310 }
1311 
1312 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1313                                                          Type *Ty) const {
1314   // FIXME: Could be smarter if called for vector constants.
1315   return true;
1316 }
1317 
1318 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1319   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1320     switch (Op) {
1321     case ISD::LOAD:
1322     case ISD::STORE:
1323 
1324     // These operations are done with 32-bit instructions anyway.
1325     case ISD::AND:
1326     case ISD::OR:
1327     case ISD::XOR:
1328     case ISD::SELECT:
1329       // TODO: Extensions?
1330       return true;
1331     default:
1332       return false;
1333     }
1334   }
1335 
1336   // SimplifySetCC uses this function to determine whether or not it should
1337   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1338   if (VT == MVT::i1 && Op == ISD::SETCC)
1339     return false;
1340 
1341   return TargetLowering::isTypeDesirableForOp(Op, VT);
1342 }
1343 
1344 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1345                                                    const SDLoc &SL,
1346                                                    SDValue Chain,
1347                                                    uint64_t Offset) const {
1348   const DataLayout &DL = DAG.getDataLayout();
1349   MachineFunction &MF = DAG.getMachineFunction();
1350   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1351 
1352   const ArgDescriptor *InputPtrReg;
1353   const TargetRegisterClass *RC;
1354 
1355   std::tie(InputPtrReg, RC)
1356     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1357 
1358   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1359   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1360   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1361     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1362 
1363   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1364 }
1365 
1366 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1367                                             const SDLoc &SL) const {
1368   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1369                                                FIRST_IMPLICIT);
1370   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1371 }
1372 
1373 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1374                                          const SDLoc &SL, SDValue Val,
1375                                          bool Signed,
1376                                          const ISD::InputArg *Arg) const {
1377   // First, if it is a widened vector, narrow it.
1378   if (VT.isVector() &&
1379       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1380     EVT NarrowedVT =
1381         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1382                          VT.getVectorNumElements());
1383     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1384                       DAG.getConstant(0, SL, MVT::i32));
1385   }
1386 
1387   // Then convert the vector elements or scalar value.
1388   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1389       VT.bitsLT(MemVT)) {
1390     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1391     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1392   }
1393 
1394   if (MemVT.isFloatingPoint())
1395     Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1396   else if (Signed)
1397     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1398   else
1399     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1400 
1401   return Val;
1402 }
1403 
1404 SDValue SITargetLowering::lowerKernargMemParameter(
1405   SelectionDAG &DAG, EVT VT, EVT MemVT,
1406   const SDLoc &SL, SDValue Chain,
1407   uint64_t Offset, unsigned Align, bool Signed,
1408   const ISD::InputArg *Arg) const {
1409   Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1410   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
1411   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1412 
1413   // Try to avoid using an extload by loading earlier than the argument address,
1414   // and extracting the relevant bits. The load should hopefully be merged with
1415   // the previous argument.
1416   if (MemVT.getStoreSize() < 4 && Align < 4) {
1417     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1418     int64_t AlignDownOffset = alignDown(Offset, 4);
1419     int64_t OffsetDiff = Offset - AlignDownOffset;
1420 
1421     EVT IntVT = MemVT.changeTypeToInteger();
1422 
1423     // TODO: If we passed in the base kernel offset we could have a better
1424     // alignment than 4, but we don't really need it.
1425     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1426     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1427                                MachineMemOperand::MODereferenceable |
1428                                MachineMemOperand::MOInvariant);
1429 
1430     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1431     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1432 
1433     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1434     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1435     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1436 
1437 
1438     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1439   }
1440 
1441   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1442   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1443                              MachineMemOperand::MODereferenceable |
1444                              MachineMemOperand::MOInvariant);
1445 
1446   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1447   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1448 }
1449 
1450 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1451                                               const SDLoc &SL, SDValue Chain,
1452                                               const ISD::InputArg &Arg) const {
1453   MachineFunction &MF = DAG.getMachineFunction();
1454   MachineFrameInfo &MFI = MF.getFrameInfo();
1455 
1456   if (Arg.Flags.isByVal()) {
1457     unsigned Size = Arg.Flags.getByValSize();
1458     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1459     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1460   }
1461 
1462   unsigned ArgOffset = VA.getLocMemOffset();
1463   unsigned ArgSize = VA.getValVT().getStoreSize();
1464 
1465   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1466 
1467   // Create load nodes to retrieve arguments from the stack.
1468   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1469   SDValue ArgValue;
1470 
1471   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1472   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1473   MVT MemVT = VA.getValVT();
1474 
1475   switch (VA.getLocInfo()) {
1476   default:
1477     break;
1478   case CCValAssign::BCvt:
1479     MemVT = VA.getLocVT();
1480     break;
1481   case CCValAssign::SExt:
1482     ExtType = ISD::SEXTLOAD;
1483     break;
1484   case CCValAssign::ZExt:
1485     ExtType = ISD::ZEXTLOAD;
1486     break;
1487   case CCValAssign::AExt:
1488     ExtType = ISD::EXTLOAD;
1489     break;
1490   }
1491 
1492   ArgValue = DAG.getExtLoad(
1493     ExtType, SL, VA.getLocVT(), Chain, FIN,
1494     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1495     MemVT);
1496   return ArgValue;
1497 }
1498 
1499 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1500   const SIMachineFunctionInfo &MFI,
1501   EVT VT,
1502   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1503   const ArgDescriptor *Reg;
1504   const TargetRegisterClass *RC;
1505 
1506   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1507   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1508 }
1509 
1510 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1511                                    CallingConv::ID CallConv,
1512                                    ArrayRef<ISD::InputArg> Ins,
1513                                    BitVector &Skipped,
1514                                    FunctionType *FType,
1515                                    SIMachineFunctionInfo *Info) {
1516   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1517     const ISD::InputArg *Arg = &Ins[I];
1518 
1519     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1520            "vector type argument should have been split");
1521 
1522     // First check if it's a PS input addr.
1523     if (CallConv == CallingConv::AMDGPU_PS &&
1524         !Arg->Flags.isInReg() && !Arg->Flags.isByVal() && PSInputNum <= 15) {
1525 
1526       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1527 
1528       // Inconveniently only the first part of the split is marked as isSplit,
1529       // so skip to the end. We only want to increment PSInputNum once for the
1530       // entire split argument.
1531       if (Arg->Flags.isSplit()) {
1532         while (!Arg->Flags.isSplitEnd()) {
1533           assert(!Arg->VT.isVector() &&
1534                  "unexpected vector split in ps argument type");
1535           if (!SkipArg)
1536             Splits.push_back(*Arg);
1537           Arg = &Ins[++I];
1538         }
1539       }
1540 
1541       if (SkipArg) {
1542         // We can safely skip PS inputs.
1543         Skipped.set(Arg->getOrigArgIndex());
1544         ++PSInputNum;
1545         continue;
1546       }
1547 
1548       Info->markPSInputAllocated(PSInputNum);
1549       if (Arg->Used)
1550         Info->markPSInputEnabled(PSInputNum);
1551 
1552       ++PSInputNum;
1553     }
1554 
1555     Splits.push_back(*Arg);
1556   }
1557 }
1558 
1559 // Allocate special inputs passed in VGPRs.
1560 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1561                                            MachineFunction &MF,
1562                                            const SIRegisterInfo &TRI,
1563                                            SIMachineFunctionInfo &Info) {
1564   if (Info.hasWorkItemIDX()) {
1565     unsigned Reg = AMDGPU::VGPR0;
1566     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1567 
1568     CCInfo.AllocateReg(Reg);
1569     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1570   }
1571 
1572   if (Info.hasWorkItemIDY()) {
1573     unsigned Reg = AMDGPU::VGPR1;
1574     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1575 
1576     CCInfo.AllocateReg(Reg);
1577     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1578   }
1579 
1580   if (Info.hasWorkItemIDZ()) {
1581     unsigned Reg = AMDGPU::VGPR2;
1582     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1583 
1584     CCInfo.AllocateReg(Reg);
1585     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1586   }
1587 }
1588 
1589 // Try to allocate a VGPR at the end of the argument list, or if no argument
1590 // VGPRs are left allocating a stack slot.
1591 // If \p Mask is is given it indicates bitfield position in the register.
1592 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1593 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1594                                          ArgDescriptor Arg = ArgDescriptor()) {
1595   if (Arg.isSet())
1596     return ArgDescriptor::createArg(Arg, Mask);
1597 
1598   ArrayRef<MCPhysReg> ArgVGPRs
1599     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1600   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1601   if (RegIdx == ArgVGPRs.size()) {
1602     // Spill to stack required.
1603     int64_t Offset = CCInfo.AllocateStack(4, 4);
1604 
1605     return ArgDescriptor::createStack(Offset, Mask);
1606   }
1607 
1608   unsigned Reg = ArgVGPRs[RegIdx];
1609   Reg = CCInfo.AllocateReg(Reg);
1610   assert(Reg != AMDGPU::NoRegister);
1611 
1612   MachineFunction &MF = CCInfo.getMachineFunction();
1613   MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1614   return ArgDescriptor::createRegister(Reg, Mask);
1615 }
1616 
1617 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1618                                              const TargetRegisterClass *RC,
1619                                              unsigned NumArgRegs) {
1620   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1621   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1622   if (RegIdx == ArgSGPRs.size())
1623     report_fatal_error("ran out of SGPRs for arguments");
1624 
1625   unsigned Reg = ArgSGPRs[RegIdx];
1626   Reg = CCInfo.AllocateReg(Reg);
1627   assert(Reg != AMDGPU::NoRegister);
1628 
1629   MachineFunction &MF = CCInfo.getMachineFunction();
1630   MF.addLiveIn(Reg, RC);
1631   return ArgDescriptor::createRegister(Reg);
1632 }
1633 
1634 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1635   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1636 }
1637 
1638 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1639   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1640 }
1641 
1642 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1643                                       MachineFunction &MF,
1644                                       const SIRegisterInfo &TRI,
1645                                       SIMachineFunctionInfo &Info) {
1646   const unsigned Mask = 0x3ff;
1647   ArgDescriptor Arg;
1648 
1649   if (Info.hasWorkItemIDX()) {
1650     Arg = allocateVGPR32Input(CCInfo, Mask);
1651     Info.setWorkItemIDX(Arg);
1652   }
1653 
1654   if (Info.hasWorkItemIDY()) {
1655     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1656     Info.setWorkItemIDY(Arg);
1657   }
1658 
1659   if (Info.hasWorkItemIDZ())
1660     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1661 }
1662 
1663 static void allocateSpecialInputSGPRs(CCState &CCInfo,
1664                                       MachineFunction &MF,
1665                                       const SIRegisterInfo &TRI,
1666                                       SIMachineFunctionInfo &Info) {
1667   auto &ArgInfo = Info.getArgInfo();
1668 
1669   // TODO: Unify handling with private memory pointers.
1670 
1671   if (Info.hasDispatchPtr())
1672     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1673 
1674   if (Info.hasQueuePtr())
1675     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1676 
1677   if (Info.hasKernargSegmentPtr())
1678     ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1679 
1680   if (Info.hasDispatchID())
1681     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1682 
1683   // flat_scratch_init is not applicable for non-kernel functions.
1684 
1685   if (Info.hasWorkGroupIDX())
1686     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1687 
1688   if (Info.hasWorkGroupIDY())
1689     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1690 
1691   if (Info.hasWorkGroupIDZ())
1692     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1693 
1694   if (Info.hasImplicitArgPtr())
1695     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1696 }
1697 
1698 // Allocate special inputs passed in user SGPRs.
1699 static void allocateHSAUserSGPRs(CCState &CCInfo,
1700                                  MachineFunction &MF,
1701                                  const SIRegisterInfo &TRI,
1702                                  SIMachineFunctionInfo &Info) {
1703   if (Info.hasImplicitBufferPtr()) {
1704     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1705     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1706     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1707   }
1708 
1709   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1710   if (Info.hasPrivateSegmentBuffer()) {
1711     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1712     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1713     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1714   }
1715 
1716   if (Info.hasDispatchPtr()) {
1717     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1718     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1719     CCInfo.AllocateReg(DispatchPtrReg);
1720   }
1721 
1722   if (Info.hasQueuePtr()) {
1723     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1724     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1725     CCInfo.AllocateReg(QueuePtrReg);
1726   }
1727 
1728   if (Info.hasKernargSegmentPtr()) {
1729     unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1730     MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1731     CCInfo.AllocateReg(InputPtrReg);
1732   }
1733 
1734   if (Info.hasDispatchID()) {
1735     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1736     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1737     CCInfo.AllocateReg(DispatchIDReg);
1738   }
1739 
1740   if (Info.hasFlatScratchInit()) {
1741     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1742     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1743     CCInfo.AllocateReg(FlatScratchInitReg);
1744   }
1745 
1746   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1747   // these from the dispatch pointer.
1748 }
1749 
1750 // Allocate special input registers that are initialized per-wave.
1751 static void allocateSystemSGPRs(CCState &CCInfo,
1752                                 MachineFunction &MF,
1753                                 SIMachineFunctionInfo &Info,
1754                                 CallingConv::ID CallConv,
1755                                 bool IsShader) {
1756   if (Info.hasWorkGroupIDX()) {
1757     unsigned Reg = Info.addWorkGroupIDX();
1758     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1759     CCInfo.AllocateReg(Reg);
1760   }
1761 
1762   if (Info.hasWorkGroupIDY()) {
1763     unsigned Reg = Info.addWorkGroupIDY();
1764     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1765     CCInfo.AllocateReg(Reg);
1766   }
1767 
1768   if (Info.hasWorkGroupIDZ()) {
1769     unsigned Reg = Info.addWorkGroupIDZ();
1770     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1771     CCInfo.AllocateReg(Reg);
1772   }
1773 
1774   if (Info.hasWorkGroupInfo()) {
1775     unsigned Reg = Info.addWorkGroupInfo();
1776     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1777     CCInfo.AllocateReg(Reg);
1778   }
1779 
1780   if (Info.hasPrivateSegmentWaveByteOffset()) {
1781     // Scratch wave offset passed in system SGPR.
1782     unsigned PrivateSegmentWaveByteOffsetReg;
1783 
1784     if (IsShader) {
1785       PrivateSegmentWaveByteOffsetReg =
1786         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1787 
1788       // This is true if the scratch wave byte offset doesn't have a fixed
1789       // location.
1790       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1791         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1792         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1793       }
1794     } else
1795       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1796 
1797     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1798     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1799   }
1800 }
1801 
1802 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1803                                      MachineFunction &MF,
1804                                      const SIRegisterInfo &TRI,
1805                                      SIMachineFunctionInfo &Info) {
1806   // Now that we've figured out where the scratch register inputs are, see if
1807   // should reserve the arguments and use them directly.
1808   MachineFrameInfo &MFI = MF.getFrameInfo();
1809   bool HasStackObjects = MFI.hasStackObjects();
1810   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1811 
1812   // Record that we know we have non-spill stack objects so we don't need to
1813   // check all stack objects later.
1814   if (HasStackObjects)
1815     Info.setHasNonSpillStackObjects(true);
1816 
1817   // Everything live out of a block is spilled with fast regalloc, so it's
1818   // almost certain that spilling will be required.
1819   if (TM.getOptLevel() == CodeGenOpt::None)
1820     HasStackObjects = true;
1821 
1822   // For now assume stack access is needed in any callee functions, so we need
1823   // the scratch registers to pass in.
1824   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1825 
1826   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1827     // If we have stack objects, we unquestionably need the private buffer
1828     // resource. For the Code Object V2 ABI, this will be the first 4 user
1829     // SGPR inputs. We can reserve those and use them directly.
1830 
1831     unsigned PrivateSegmentBufferReg =
1832         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1833     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1834   } else {
1835     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1836     // We tentatively reserve the last registers (skipping the last registers
1837     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1838     // we'll replace these with the ones immediately after those which were
1839     // really allocated. In the prologue copies will be inserted from the
1840     // argument to these reserved registers.
1841 
1842     // Without HSA, relocations are used for the scratch pointer and the
1843     // buffer resource setup is always inserted in the prologue. Scratch wave
1844     // offset is still in an input SGPR.
1845     Info.setScratchRSrcReg(ReservedBufferReg);
1846   }
1847 
1848   // hasFP should be accurate for kernels even before the frame is finalized.
1849   if (ST.getFrameLowering()->hasFP(MF)) {
1850     MachineRegisterInfo &MRI = MF.getRegInfo();
1851 
1852     // Try to use s32 as the SP, but move it if it would interfere with input
1853     // arguments. This won't work with calls though.
1854     //
1855     // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1856     // registers.
1857     if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1858       Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1859     } else {
1860       assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1861 
1862       if (MFI.hasCalls())
1863         report_fatal_error("call in graphics shader with too many input SGPRs");
1864 
1865       for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1866         if (!MRI.isLiveIn(Reg)) {
1867           Info.setStackPtrOffsetReg(Reg);
1868           break;
1869         }
1870       }
1871 
1872       if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1873         report_fatal_error("failed to find register for SP");
1874     }
1875 
1876     if (MFI.hasCalls()) {
1877       Info.setScratchWaveOffsetReg(AMDGPU::SGPR33);
1878       Info.setFrameOffsetReg(AMDGPU::SGPR33);
1879     } else {
1880       unsigned ReservedOffsetReg =
1881         TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1882       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1883       Info.setFrameOffsetReg(ReservedOffsetReg);
1884     }
1885   } else if (RequiresStackAccess) {
1886     assert(!MFI.hasCalls());
1887     // We know there are accesses and they will be done relative to SP, so just
1888     // pin it to the input.
1889     //
1890     // FIXME: Should not do this if inline asm is reading/writing these
1891     // registers.
1892     unsigned PreloadedSP = Info.getPreloadedReg(
1893         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1894 
1895     Info.setStackPtrOffsetReg(PreloadedSP);
1896     Info.setScratchWaveOffsetReg(PreloadedSP);
1897     Info.setFrameOffsetReg(PreloadedSP);
1898   } else {
1899     assert(!MFI.hasCalls());
1900 
1901     // There may not be stack access at all. There may still be spills, or
1902     // access of a constant pointer (in which cases an extra copy will be
1903     // emitted in the prolog).
1904     unsigned ReservedOffsetReg
1905       = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1906     Info.setStackPtrOffsetReg(ReservedOffsetReg);
1907     Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1908     Info.setFrameOffsetReg(ReservedOffsetReg);
1909   }
1910 }
1911 
1912 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1913   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1914   return !Info->isEntryFunction();
1915 }
1916 
1917 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1918 
1919 }
1920 
1921 void SITargetLowering::insertCopiesSplitCSR(
1922   MachineBasicBlock *Entry,
1923   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1924   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1925 
1926   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1927   if (!IStart)
1928     return;
1929 
1930   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1931   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1932   MachineBasicBlock::iterator MBBI = Entry->begin();
1933   for (const MCPhysReg *I = IStart; *I; ++I) {
1934     const TargetRegisterClass *RC = nullptr;
1935     if (AMDGPU::SReg_64RegClass.contains(*I))
1936       RC = &AMDGPU::SGPR_64RegClass;
1937     else if (AMDGPU::SReg_32RegClass.contains(*I))
1938       RC = &AMDGPU::SGPR_32RegClass;
1939     else
1940       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1941 
1942     unsigned NewVR = MRI->createVirtualRegister(RC);
1943     // Create copy from CSR to a virtual register.
1944     Entry->addLiveIn(*I);
1945     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1946       .addReg(*I);
1947 
1948     // Insert the copy-back instructions right before the terminator.
1949     for (auto *Exit : Exits)
1950       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1951               TII->get(TargetOpcode::COPY), *I)
1952         .addReg(NewVR);
1953   }
1954 }
1955 
1956 SDValue SITargetLowering::LowerFormalArguments(
1957     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1958     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1959     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1960   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1961 
1962   MachineFunction &MF = DAG.getMachineFunction();
1963   const Function &Fn = MF.getFunction();
1964   FunctionType *FType = MF.getFunction().getFunctionType();
1965   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1966 
1967   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1968     DiagnosticInfoUnsupported NoGraphicsHSA(
1969         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1970     DAG.getContext()->diagnose(NoGraphicsHSA);
1971     return DAG.getEntryNode();
1972   }
1973 
1974   SmallVector<ISD::InputArg, 16> Splits;
1975   SmallVector<CCValAssign, 16> ArgLocs;
1976   BitVector Skipped(Ins.size());
1977   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1978                  *DAG.getContext());
1979 
1980   bool IsShader = AMDGPU::isShader(CallConv);
1981   bool IsKernel = AMDGPU::isKernel(CallConv);
1982   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1983 
1984   if (IsShader) {
1985     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1986 
1987     // At least one interpolation mode must be enabled or else the GPU will
1988     // hang.
1989     //
1990     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1991     // set PSInputAddr, the user wants to enable some bits after the compilation
1992     // based on run-time states. Since we can't know what the final PSInputEna
1993     // will look like, so we shouldn't do anything here and the user should take
1994     // responsibility for the correct programming.
1995     //
1996     // Otherwise, the following restrictions apply:
1997     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1998     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1999     //   enabled too.
2000     if (CallConv == CallingConv::AMDGPU_PS) {
2001       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2002            ((Info->getPSInputAddr() & 0xF) == 0 &&
2003             Info->isPSInputAllocated(11))) {
2004         CCInfo.AllocateReg(AMDGPU::VGPR0);
2005         CCInfo.AllocateReg(AMDGPU::VGPR1);
2006         Info->markPSInputAllocated(0);
2007         Info->markPSInputEnabled(0);
2008       }
2009       if (Subtarget->isAmdPalOS()) {
2010         // For isAmdPalOS, the user does not enable some bits after compilation
2011         // based on run-time states; the register values being generated here are
2012         // the final ones set in hardware. Therefore we need to apply the
2013         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2014         // a bit is set in PSInputAddr but not PSInputEnable is where the
2015         // frontend set up an input arg for a particular interpolation mode, but
2016         // nothing uses that input arg. Really we should have an earlier pass
2017         // that removes such an arg.)
2018         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2019         if ((PsInputBits & 0x7F) == 0 ||
2020             ((PsInputBits & 0xF) == 0 &&
2021              (PsInputBits >> 11 & 1)))
2022           Info->markPSInputEnabled(
2023               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2024       }
2025     }
2026 
2027     assert(!Info->hasDispatchPtr() &&
2028            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2029            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2030            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2031            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2032            !Info->hasWorkItemIDZ());
2033   } else if (IsKernel) {
2034     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2035   } else {
2036     Splits.append(Ins.begin(), Ins.end());
2037   }
2038 
2039   if (IsEntryFunc) {
2040     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2041     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2042   }
2043 
2044   if (IsKernel) {
2045     analyzeFormalArgumentsCompute(CCInfo, Ins);
2046   } else {
2047     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2048     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2049   }
2050 
2051   SmallVector<SDValue, 16> Chains;
2052 
2053   // FIXME: This is the minimum kernel argument alignment. We should improve
2054   // this to the maximum alignment of the arguments.
2055   //
2056   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2057   // kern arg offset.
2058   const unsigned KernelArgBaseAlign = 16;
2059 
2060    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2061     const ISD::InputArg &Arg = Ins[i];
2062     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2063       InVals.push_back(DAG.getUNDEF(Arg.VT));
2064       continue;
2065     }
2066 
2067     CCValAssign &VA = ArgLocs[ArgIdx++];
2068     MVT VT = VA.getLocVT();
2069 
2070     if (IsEntryFunc && VA.isMemLoc()) {
2071       VT = Ins[i].VT;
2072       EVT MemVT = VA.getLocVT();
2073 
2074       const uint64_t Offset = VA.getLocMemOffset();
2075       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2076 
2077       SDValue Arg = lowerKernargMemParameter(
2078         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2079       Chains.push_back(Arg.getValue(1));
2080 
2081       auto *ParamTy =
2082         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2083       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2084           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2085                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2086         // On SI local pointers are just offsets into LDS, so they are always
2087         // less than 16-bits.  On CI and newer they could potentially be
2088         // real pointers, so we can't guarantee their size.
2089         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2090                           DAG.getValueType(MVT::i16));
2091       }
2092 
2093       InVals.push_back(Arg);
2094       continue;
2095     } else if (!IsEntryFunc && VA.isMemLoc()) {
2096       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2097       InVals.push_back(Val);
2098       if (!Arg.Flags.isByVal())
2099         Chains.push_back(Val.getValue(1));
2100       continue;
2101     }
2102 
2103     assert(VA.isRegLoc() && "Parameter must be in a register!");
2104 
2105     unsigned Reg = VA.getLocReg();
2106     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2107     EVT ValVT = VA.getValVT();
2108 
2109     Reg = MF.addLiveIn(Reg, RC);
2110     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2111 
2112     if (Arg.Flags.isSRet()) {
2113       // The return object should be reasonably addressable.
2114 
2115       // FIXME: This helps when the return is a real sret. If it is a
2116       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2117       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2118       unsigned NumBits
2119         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2120       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2121         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2122     }
2123 
2124     // If this is an 8 or 16-bit value, it is really passed promoted
2125     // to 32 bits. Insert an assert[sz]ext to capture this, then
2126     // truncate to the right size.
2127     switch (VA.getLocInfo()) {
2128     case CCValAssign::Full:
2129       break;
2130     case CCValAssign::BCvt:
2131       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2132       break;
2133     case CCValAssign::SExt:
2134       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2135                         DAG.getValueType(ValVT));
2136       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2137       break;
2138     case CCValAssign::ZExt:
2139       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2140                         DAG.getValueType(ValVT));
2141       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2142       break;
2143     case CCValAssign::AExt:
2144       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2145       break;
2146     default:
2147       llvm_unreachable("Unknown loc info!");
2148     }
2149 
2150     InVals.push_back(Val);
2151   }
2152 
2153   if (!IsEntryFunc) {
2154     // Special inputs come after user arguments.
2155     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2156   }
2157 
2158   // Start adding system SGPRs.
2159   if (IsEntryFunc) {
2160     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2161   } else {
2162     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2163     CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2164     CCInfo.AllocateReg(Info->getFrameOffsetReg());
2165     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2166   }
2167 
2168   auto &ArgUsageInfo =
2169     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2170   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2171 
2172   unsigned StackArgSize = CCInfo.getNextStackOffset();
2173   Info->setBytesInStackArgArea(StackArgSize);
2174 
2175   return Chains.empty() ? Chain :
2176     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2177 }
2178 
2179 // TODO: If return values can't fit in registers, we should return as many as
2180 // possible in registers before passing on stack.
2181 bool SITargetLowering::CanLowerReturn(
2182   CallingConv::ID CallConv,
2183   MachineFunction &MF, bool IsVarArg,
2184   const SmallVectorImpl<ISD::OutputArg> &Outs,
2185   LLVMContext &Context) const {
2186   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2187   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2188   // for shaders. Vector types should be explicitly handled by CC.
2189   if (AMDGPU::isEntryFunctionCC(CallConv))
2190     return true;
2191 
2192   SmallVector<CCValAssign, 16> RVLocs;
2193   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2194   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2195 }
2196 
2197 SDValue
2198 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2199                               bool isVarArg,
2200                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2201                               const SmallVectorImpl<SDValue> &OutVals,
2202                               const SDLoc &DL, SelectionDAG &DAG) const {
2203   MachineFunction &MF = DAG.getMachineFunction();
2204   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2205 
2206   if (AMDGPU::isKernel(CallConv)) {
2207     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2208                                              OutVals, DL, DAG);
2209   }
2210 
2211   bool IsShader = AMDGPU::isShader(CallConv);
2212 
2213   Info->setIfReturnsVoid(Outs.empty());
2214   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2215 
2216   // CCValAssign - represent the assignment of the return value to a location.
2217   SmallVector<CCValAssign, 48> RVLocs;
2218   SmallVector<ISD::OutputArg, 48> Splits;
2219 
2220   // CCState - Info about the registers and stack slots.
2221   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2222                  *DAG.getContext());
2223 
2224   // Analyze outgoing return values.
2225   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2226 
2227   SDValue Flag;
2228   SmallVector<SDValue, 48> RetOps;
2229   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2230 
2231   // Add return address for callable functions.
2232   if (!Info->isEntryFunction()) {
2233     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2234     SDValue ReturnAddrReg = CreateLiveInRegister(
2235       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2236 
2237     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2238         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2239         MVT::i64);
2240     Chain =
2241         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2242     Flag = Chain.getValue(1);
2243     RetOps.push_back(ReturnAddrVirtualReg);
2244   }
2245 
2246   // Copy the result values into the output registers.
2247   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2248        ++I, ++RealRVLocIdx) {
2249     CCValAssign &VA = RVLocs[I];
2250     assert(VA.isRegLoc() && "Can only return in registers!");
2251     // TODO: Partially return in registers if return values don't fit.
2252     SDValue Arg = OutVals[RealRVLocIdx];
2253 
2254     // Copied from other backends.
2255     switch (VA.getLocInfo()) {
2256     case CCValAssign::Full:
2257       break;
2258     case CCValAssign::BCvt:
2259       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2260       break;
2261     case CCValAssign::SExt:
2262       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2263       break;
2264     case CCValAssign::ZExt:
2265       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2266       break;
2267     case CCValAssign::AExt:
2268       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2269       break;
2270     default:
2271       llvm_unreachable("Unknown loc info!");
2272     }
2273 
2274     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2275     Flag = Chain.getValue(1);
2276     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2277   }
2278 
2279   // FIXME: Does sret work properly?
2280   if (!Info->isEntryFunction()) {
2281     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2282     const MCPhysReg *I =
2283       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2284     if (I) {
2285       for (; *I; ++I) {
2286         if (AMDGPU::SReg_64RegClass.contains(*I))
2287           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2288         else if (AMDGPU::SReg_32RegClass.contains(*I))
2289           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2290         else
2291           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2292       }
2293     }
2294   }
2295 
2296   // Update chain and glue.
2297   RetOps[0] = Chain;
2298   if (Flag.getNode())
2299     RetOps.push_back(Flag);
2300 
2301   unsigned Opc = AMDGPUISD::ENDPGM;
2302   if (!IsWaveEnd)
2303     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2304   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2305 }
2306 
2307 SDValue SITargetLowering::LowerCallResult(
2308     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2309     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2310     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2311     SDValue ThisVal) const {
2312   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2313 
2314   // Assign locations to each value returned by this call.
2315   SmallVector<CCValAssign, 16> RVLocs;
2316   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2317                  *DAG.getContext());
2318   CCInfo.AnalyzeCallResult(Ins, RetCC);
2319 
2320   // Copy all of the result registers out of their specified physreg.
2321   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2322     CCValAssign VA = RVLocs[i];
2323     SDValue Val;
2324 
2325     if (VA.isRegLoc()) {
2326       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2327       Chain = Val.getValue(1);
2328       InFlag = Val.getValue(2);
2329     } else if (VA.isMemLoc()) {
2330       report_fatal_error("TODO: return values in memory");
2331     } else
2332       llvm_unreachable("unknown argument location type");
2333 
2334     switch (VA.getLocInfo()) {
2335     case CCValAssign::Full:
2336       break;
2337     case CCValAssign::BCvt:
2338       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2339       break;
2340     case CCValAssign::ZExt:
2341       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2342                         DAG.getValueType(VA.getValVT()));
2343       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2344       break;
2345     case CCValAssign::SExt:
2346       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2347                         DAG.getValueType(VA.getValVT()));
2348       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2349       break;
2350     case CCValAssign::AExt:
2351       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2352       break;
2353     default:
2354       llvm_unreachable("Unknown loc info!");
2355     }
2356 
2357     InVals.push_back(Val);
2358   }
2359 
2360   return Chain;
2361 }
2362 
2363 // Add code to pass special inputs required depending on used features separate
2364 // from the explicit user arguments present in the IR.
2365 void SITargetLowering::passSpecialInputs(
2366     CallLoweringInfo &CLI,
2367     CCState &CCInfo,
2368     const SIMachineFunctionInfo &Info,
2369     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2370     SmallVectorImpl<SDValue> &MemOpChains,
2371     SDValue Chain) const {
2372   // If we don't have a call site, this was a call inserted by
2373   // legalization. These can never use special inputs.
2374   if (!CLI.CS)
2375     return;
2376 
2377   const Function *CalleeFunc = CLI.CS.getCalledFunction();
2378   assert(CalleeFunc);
2379 
2380   SelectionDAG &DAG = CLI.DAG;
2381   const SDLoc &DL = CLI.DL;
2382 
2383   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2384 
2385   auto &ArgUsageInfo =
2386     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2387   const AMDGPUFunctionArgInfo &CalleeArgInfo
2388     = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2389 
2390   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2391 
2392   // TODO: Unify with private memory register handling. This is complicated by
2393   // the fact that at least in kernels, the input argument is not necessarily
2394   // in the same location as the input.
2395   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2396     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2397     AMDGPUFunctionArgInfo::QUEUE_PTR,
2398     AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2399     AMDGPUFunctionArgInfo::DISPATCH_ID,
2400     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2401     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2402     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2403     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2404   };
2405 
2406   for (auto InputID : InputRegs) {
2407     const ArgDescriptor *OutgoingArg;
2408     const TargetRegisterClass *ArgRC;
2409 
2410     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2411     if (!OutgoingArg)
2412       continue;
2413 
2414     const ArgDescriptor *IncomingArg;
2415     const TargetRegisterClass *IncomingArgRC;
2416     std::tie(IncomingArg, IncomingArgRC)
2417       = CallerArgInfo.getPreloadedValue(InputID);
2418     assert(IncomingArgRC == ArgRC);
2419 
2420     // All special arguments are ints for now.
2421     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2422     SDValue InputReg;
2423 
2424     if (IncomingArg) {
2425       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2426     } else {
2427       // The implicit arg ptr is special because it doesn't have a corresponding
2428       // input for kernels, and is computed from the kernarg segment pointer.
2429       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2430       InputReg = getImplicitArgPtr(DAG, DL);
2431     }
2432 
2433     if (OutgoingArg->isRegister()) {
2434       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2435     } else {
2436       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2437       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2438                                               SpecialArgOffset);
2439       MemOpChains.push_back(ArgStore);
2440     }
2441   }
2442 
2443   // Pack workitem IDs into a single register or pass it as is if already
2444   // packed.
2445   const ArgDescriptor *OutgoingArg;
2446   const TargetRegisterClass *ArgRC;
2447 
2448   std::tie(OutgoingArg, ArgRC) =
2449     CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2450   if (!OutgoingArg)
2451     std::tie(OutgoingArg, ArgRC) =
2452       CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2453   if (!OutgoingArg)
2454     std::tie(OutgoingArg, ArgRC) =
2455       CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2456   if (!OutgoingArg)
2457     return;
2458 
2459   const ArgDescriptor *IncomingArgX
2460     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2461   const ArgDescriptor *IncomingArgY
2462     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2463   const ArgDescriptor *IncomingArgZ
2464     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2465 
2466   SDValue InputReg;
2467   SDLoc SL;
2468 
2469   // If incoming ids are not packed we need to pack them.
2470   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX)
2471     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2472 
2473   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) {
2474     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2475     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2476                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2477     InputReg = InputReg.getNode() ?
2478                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2479   }
2480 
2481   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) {
2482     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2483     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2484                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2485     InputReg = InputReg.getNode() ?
2486                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2487   }
2488 
2489   if (!InputReg.getNode()) {
2490     // Workitem ids are already packed, any of present incoming arguments
2491     // will carry all required fields.
2492     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2493       IncomingArgX ? *IncomingArgX :
2494       IncomingArgY ? *IncomingArgY :
2495                      *IncomingArgZ, ~0u);
2496     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2497   }
2498 
2499   if (OutgoingArg->isRegister()) {
2500     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2501   } else {
2502     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2503     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2504                                             SpecialArgOffset);
2505     MemOpChains.push_back(ArgStore);
2506   }
2507 }
2508 
2509 static bool canGuaranteeTCO(CallingConv::ID CC) {
2510   return CC == CallingConv::Fast;
2511 }
2512 
2513 /// Return true if we might ever do TCO for calls with this calling convention.
2514 static bool mayTailCallThisCC(CallingConv::ID CC) {
2515   switch (CC) {
2516   case CallingConv::C:
2517     return true;
2518   default:
2519     return canGuaranteeTCO(CC);
2520   }
2521 }
2522 
2523 bool SITargetLowering::isEligibleForTailCallOptimization(
2524     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2525     const SmallVectorImpl<ISD::OutputArg> &Outs,
2526     const SmallVectorImpl<SDValue> &OutVals,
2527     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2528   if (!mayTailCallThisCC(CalleeCC))
2529     return false;
2530 
2531   MachineFunction &MF = DAG.getMachineFunction();
2532   const Function &CallerF = MF.getFunction();
2533   CallingConv::ID CallerCC = CallerF.getCallingConv();
2534   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2535   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2536 
2537   // Kernels aren't callable, and don't have a live in return address so it
2538   // doesn't make sense to do a tail call with entry functions.
2539   if (!CallerPreserved)
2540     return false;
2541 
2542   bool CCMatch = CallerCC == CalleeCC;
2543 
2544   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2545     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2546       return true;
2547     return false;
2548   }
2549 
2550   // TODO: Can we handle var args?
2551   if (IsVarArg)
2552     return false;
2553 
2554   for (const Argument &Arg : CallerF.args()) {
2555     if (Arg.hasByValAttr())
2556       return false;
2557   }
2558 
2559   LLVMContext &Ctx = *DAG.getContext();
2560 
2561   // Check that the call results are passed in the same way.
2562   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2563                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2564                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2565     return false;
2566 
2567   // The callee has to preserve all registers the caller needs to preserve.
2568   if (!CCMatch) {
2569     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2570     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2571       return false;
2572   }
2573 
2574   // Nothing more to check if the callee is taking no arguments.
2575   if (Outs.empty())
2576     return true;
2577 
2578   SmallVector<CCValAssign, 16> ArgLocs;
2579   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2580 
2581   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2582 
2583   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2584   // If the stack arguments for this call do not fit into our own save area then
2585   // the call cannot be made tail.
2586   // TODO: Is this really necessary?
2587   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2588     return false;
2589 
2590   const MachineRegisterInfo &MRI = MF.getRegInfo();
2591   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2592 }
2593 
2594 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2595   if (!CI->isTailCall())
2596     return false;
2597 
2598   const Function *ParentFn = CI->getParent()->getParent();
2599   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2600     return false;
2601 
2602   auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2603   return (Attr.getValueAsString() != "true");
2604 }
2605 
2606 // The wave scratch offset register is used as the global base pointer.
2607 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2608                                     SmallVectorImpl<SDValue> &InVals) const {
2609   SelectionDAG &DAG = CLI.DAG;
2610   const SDLoc &DL = CLI.DL;
2611   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2612   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2613   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2614   SDValue Chain = CLI.Chain;
2615   SDValue Callee = CLI.Callee;
2616   bool &IsTailCall = CLI.IsTailCall;
2617   CallingConv::ID CallConv = CLI.CallConv;
2618   bool IsVarArg = CLI.IsVarArg;
2619   bool IsSibCall = false;
2620   bool IsThisReturn = false;
2621   MachineFunction &MF = DAG.getMachineFunction();
2622 
2623   if (IsVarArg) {
2624     return lowerUnhandledCall(CLI, InVals,
2625                               "unsupported call to variadic function ");
2626   }
2627 
2628   if (!CLI.CS.getInstruction())
2629     report_fatal_error("unsupported libcall legalization");
2630 
2631   if (!CLI.CS.getCalledFunction()) {
2632     return lowerUnhandledCall(CLI, InVals,
2633                               "unsupported indirect call to function ");
2634   }
2635 
2636   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2637     return lowerUnhandledCall(CLI, InVals,
2638                               "unsupported required tail call to function ");
2639   }
2640 
2641   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2642     // Note the issue is with the CC of the calling function, not of the call
2643     // itself.
2644     return lowerUnhandledCall(CLI, InVals,
2645                           "unsupported call from graphics shader of function ");
2646   }
2647 
2648   if (IsTailCall) {
2649     IsTailCall = isEligibleForTailCallOptimization(
2650       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2651     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2652       report_fatal_error("failed to perform tail call elimination on a call "
2653                          "site marked musttail");
2654     }
2655 
2656     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2657 
2658     // A sibling call is one where we're under the usual C ABI and not planning
2659     // to change that but can still do a tail call:
2660     if (!TailCallOpt && IsTailCall)
2661       IsSibCall = true;
2662 
2663     if (IsTailCall)
2664       ++NumTailCalls;
2665   }
2666 
2667   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2668 
2669   // Analyze operands of the call, assigning locations to each operand.
2670   SmallVector<CCValAssign, 16> ArgLocs;
2671   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2672   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2673 
2674   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2675 
2676   // Get a count of how many bytes are to be pushed on the stack.
2677   unsigned NumBytes = CCInfo.getNextStackOffset();
2678 
2679   if (IsSibCall) {
2680     // Since we're not changing the ABI to make this a tail call, the memory
2681     // operands are already available in the caller's incoming argument space.
2682     NumBytes = 0;
2683   }
2684 
2685   // FPDiff is the byte offset of the call's argument area from the callee's.
2686   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2687   // by this amount for a tail call. In a sibling call it must be 0 because the
2688   // caller will deallocate the entire stack and the callee still expects its
2689   // arguments to begin at SP+0. Completely unused for non-tail calls.
2690   int32_t FPDiff = 0;
2691   MachineFrameInfo &MFI = MF.getFrameInfo();
2692   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2693 
2694   // Adjust the stack pointer for the new arguments...
2695   // These operations are automatically eliminated by the prolog/epilog pass
2696   if (!IsSibCall) {
2697     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2698 
2699     SmallVector<SDValue, 4> CopyFromChains;
2700 
2701     // In the HSA case, this should be an identity copy.
2702     SDValue ScratchRSrcReg
2703       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2704     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2705     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2706     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2707   }
2708 
2709   SmallVector<SDValue, 8> MemOpChains;
2710   MVT PtrVT = MVT::i32;
2711 
2712   // Walk the register/memloc assignments, inserting copies/loads.
2713   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2714        ++i, ++realArgIdx) {
2715     CCValAssign &VA = ArgLocs[i];
2716     SDValue Arg = OutVals[realArgIdx];
2717 
2718     // Promote the value if needed.
2719     switch (VA.getLocInfo()) {
2720     case CCValAssign::Full:
2721       break;
2722     case CCValAssign::BCvt:
2723       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2724       break;
2725     case CCValAssign::ZExt:
2726       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2727       break;
2728     case CCValAssign::SExt:
2729       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2730       break;
2731     case CCValAssign::AExt:
2732       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2733       break;
2734     case CCValAssign::FPExt:
2735       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2736       break;
2737     default:
2738       llvm_unreachable("Unknown loc info!");
2739     }
2740 
2741     if (VA.isRegLoc()) {
2742       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2743     } else {
2744       assert(VA.isMemLoc());
2745 
2746       SDValue DstAddr;
2747       MachinePointerInfo DstInfo;
2748 
2749       unsigned LocMemOffset = VA.getLocMemOffset();
2750       int32_t Offset = LocMemOffset;
2751 
2752       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2753       unsigned Align = 0;
2754 
2755       if (IsTailCall) {
2756         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2757         unsigned OpSize = Flags.isByVal() ?
2758           Flags.getByValSize() : VA.getValVT().getStoreSize();
2759 
2760         // FIXME: We can have better than the minimum byval required alignment.
2761         Align = Flags.isByVal() ? Flags.getByValAlign() :
2762           MinAlign(Subtarget->getStackAlignment(), Offset);
2763 
2764         Offset = Offset + FPDiff;
2765         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2766 
2767         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2768         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2769 
2770         // Make sure any stack arguments overlapping with where we're storing
2771         // are loaded before this eventual operation. Otherwise they'll be
2772         // clobbered.
2773 
2774         // FIXME: Why is this really necessary? This seems to just result in a
2775         // lot of code to copy the stack and write them back to the same
2776         // locations, which are supposed to be immutable?
2777         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2778       } else {
2779         DstAddr = PtrOff;
2780         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2781         Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset);
2782       }
2783 
2784       if (Outs[i].Flags.isByVal()) {
2785         SDValue SizeNode =
2786             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2787         SDValue Cpy = DAG.getMemcpy(
2788             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2789             /*isVol = */ false, /*AlwaysInline = */ true,
2790             /*isTailCall = */ false, DstInfo,
2791             MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2792                 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS))));
2793 
2794         MemOpChains.push_back(Cpy);
2795       } else {
2796         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align);
2797         MemOpChains.push_back(Store);
2798       }
2799     }
2800   }
2801 
2802   // Copy special input registers after user input arguments.
2803   passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2804 
2805   if (!MemOpChains.empty())
2806     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2807 
2808   // Build a sequence of copy-to-reg nodes chained together with token chain
2809   // and flag operands which copy the outgoing args into the appropriate regs.
2810   SDValue InFlag;
2811   for (auto &RegToPass : RegsToPass) {
2812     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2813                              RegToPass.second, InFlag);
2814     InFlag = Chain.getValue(1);
2815   }
2816 
2817 
2818   SDValue PhysReturnAddrReg;
2819   if (IsTailCall) {
2820     // Since the return is being combined with the call, we need to pass on the
2821     // return address.
2822 
2823     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2824     SDValue ReturnAddrReg = CreateLiveInRegister(
2825       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2826 
2827     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2828                                         MVT::i64);
2829     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2830     InFlag = Chain.getValue(1);
2831   }
2832 
2833   // We don't usually want to end the call-sequence here because we would tidy
2834   // the frame up *after* the call, however in the ABI-changing tail-call case
2835   // we've carefully laid out the parameters so that when sp is reset they'll be
2836   // in the correct location.
2837   if (IsTailCall && !IsSibCall) {
2838     Chain = DAG.getCALLSEQ_END(Chain,
2839                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2840                                DAG.getTargetConstant(0, DL, MVT::i32),
2841                                InFlag, DL);
2842     InFlag = Chain.getValue(1);
2843   }
2844 
2845   std::vector<SDValue> Ops;
2846   Ops.push_back(Chain);
2847   Ops.push_back(Callee);
2848   // Add a redundant copy of the callee global which will not be legalized, as
2849   // we need direct access to the callee later.
2850   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee);
2851   const GlobalValue *GV = GSD->getGlobal();
2852   Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2853 
2854   if (IsTailCall) {
2855     // Each tail call may have to adjust the stack by a different amount, so
2856     // this information must travel along with the operation for eventual
2857     // consumption by emitEpilogue.
2858     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2859 
2860     Ops.push_back(PhysReturnAddrReg);
2861   }
2862 
2863   // Add argument registers to the end of the list so that they are known live
2864   // into the call.
2865   for (auto &RegToPass : RegsToPass) {
2866     Ops.push_back(DAG.getRegister(RegToPass.first,
2867                                   RegToPass.second.getValueType()));
2868   }
2869 
2870   // Add a register mask operand representing the call-preserved registers.
2871 
2872   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2873   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2874   assert(Mask && "Missing call preserved mask for calling convention");
2875   Ops.push_back(DAG.getRegisterMask(Mask));
2876 
2877   if (InFlag.getNode())
2878     Ops.push_back(InFlag);
2879 
2880   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2881 
2882   // If we're doing a tall call, use a TC_RETURN here rather than an
2883   // actual call instruction.
2884   if (IsTailCall) {
2885     MFI.setHasTailCall();
2886     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2887   }
2888 
2889   // Returns a chain and a flag for retval copy to use.
2890   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2891   Chain = Call.getValue(0);
2892   InFlag = Call.getValue(1);
2893 
2894   uint64_t CalleePopBytes = NumBytes;
2895   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2896                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2897                              InFlag, DL);
2898   if (!Ins.empty())
2899     InFlag = Chain.getValue(1);
2900 
2901   // Handle result values, copying them out of physregs into vregs that we
2902   // return.
2903   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2904                          InVals, IsThisReturn,
2905                          IsThisReturn ? OutVals[0] : SDValue());
2906 }
2907 
2908 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2909                                              SelectionDAG &DAG) const {
2910   unsigned Reg = StringSwitch<unsigned>(RegName)
2911     .Case("m0", AMDGPU::M0)
2912     .Case("exec", AMDGPU::EXEC)
2913     .Case("exec_lo", AMDGPU::EXEC_LO)
2914     .Case("exec_hi", AMDGPU::EXEC_HI)
2915     .Case("flat_scratch", AMDGPU::FLAT_SCR)
2916     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2917     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2918     .Default(AMDGPU::NoRegister);
2919 
2920   if (Reg == AMDGPU::NoRegister) {
2921     report_fatal_error(Twine("invalid register name \""
2922                              + StringRef(RegName)  + "\"."));
2923 
2924   }
2925 
2926   if (!Subtarget->hasFlatScrRegister() &&
2927        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2928     report_fatal_error(Twine("invalid register \""
2929                              + StringRef(RegName)  + "\" for subtarget."));
2930   }
2931 
2932   switch (Reg) {
2933   case AMDGPU::M0:
2934   case AMDGPU::EXEC_LO:
2935   case AMDGPU::EXEC_HI:
2936   case AMDGPU::FLAT_SCR_LO:
2937   case AMDGPU::FLAT_SCR_HI:
2938     if (VT.getSizeInBits() == 32)
2939       return Reg;
2940     break;
2941   case AMDGPU::EXEC:
2942   case AMDGPU::FLAT_SCR:
2943     if (VT.getSizeInBits() == 64)
2944       return Reg;
2945     break;
2946   default:
2947     llvm_unreachable("missing register type checking");
2948   }
2949 
2950   report_fatal_error(Twine("invalid type for register \""
2951                            + StringRef(RegName) + "\"."));
2952 }
2953 
2954 // If kill is not the last instruction, split the block so kill is always a
2955 // proper terminator.
2956 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2957                                                     MachineBasicBlock *BB) const {
2958   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2959 
2960   MachineBasicBlock::iterator SplitPoint(&MI);
2961   ++SplitPoint;
2962 
2963   if (SplitPoint == BB->end()) {
2964     // Don't bother with a new block.
2965     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2966     return BB;
2967   }
2968 
2969   MachineFunction *MF = BB->getParent();
2970   MachineBasicBlock *SplitBB
2971     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2972 
2973   MF->insert(++MachineFunction::iterator(BB), SplitBB);
2974   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2975 
2976   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2977   BB->addSuccessor(SplitBB);
2978 
2979   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2980   return SplitBB;
2981 }
2982 
2983 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
2984 // \p MI will be the only instruction in the loop body block. Otherwise, it will
2985 // be the first instruction in the remainder block.
2986 //
2987 /// \returns { LoopBody, Remainder }
2988 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
2989 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
2990   MachineFunction *MF = MBB.getParent();
2991   MachineBasicBlock::iterator I(&MI);
2992 
2993   // To insert the loop we need to split the block. Move everything after this
2994   // point to a new block, and insert a new empty block between the two.
2995   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
2996   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
2997   MachineFunction::iterator MBBI(MBB);
2998   ++MBBI;
2999 
3000   MF->insert(MBBI, LoopBB);
3001   MF->insert(MBBI, RemainderBB);
3002 
3003   LoopBB->addSuccessor(LoopBB);
3004   LoopBB->addSuccessor(RemainderBB);
3005 
3006   // Move the rest of the block into a new block.
3007   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3008 
3009   if (InstInLoop) {
3010     auto Next = std::next(I);
3011 
3012     // Move instruction to loop body.
3013     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3014 
3015     // Move the rest of the block.
3016     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3017   } else {
3018     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3019   }
3020 
3021   MBB.addSuccessor(LoopBB);
3022 
3023   return std::make_pair(LoopBB, RemainderBB);
3024 }
3025 
3026 MachineBasicBlock *
3027 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3028                                          MachineBasicBlock *BB) const {
3029   const DebugLoc &DL = MI.getDebugLoc();
3030 
3031   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3032 
3033   MachineBasicBlock *LoopBB;
3034   MachineBasicBlock *RemainderBB;
3035   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3036 
3037   MachineBasicBlock::iterator Prev = std::prev(MI.getIterator());
3038 
3039   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3040 
3041   MachineBasicBlock::iterator I = LoopBB->end();
3042   MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0);
3043 
3044   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3045     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3046 
3047   // Clear TRAP_STS.MEM_VIOL
3048   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3049     .addImm(0)
3050     .addImm(EncodedReg);
3051 
3052   // This is a pain, but we're not allowed to have physical register live-ins
3053   // yet. Insert a pair of copies if the VGPR0 hack is necessary.
3054   if (Src && TargetRegisterInfo::isPhysicalRegister(Src->getReg())) {
3055     unsigned Data0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3056     BuildMI(*BB, std::next(Prev), DL, TII->get(AMDGPU::COPY), Data0)
3057       .add(*Src);
3058 
3059     BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::COPY), Src->getReg())
3060       .addReg(Data0);
3061 
3062     MRI.setSimpleHint(Data0, Src->getReg());
3063   }
3064 
3065   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_WAITCNT))
3066     .addImm(0);
3067 
3068   unsigned Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3069 
3070   // Load and check TRAP_STS.MEM_VIOL
3071   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3072     .addImm(EncodedReg);
3073 
3074   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3075   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3076     .addReg(Reg, RegState::Kill)
3077     .addImm(0);
3078   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3079     .addMBB(LoopBB);
3080 
3081   return RemainderBB;
3082 }
3083 
3084 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3085 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3086 // will only do one iteration. In the worst case, this will loop 64 times.
3087 //
3088 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3089 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3090   const SIInstrInfo *TII,
3091   MachineRegisterInfo &MRI,
3092   MachineBasicBlock &OrigBB,
3093   MachineBasicBlock &LoopBB,
3094   const DebugLoc &DL,
3095   const MachineOperand &IdxReg,
3096   unsigned InitReg,
3097   unsigned ResultReg,
3098   unsigned PhiReg,
3099   unsigned InitSaveExecReg,
3100   int Offset,
3101   bool UseGPRIdxMode,
3102   bool IsIndirectSrc) {
3103   MachineFunction *MF = OrigBB.getParent();
3104   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3105   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3106   MachineBasicBlock::iterator I = LoopBB.begin();
3107 
3108   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3109   unsigned PhiExec = MRI.createVirtualRegister(BoolRC);
3110   unsigned NewExec = MRI.createVirtualRegister(BoolRC);
3111   unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3112   unsigned CondReg = MRI.createVirtualRegister(BoolRC);
3113 
3114   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3115     .addReg(InitReg)
3116     .addMBB(&OrigBB)
3117     .addReg(ResultReg)
3118     .addMBB(&LoopBB);
3119 
3120   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3121     .addReg(InitSaveExecReg)
3122     .addMBB(&OrigBB)
3123     .addReg(NewExec)
3124     .addMBB(&LoopBB);
3125 
3126   // Read the next variant <- also loop target.
3127   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3128     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3129 
3130   // Compare the just read M0 value to all possible Idx values.
3131   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3132     .addReg(CurrentIdxReg)
3133     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3134 
3135   // Update EXEC, save the original EXEC value to VCC.
3136   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3137                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3138           NewExec)
3139     .addReg(CondReg, RegState::Kill);
3140 
3141   MRI.setSimpleHint(NewExec, CondReg);
3142 
3143   if (UseGPRIdxMode) {
3144     unsigned IdxReg;
3145     if (Offset == 0) {
3146       IdxReg = CurrentIdxReg;
3147     } else {
3148       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3149       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3150         .addReg(CurrentIdxReg, RegState::Kill)
3151         .addImm(Offset);
3152     }
3153     unsigned IdxMode = IsIndirectSrc ?
3154       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3155     MachineInstr *SetOn =
3156       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3157       .addReg(IdxReg, RegState::Kill)
3158       .addImm(IdxMode);
3159     SetOn->getOperand(3).setIsUndef();
3160   } else {
3161     // Move index from VCC into M0
3162     if (Offset == 0) {
3163       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3164         .addReg(CurrentIdxReg, RegState::Kill);
3165     } else {
3166       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3167         .addReg(CurrentIdxReg, RegState::Kill)
3168         .addImm(Offset);
3169     }
3170   }
3171 
3172   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3173   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3174   MachineInstr *InsertPt =
3175     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3176                                                   : AMDGPU::S_XOR_B64_term), Exec)
3177       .addReg(Exec)
3178       .addReg(NewExec);
3179 
3180   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3181   // s_cbranch_scc0?
3182 
3183   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3184   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3185     .addMBB(&LoopBB);
3186 
3187   return InsertPt->getIterator();
3188 }
3189 
3190 // This has slightly sub-optimal regalloc when the source vector is killed by
3191 // the read. The register allocator does not understand that the kill is
3192 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3193 // subregister from it, using 1 more VGPR than necessary. This was saved when
3194 // this was expanded after register allocation.
3195 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3196                                                   MachineBasicBlock &MBB,
3197                                                   MachineInstr &MI,
3198                                                   unsigned InitResultReg,
3199                                                   unsigned PhiReg,
3200                                                   int Offset,
3201                                                   bool UseGPRIdxMode,
3202                                                   bool IsIndirectSrc) {
3203   MachineFunction *MF = MBB.getParent();
3204   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3205   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3206   MachineRegisterInfo &MRI = MF->getRegInfo();
3207   const DebugLoc &DL = MI.getDebugLoc();
3208   MachineBasicBlock::iterator I(&MI);
3209 
3210   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3211   unsigned DstReg = MI.getOperand(0).getReg();
3212   unsigned SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3213   unsigned TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3214   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3215   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3216 
3217   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3218 
3219   // Save the EXEC mask
3220   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3221     .addReg(Exec);
3222 
3223   MachineBasicBlock *LoopBB;
3224   MachineBasicBlock *RemainderBB;
3225   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3226 
3227   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3228 
3229   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3230                                       InitResultReg, DstReg, PhiReg, TmpExec,
3231                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3232 
3233   MachineBasicBlock::iterator First = RemainderBB->begin();
3234   BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec)
3235     .addReg(SaveExec);
3236 
3237   return InsPt;
3238 }
3239 
3240 // Returns subreg index, offset
3241 static std::pair<unsigned, int>
3242 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3243                             const TargetRegisterClass *SuperRC,
3244                             unsigned VecReg,
3245                             int Offset) {
3246   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3247 
3248   // Skip out of bounds offsets, or else we would end up using an undefined
3249   // register.
3250   if (Offset >= NumElts || Offset < 0)
3251     return std::make_pair(AMDGPU::sub0, Offset);
3252 
3253   return std::make_pair(AMDGPU::sub0 + Offset, 0);
3254 }
3255 
3256 // Return true if the index is an SGPR and was set.
3257 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3258                                  MachineRegisterInfo &MRI,
3259                                  MachineInstr &MI,
3260                                  int Offset,
3261                                  bool UseGPRIdxMode,
3262                                  bool IsIndirectSrc) {
3263   MachineBasicBlock *MBB = MI.getParent();
3264   const DebugLoc &DL = MI.getDebugLoc();
3265   MachineBasicBlock::iterator I(&MI);
3266 
3267   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3268   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3269 
3270   assert(Idx->getReg() != AMDGPU::NoRegister);
3271 
3272   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3273     return false;
3274 
3275   if (UseGPRIdxMode) {
3276     unsigned IdxMode = IsIndirectSrc ?
3277       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3278     if (Offset == 0) {
3279       MachineInstr *SetOn =
3280           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3281               .add(*Idx)
3282               .addImm(IdxMode);
3283 
3284       SetOn->getOperand(3).setIsUndef();
3285     } else {
3286       unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3287       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3288           .add(*Idx)
3289           .addImm(Offset);
3290       MachineInstr *SetOn =
3291         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3292         .addReg(Tmp, RegState::Kill)
3293         .addImm(IdxMode);
3294 
3295       SetOn->getOperand(3).setIsUndef();
3296     }
3297 
3298     return true;
3299   }
3300 
3301   if (Offset == 0) {
3302     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3303       .add(*Idx);
3304   } else {
3305     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3306       .add(*Idx)
3307       .addImm(Offset);
3308   }
3309 
3310   return true;
3311 }
3312 
3313 // Control flow needs to be inserted if indexing with a VGPR.
3314 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3315                                           MachineBasicBlock &MBB,
3316                                           const GCNSubtarget &ST) {
3317   const SIInstrInfo *TII = ST.getInstrInfo();
3318   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3319   MachineFunction *MF = MBB.getParent();
3320   MachineRegisterInfo &MRI = MF->getRegInfo();
3321 
3322   unsigned Dst = MI.getOperand(0).getReg();
3323   unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3324   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3325 
3326   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3327 
3328   unsigned SubReg;
3329   std::tie(SubReg, Offset)
3330     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3331 
3332   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3333 
3334   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3335     MachineBasicBlock::iterator I(&MI);
3336     const DebugLoc &DL = MI.getDebugLoc();
3337 
3338     if (UseGPRIdxMode) {
3339       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3340       // to avoid interfering with other uses, so probably requires a new
3341       // optimization pass.
3342       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3343         .addReg(SrcReg, RegState::Undef, SubReg)
3344         .addReg(SrcReg, RegState::Implicit)
3345         .addReg(AMDGPU::M0, RegState::Implicit);
3346       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3347     } else {
3348       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3349         .addReg(SrcReg, RegState::Undef, SubReg)
3350         .addReg(SrcReg, RegState::Implicit);
3351     }
3352 
3353     MI.eraseFromParent();
3354 
3355     return &MBB;
3356   }
3357 
3358   const DebugLoc &DL = MI.getDebugLoc();
3359   MachineBasicBlock::iterator I(&MI);
3360 
3361   unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3362   unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3363 
3364   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3365 
3366   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3367                               Offset, UseGPRIdxMode, true);
3368   MachineBasicBlock *LoopBB = InsPt->getParent();
3369 
3370   if (UseGPRIdxMode) {
3371     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3372       .addReg(SrcReg, RegState::Undef, SubReg)
3373       .addReg(SrcReg, RegState::Implicit)
3374       .addReg(AMDGPU::M0, RegState::Implicit);
3375     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3376   } else {
3377     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3378       .addReg(SrcReg, RegState::Undef, SubReg)
3379       .addReg(SrcReg, RegState::Implicit);
3380   }
3381 
3382   MI.eraseFromParent();
3383 
3384   return LoopBB;
3385 }
3386 
3387 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3388                                  const TargetRegisterClass *VecRC) {
3389   switch (TRI.getRegSizeInBits(*VecRC)) {
3390   case 32: // 4 bytes
3391     return AMDGPU::V_MOVRELD_B32_V1;
3392   case 64: // 8 bytes
3393     return AMDGPU::V_MOVRELD_B32_V2;
3394   case 128: // 16 bytes
3395     return AMDGPU::V_MOVRELD_B32_V4;
3396   case 256: // 32 bytes
3397     return AMDGPU::V_MOVRELD_B32_V8;
3398   case 512: // 64 bytes
3399     return AMDGPU::V_MOVRELD_B32_V16;
3400   default:
3401     llvm_unreachable("unsupported size for MOVRELD pseudos");
3402   }
3403 }
3404 
3405 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3406                                           MachineBasicBlock &MBB,
3407                                           const GCNSubtarget &ST) {
3408   const SIInstrInfo *TII = ST.getInstrInfo();
3409   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3410   MachineFunction *MF = MBB.getParent();
3411   MachineRegisterInfo &MRI = MF->getRegInfo();
3412 
3413   unsigned Dst = MI.getOperand(0).getReg();
3414   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3415   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3416   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3417   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3418   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3419 
3420   // This can be an immediate, but will be folded later.
3421   assert(Val->getReg());
3422 
3423   unsigned SubReg;
3424   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3425                                                          SrcVec->getReg(),
3426                                                          Offset);
3427   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3428 
3429   if (Idx->getReg() == AMDGPU::NoRegister) {
3430     MachineBasicBlock::iterator I(&MI);
3431     const DebugLoc &DL = MI.getDebugLoc();
3432 
3433     assert(Offset == 0);
3434 
3435     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3436         .add(*SrcVec)
3437         .add(*Val)
3438         .addImm(SubReg);
3439 
3440     MI.eraseFromParent();
3441     return &MBB;
3442   }
3443 
3444   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3445     MachineBasicBlock::iterator I(&MI);
3446     const DebugLoc &DL = MI.getDebugLoc();
3447 
3448     if (UseGPRIdxMode) {
3449       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3450           .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3451           .add(*Val)
3452           .addReg(Dst, RegState::ImplicitDefine)
3453           .addReg(SrcVec->getReg(), RegState::Implicit)
3454           .addReg(AMDGPU::M0, RegState::Implicit);
3455 
3456       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3457     } else {
3458       const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3459 
3460       BuildMI(MBB, I, DL, MovRelDesc)
3461           .addReg(Dst, RegState::Define)
3462           .addReg(SrcVec->getReg())
3463           .add(*Val)
3464           .addImm(SubReg - AMDGPU::sub0);
3465     }
3466 
3467     MI.eraseFromParent();
3468     return &MBB;
3469   }
3470 
3471   if (Val->isReg())
3472     MRI.clearKillFlags(Val->getReg());
3473 
3474   const DebugLoc &DL = MI.getDebugLoc();
3475 
3476   unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3477 
3478   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3479                               Offset, UseGPRIdxMode, false);
3480   MachineBasicBlock *LoopBB = InsPt->getParent();
3481 
3482   if (UseGPRIdxMode) {
3483     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3484         .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3485         .add(*Val)                               // src0
3486         .addReg(Dst, RegState::ImplicitDefine)
3487         .addReg(PhiReg, RegState::Implicit)
3488         .addReg(AMDGPU::M0, RegState::Implicit);
3489     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3490   } else {
3491     const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3492 
3493     BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3494         .addReg(Dst, RegState::Define)
3495         .addReg(PhiReg)
3496         .add(*Val)
3497         .addImm(SubReg - AMDGPU::sub0);
3498   }
3499 
3500   MI.eraseFromParent();
3501 
3502   return LoopBB;
3503 }
3504 
3505 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3506   MachineInstr &MI, MachineBasicBlock *BB) const {
3507 
3508   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3509   MachineFunction *MF = BB->getParent();
3510   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3511 
3512   if (TII->isMIMG(MI)) {
3513     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3514       report_fatal_error("missing mem operand from MIMG instruction");
3515     }
3516     // Add a memoperand for mimg instructions so that they aren't assumed to
3517     // be ordered memory instuctions.
3518 
3519     return BB;
3520   }
3521 
3522   switch (MI.getOpcode()) {
3523   case AMDGPU::S_ADD_U64_PSEUDO:
3524   case AMDGPU::S_SUB_U64_PSEUDO: {
3525     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3526     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3527     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3528     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3529     const DebugLoc &DL = MI.getDebugLoc();
3530 
3531     MachineOperand &Dest = MI.getOperand(0);
3532     MachineOperand &Src0 = MI.getOperand(1);
3533     MachineOperand &Src1 = MI.getOperand(2);
3534 
3535     unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3536     unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3537 
3538     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3539      Src0, BoolRC, AMDGPU::sub0,
3540      &AMDGPU::SReg_32_XM0RegClass);
3541     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3542       Src0, BoolRC, AMDGPU::sub1,
3543       &AMDGPU::SReg_32_XM0RegClass);
3544 
3545     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3546       Src1, BoolRC, AMDGPU::sub0,
3547       &AMDGPU::SReg_32_XM0RegClass);
3548     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3549       Src1, BoolRC, AMDGPU::sub1,
3550       &AMDGPU::SReg_32_XM0RegClass);
3551 
3552     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3553 
3554     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3555     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3556     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3557       .add(Src0Sub0)
3558       .add(Src1Sub0);
3559     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3560       .add(Src0Sub1)
3561       .add(Src1Sub1);
3562     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3563       .addReg(DestSub0)
3564       .addImm(AMDGPU::sub0)
3565       .addReg(DestSub1)
3566       .addImm(AMDGPU::sub1);
3567     MI.eraseFromParent();
3568     return BB;
3569   }
3570   case AMDGPU::SI_INIT_M0: {
3571     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3572             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3573         .add(MI.getOperand(0));
3574     MI.eraseFromParent();
3575     return BB;
3576   }
3577   case AMDGPU::SI_INIT_EXEC:
3578     // This should be before all vector instructions.
3579     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3580             AMDGPU::EXEC)
3581         .addImm(MI.getOperand(0).getImm());
3582     MI.eraseFromParent();
3583     return BB;
3584 
3585   case AMDGPU::SI_INIT_EXEC_LO:
3586     // This should be before all vector instructions.
3587     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3588             AMDGPU::EXEC_LO)
3589         .addImm(MI.getOperand(0).getImm());
3590     MI.eraseFromParent();
3591     return BB;
3592 
3593   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3594     // Extract the thread count from an SGPR input and set EXEC accordingly.
3595     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3596     //
3597     // S_BFE_U32 count, input, {shift, 7}
3598     // S_BFM_B64 exec, count, 0
3599     // S_CMP_EQ_U32 count, 64
3600     // S_CMOV_B64 exec, -1
3601     MachineInstr *FirstMI = &*BB->begin();
3602     MachineRegisterInfo &MRI = MF->getRegInfo();
3603     unsigned InputReg = MI.getOperand(0).getReg();
3604     unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3605     bool Found = false;
3606 
3607     // Move the COPY of the input reg to the beginning, so that we can use it.
3608     for (auto I = BB->begin(); I != &MI; I++) {
3609       if (I->getOpcode() != TargetOpcode::COPY ||
3610           I->getOperand(0).getReg() != InputReg)
3611         continue;
3612 
3613       if (I == FirstMI) {
3614         FirstMI = &*++BB->begin();
3615       } else {
3616         I->removeFromParent();
3617         BB->insert(FirstMI, &*I);
3618       }
3619       Found = true;
3620       break;
3621     }
3622     assert(Found);
3623     (void)Found;
3624 
3625     // This should be before all vector instructions.
3626     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3627     bool isWave32 = getSubtarget()->isWave32();
3628     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3629     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3630         .addReg(InputReg)
3631         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3632     BuildMI(*BB, FirstMI, DebugLoc(),
3633             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3634             Exec)
3635         .addReg(CountReg)
3636         .addImm(0);
3637     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3638         .addReg(CountReg, RegState::Kill)
3639         .addImm(getSubtarget()->getWavefrontSize());
3640     BuildMI(*BB, FirstMI, DebugLoc(),
3641             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3642             Exec)
3643         .addImm(-1);
3644     MI.eraseFromParent();
3645     return BB;
3646   }
3647 
3648   case AMDGPU::GET_GROUPSTATICSIZE: {
3649     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3650            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3651     DebugLoc DL = MI.getDebugLoc();
3652     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3653         .add(MI.getOperand(0))
3654         .addImm(MFI->getLDSSize());
3655     MI.eraseFromParent();
3656     return BB;
3657   }
3658   case AMDGPU::SI_INDIRECT_SRC_V1:
3659   case AMDGPU::SI_INDIRECT_SRC_V2:
3660   case AMDGPU::SI_INDIRECT_SRC_V4:
3661   case AMDGPU::SI_INDIRECT_SRC_V8:
3662   case AMDGPU::SI_INDIRECT_SRC_V16:
3663     return emitIndirectSrc(MI, *BB, *getSubtarget());
3664   case AMDGPU::SI_INDIRECT_DST_V1:
3665   case AMDGPU::SI_INDIRECT_DST_V2:
3666   case AMDGPU::SI_INDIRECT_DST_V4:
3667   case AMDGPU::SI_INDIRECT_DST_V8:
3668   case AMDGPU::SI_INDIRECT_DST_V16:
3669     return emitIndirectDst(MI, *BB, *getSubtarget());
3670   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3671   case AMDGPU::SI_KILL_I1_PSEUDO:
3672     return splitKillBlock(MI, BB);
3673   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3674     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3675     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3676     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3677 
3678     unsigned Dst = MI.getOperand(0).getReg();
3679     unsigned Src0 = MI.getOperand(1).getReg();
3680     unsigned Src1 = MI.getOperand(2).getReg();
3681     const DebugLoc &DL = MI.getDebugLoc();
3682     unsigned SrcCond = MI.getOperand(3).getReg();
3683 
3684     unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3685     unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3686     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3687     unsigned SrcCondCopy = MRI.createVirtualRegister(CondRC);
3688 
3689     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3690       .addReg(SrcCond);
3691     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3692       .addImm(0)
3693       .addReg(Src0, 0, AMDGPU::sub0)
3694       .addImm(0)
3695       .addReg(Src1, 0, AMDGPU::sub0)
3696       .addReg(SrcCondCopy);
3697     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3698       .addImm(0)
3699       .addReg(Src0, 0, AMDGPU::sub1)
3700       .addImm(0)
3701       .addReg(Src1, 0, AMDGPU::sub1)
3702       .addReg(SrcCondCopy);
3703 
3704     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3705       .addReg(DstLo)
3706       .addImm(AMDGPU::sub0)
3707       .addReg(DstHi)
3708       .addImm(AMDGPU::sub1);
3709     MI.eraseFromParent();
3710     return BB;
3711   }
3712   case AMDGPU::SI_BR_UNDEF: {
3713     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3714     const DebugLoc &DL = MI.getDebugLoc();
3715     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3716                            .add(MI.getOperand(0));
3717     Br->getOperand(1).setIsUndef(true); // read undef SCC
3718     MI.eraseFromParent();
3719     return BB;
3720   }
3721   case AMDGPU::ADJCALLSTACKUP:
3722   case AMDGPU::ADJCALLSTACKDOWN: {
3723     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3724     MachineInstrBuilder MIB(*MF, &MI);
3725 
3726     // Add an implicit use of the frame offset reg to prevent the restore copy
3727     // inserted after the call from being reorderd after stack operations in the
3728     // the caller's frame.
3729     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3730         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3731         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3732     return BB;
3733   }
3734   case AMDGPU::SI_CALL_ISEL: {
3735     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3736     const DebugLoc &DL = MI.getDebugLoc();
3737 
3738     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3739 
3740     MachineInstrBuilder MIB;
3741     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3742 
3743     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3744       MIB.add(MI.getOperand(I));
3745 
3746     MIB.cloneMemRefs(MI);
3747     MI.eraseFromParent();
3748     return BB;
3749   }
3750   case AMDGPU::V_ADD_I32_e32:
3751   case AMDGPU::V_SUB_I32_e32:
3752   case AMDGPU::V_SUBREV_I32_e32: {
3753     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3754     const DebugLoc &DL = MI.getDebugLoc();
3755     unsigned Opc = MI.getOpcode();
3756 
3757     bool NeedClampOperand = false;
3758     if (TII->pseudoToMCOpcode(Opc) == -1) {
3759       Opc = AMDGPU::getVOPe64(Opc);
3760       NeedClampOperand = true;
3761     }
3762 
3763     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3764     if (TII->isVOP3(*I)) {
3765       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3766       const SIRegisterInfo *TRI = ST.getRegisterInfo();
3767       I.addReg(TRI->getVCC(), RegState::Define);
3768     }
3769     I.add(MI.getOperand(1))
3770      .add(MI.getOperand(2));
3771     if (NeedClampOperand)
3772       I.addImm(0); // clamp bit for e64 encoding
3773 
3774     TII->legalizeOperands(*I);
3775 
3776     MI.eraseFromParent();
3777     return BB;
3778   }
3779   case AMDGPU::DS_GWS_INIT:
3780   case AMDGPU::DS_GWS_SEMA_V:
3781   case AMDGPU::DS_GWS_SEMA_BR:
3782   case AMDGPU::DS_GWS_SEMA_P:
3783   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
3784   case AMDGPU::DS_GWS_BARRIER:
3785     if (getSubtarget()->hasGWSAutoReplay())
3786       return BB;
3787     return emitGWSMemViolTestLoop(MI, BB);
3788   default:
3789     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3790   }
3791 }
3792 
3793 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3794   return isTypeLegal(VT.getScalarType());
3795 }
3796 
3797 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3798   // This currently forces unfolding various combinations of fsub into fma with
3799   // free fneg'd operands. As long as we have fast FMA (controlled by
3800   // isFMAFasterThanFMulAndFAdd), we should perform these.
3801 
3802   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3803   // most of these combines appear to be cycle neutral but save on instruction
3804   // count / code size.
3805   return true;
3806 }
3807 
3808 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3809                                          EVT VT) const {
3810   if (!VT.isVector()) {
3811     return MVT::i1;
3812   }
3813   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3814 }
3815 
3816 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3817   // TODO: Should i16 be used always if legal? For now it would force VALU
3818   // shifts.
3819   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3820 }
3821 
3822 // Answering this is somewhat tricky and depends on the specific device which
3823 // have different rates for fma or all f64 operations.
3824 //
3825 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3826 // regardless of which device (although the number of cycles differs between
3827 // devices), so it is always profitable for f64.
3828 //
3829 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3830 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3831 // which we can always do even without fused FP ops since it returns the same
3832 // result as the separate operations and since it is always full
3833 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3834 // however does not support denormals, so we do report fma as faster if we have
3835 // a fast fma device and require denormals.
3836 //
3837 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3838   VT = VT.getScalarType();
3839 
3840   switch (VT.getSimpleVT().SimpleTy) {
3841   case MVT::f32: {
3842     // This is as fast on some subtargets. However, we always have full rate f32
3843     // mad available which returns the same result as the separate operations
3844     // which we should prefer over fma. We can't use this if we want to support
3845     // denormals, so only report this in these cases.
3846     if (Subtarget->hasFP32Denormals())
3847       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3848 
3849     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3850     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3851   }
3852   case MVT::f64:
3853     return true;
3854   case MVT::f16:
3855     return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3856   default:
3857     break;
3858   }
3859 
3860   return false;
3861 }
3862 
3863 //===----------------------------------------------------------------------===//
3864 // Custom DAG Lowering Operations
3865 //===----------------------------------------------------------------------===//
3866 
3867 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3868 // wider vector type is legal.
3869 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3870                                              SelectionDAG &DAG) const {
3871   unsigned Opc = Op.getOpcode();
3872   EVT VT = Op.getValueType();
3873   assert(VT == MVT::v4f16);
3874 
3875   SDValue Lo, Hi;
3876   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3877 
3878   SDLoc SL(Op);
3879   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3880                              Op->getFlags());
3881   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3882                              Op->getFlags());
3883 
3884   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3885 }
3886 
3887 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3888 // wider vector type is legal.
3889 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3890                                               SelectionDAG &DAG) const {
3891   unsigned Opc = Op.getOpcode();
3892   EVT VT = Op.getValueType();
3893   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3894 
3895   SDValue Lo0, Hi0;
3896   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3897   SDValue Lo1, Hi1;
3898   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3899 
3900   SDLoc SL(Op);
3901 
3902   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3903                              Op->getFlags());
3904   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3905                              Op->getFlags());
3906 
3907   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3908 }
3909 
3910 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3911   switch (Op.getOpcode()) {
3912   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3913   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3914   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
3915   case ISD::LOAD: {
3916     SDValue Result = LowerLOAD(Op, DAG);
3917     assert((!Result.getNode() ||
3918             Result.getNode()->getNumValues() == 2) &&
3919            "Load should return a value and a chain");
3920     return Result;
3921   }
3922 
3923   case ISD::FSIN:
3924   case ISD::FCOS:
3925     return LowerTrig(Op, DAG);
3926   case ISD::SELECT: return LowerSELECT(Op, DAG);
3927   case ISD::FDIV: return LowerFDIV(Op, DAG);
3928   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3929   case ISD::STORE: return LowerSTORE(Op, DAG);
3930   case ISD::GlobalAddress: {
3931     MachineFunction &MF = DAG.getMachineFunction();
3932     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3933     return LowerGlobalAddress(MFI, Op, DAG);
3934   }
3935   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3936   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3937   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3938   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3939   case ISD::INSERT_SUBVECTOR:
3940     return lowerINSERT_SUBVECTOR(Op, DAG);
3941   case ISD::INSERT_VECTOR_ELT:
3942     return lowerINSERT_VECTOR_ELT(Op, DAG);
3943   case ISD::EXTRACT_VECTOR_ELT:
3944     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3945   case ISD::VECTOR_SHUFFLE:
3946     return lowerVECTOR_SHUFFLE(Op, DAG);
3947   case ISD::BUILD_VECTOR:
3948     return lowerBUILD_VECTOR(Op, DAG);
3949   case ISD::FP_ROUND:
3950     return lowerFP_ROUND(Op, DAG);
3951   case ISD::TRAP:
3952     return lowerTRAP(Op, DAG);
3953   case ISD::DEBUGTRAP:
3954     return lowerDEBUGTRAP(Op, DAG);
3955   case ISD::FABS:
3956   case ISD::FNEG:
3957   case ISD::FCANONICALIZE:
3958     return splitUnaryVectorOp(Op, DAG);
3959   case ISD::FMINNUM:
3960   case ISD::FMAXNUM:
3961     return lowerFMINNUM_FMAXNUM(Op, DAG);
3962   case ISD::SHL:
3963   case ISD::SRA:
3964   case ISD::SRL:
3965   case ISD::ADD:
3966   case ISD::SUB:
3967   case ISD::MUL:
3968   case ISD::SMIN:
3969   case ISD::SMAX:
3970   case ISD::UMIN:
3971   case ISD::UMAX:
3972   case ISD::FADD:
3973   case ISD::FMUL:
3974   case ISD::FMINNUM_IEEE:
3975   case ISD::FMAXNUM_IEEE:
3976     return splitBinaryVectorOp(Op, DAG);
3977   }
3978   return SDValue();
3979 }
3980 
3981 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
3982                                        const SDLoc &DL,
3983                                        SelectionDAG &DAG, bool Unpacked) {
3984   if (!LoadVT.isVector())
3985     return Result;
3986 
3987   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
3988     // Truncate to v2i16/v4i16.
3989     EVT IntLoadVT = LoadVT.changeTypeToInteger();
3990 
3991     // Workaround legalizer not scalarizing truncate after vector op
3992     // legalization byt not creating intermediate vector trunc.
3993     SmallVector<SDValue, 4> Elts;
3994     DAG.ExtractVectorElements(Result, Elts);
3995     for (SDValue &Elt : Elts)
3996       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
3997 
3998     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
3999 
4000     // Bitcast to original type (v2f16/v4f16).
4001     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4002   }
4003 
4004   // Cast back to the original packed type.
4005   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4006 }
4007 
4008 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4009                                               MemSDNode *M,
4010                                               SelectionDAG &DAG,
4011                                               ArrayRef<SDValue> Ops,
4012                                               bool IsIntrinsic) const {
4013   SDLoc DL(M);
4014 
4015   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4016   EVT LoadVT = M->getValueType(0);
4017 
4018   EVT EquivLoadVT = LoadVT;
4019   if (Unpacked && LoadVT.isVector()) {
4020     EquivLoadVT = LoadVT.isVector() ?
4021       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4022                        LoadVT.getVectorNumElements()) : LoadVT;
4023   }
4024 
4025   // Change from v4f16/v2f16 to EquivLoadVT.
4026   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4027 
4028   SDValue Load
4029     = DAG.getMemIntrinsicNode(
4030       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4031       VTList, Ops, M->getMemoryVT(),
4032       M->getMemOperand());
4033   if (!Unpacked) // Just adjusted the opcode.
4034     return Load;
4035 
4036   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4037 
4038   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4039 }
4040 
4041 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4042                                   SDNode *N, SelectionDAG &DAG) {
4043   EVT VT = N->getValueType(0);
4044   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4045   int CondCode = CD->getSExtValue();
4046   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4047       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4048     return DAG.getUNDEF(VT);
4049 
4050   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4051 
4052   SDValue LHS = N->getOperand(1);
4053   SDValue RHS = N->getOperand(2);
4054 
4055   SDLoc DL(N);
4056 
4057   EVT CmpVT = LHS.getValueType();
4058   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4059     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4060       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4061     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4062     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4063   }
4064 
4065   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4066 
4067   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4068   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4069 
4070   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4071                               DAG.getCondCode(CCOpcode));
4072   if (VT.bitsEq(CCVT))
4073     return SetCC;
4074   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4075 }
4076 
4077 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4078                                   SDNode *N, SelectionDAG &DAG) {
4079   EVT VT = N->getValueType(0);
4080   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4081 
4082   int CondCode = CD->getSExtValue();
4083   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4084       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4085     return DAG.getUNDEF(VT);
4086   }
4087 
4088   SDValue Src0 = N->getOperand(1);
4089   SDValue Src1 = N->getOperand(2);
4090   EVT CmpVT = Src0.getValueType();
4091   SDLoc SL(N);
4092 
4093   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4094     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4095     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4096   }
4097 
4098   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4099   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4100   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4101   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4102   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4103                               Src1, DAG.getCondCode(CCOpcode));
4104   if (VT.bitsEq(CCVT))
4105     return SetCC;
4106   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4107 }
4108 
4109 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4110                                           SmallVectorImpl<SDValue> &Results,
4111                                           SelectionDAG &DAG) const {
4112   switch (N->getOpcode()) {
4113   case ISD::INSERT_VECTOR_ELT: {
4114     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4115       Results.push_back(Res);
4116     return;
4117   }
4118   case ISD::EXTRACT_VECTOR_ELT: {
4119     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4120       Results.push_back(Res);
4121     return;
4122   }
4123   case ISD::INTRINSIC_WO_CHAIN: {
4124     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4125     switch (IID) {
4126     case Intrinsic::amdgcn_cvt_pkrtz: {
4127       SDValue Src0 = N->getOperand(1);
4128       SDValue Src1 = N->getOperand(2);
4129       SDLoc SL(N);
4130       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4131                                 Src0, Src1);
4132       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4133       return;
4134     }
4135     case Intrinsic::amdgcn_cvt_pknorm_i16:
4136     case Intrinsic::amdgcn_cvt_pknorm_u16:
4137     case Intrinsic::amdgcn_cvt_pk_i16:
4138     case Intrinsic::amdgcn_cvt_pk_u16: {
4139       SDValue Src0 = N->getOperand(1);
4140       SDValue Src1 = N->getOperand(2);
4141       SDLoc SL(N);
4142       unsigned Opcode;
4143 
4144       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4145         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4146       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4147         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4148       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4149         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4150       else
4151         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4152 
4153       EVT VT = N->getValueType(0);
4154       if (isTypeLegal(VT))
4155         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4156       else {
4157         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4158         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4159       }
4160       return;
4161     }
4162     }
4163     break;
4164   }
4165   case ISD::INTRINSIC_W_CHAIN: {
4166     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4167       Results.push_back(Res);
4168       Results.push_back(Res.getValue(1));
4169       return;
4170     }
4171 
4172     break;
4173   }
4174   case ISD::SELECT: {
4175     SDLoc SL(N);
4176     EVT VT = N->getValueType(0);
4177     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4178     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4179     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4180 
4181     EVT SelectVT = NewVT;
4182     if (NewVT.bitsLT(MVT::i32)) {
4183       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4184       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4185       SelectVT = MVT::i32;
4186     }
4187 
4188     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4189                                     N->getOperand(0), LHS, RHS);
4190 
4191     if (NewVT != SelectVT)
4192       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4193     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4194     return;
4195   }
4196   case ISD::FNEG: {
4197     if (N->getValueType(0) != MVT::v2f16)
4198       break;
4199 
4200     SDLoc SL(N);
4201     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4202 
4203     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4204                              BC,
4205                              DAG.getConstant(0x80008000, SL, MVT::i32));
4206     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4207     return;
4208   }
4209   case ISD::FABS: {
4210     if (N->getValueType(0) != MVT::v2f16)
4211       break;
4212 
4213     SDLoc SL(N);
4214     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4215 
4216     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4217                              BC,
4218                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4219     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4220     return;
4221   }
4222   default:
4223     break;
4224   }
4225 }
4226 
4227 /// Helper function for LowerBRCOND
4228 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4229 
4230   SDNode *Parent = Value.getNode();
4231   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4232        I != E; ++I) {
4233 
4234     if (I.getUse().get() != Value)
4235       continue;
4236 
4237     if (I->getOpcode() == Opcode)
4238       return *I;
4239   }
4240   return nullptr;
4241 }
4242 
4243 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4244   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4245     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4246     case Intrinsic::amdgcn_if:
4247       return AMDGPUISD::IF;
4248     case Intrinsic::amdgcn_else:
4249       return AMDGPUISD::ELSE;
4250     case Intrinsic::amdgcn_loop:
4251       return AMDGPUISD::LOOP;
4252     case Intrinsic::amdgcn_end_cf:
4253       llvm_unreachable("should not occur");
4254     default:
4255       return 0;
4256     }
4257   }
4258 
4259   // break, if_break, else_break are all only used as inputs to loop, not
4260   // directly as branch conditions.
4261   return 0;
4262 }
4263 
4264 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4265   const Triple &TT = getTargetMachine().getTargetTriple();
4266   return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4267           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4268          AMDGPU::shouldEmitConstantsToTextSection(TT);
4269 }
4270 
4271 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4272   // FIXME: Either avoid relying on address space here or change the default
4273   // address space for functions to avoid the explicit check.
4274   return (GV->getValueType()->isFunctionTy() ||
4275           GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4276           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4277           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4278          !shouldEmitFixup(GV) &&
4279          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4280 }
4281 
4282 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4283   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4284 }
4285 
4286 /// This transforms the control flow intrinsics to get the branch destination as
4287 /// last parameter, also switches branch target with BR if the need arise
4288 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4289                                       SelectionDAG &DAG) const {
4290   SDLoc DL(BRCOND);
4291 
4292   SDNode *Intr = BRCOND.getOperand(1).getNode();
4293   SDValue Target = BRCOND.getOperand(2);
4294   SDNode *BR = nullptr;
4295   SDNode *SetCC = nullptr;
4296 
4297   if (Intr->getOpcode() == ISD::SETCC) {
4298     // As long as we negate the condition everything is fine
4299     SetCC = Intr;
4300     Intr = SetCC->getOperand(0).getNode();
4301 
4302   } else {
4303     // Get the target from BR if we don't negate the condition
4304     BR = findUser(BRCOND, ISD::BR);
4305     Target = BR->getOperand(1);
4306   }
4307 
4308   // FIXME: This changes the types of the intrinsics instead of introducing new
4309   // nodes with the correct types.
4310   // e.g. llvm.amdgcn.loop
4311 
4312   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4313   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4314 
4315   unsigned CFNode = isCFIntrinsic(Intr);
4316   if (CFNode == 0) {
4317     // This is a uniform branch so we don't need to legalize.
4318     return BRCOND;
4319   }
4320 
4321   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4322                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4323 
4324   assert(!SetCC ||
4325         (SetCC->getConstantOperandVal(1) == 1 &&
4326          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4327                                                              ISD::SETNE));
4328 
4329   // operands of the new intrinsic call
4330   SmallVector<SDValue, 4> Ops;
4331   if (HaveChain)
4332     Ops.push_back(BRCOND.getOperand(0));
4333 
4334   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4335   Ops.push_back(Target);
4336 
4337   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4338 
4339   // build the new intrinsic call
4340   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4341 
4342   if (!HaveChain) {
4343     SDValue Ops[] =  {
4344       SDValue(Result, 0),
4345       BRCOND.getOperand(0)
4346     };
4347 
4348     Result = DAG.getMergeValues(Ops, DL).getNode();
4349   }
4350 
4351   if (BR) {
4352     // Give the branch instruction our target
4353     SDValue Ops[] = {
4354       BR->getOperand(0),
4355       BRCOND.getOperand(2)
4356     };
4357     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4358     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4359     BR = NewBR.getNode();
4360   }
4361 
4362   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4363 
4364   // Copy the intrinsic results to registers
4365   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4366     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4367     if (!CopyToReg)
4368       continue;
4369 
4370     Chain = DAG.getCopyToReg(
4371       Chain, DL,
4372       CopyToReg->getOperand(1),
4373       SDValue(Result, i - 1),
4374       SDValue());
4375 
4376     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4377   }
4378 
4379   // Remove the old intrinsic from the chain
4380   DAG.ReplaceAllUsesOfValueWith(
4381     SDValue(Intr, Intr->getNumValues() - 1),
4382     Intr->getOperand(0));
4383 
4384   return Chain;
4385 }
4386 
4387 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4388                                           SelectionDAG &DAG) const {
4389   MVT VT = Op.getSimpleValueType();
4390   SDLoc DL(Op);
4391   // Checking the depth
4392   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4393     return DAG.getConstant(0, DL, VT);
4394 
4395   MachineFunction &MF = DAG.getMachineFunction();
4396   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4397   // Check for kernel and shader functions
4398   if (Info->isEntryFunction())
4399     return DAG.getConstant(0, DL, VT);
4400 
4401   MachineFrameInfo &MFI = MF.getFrameInfo();
4402   // There is a call to @llvm.returnaddress in this function
4403   MFI.setReturnAddressIsTaken(true);
4404 
4405   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4406   // Get the return address reg and mark it as an implicit live-in
4407   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4408 
4409   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4410 }
4411 
4412 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4413                                             SDValue Op,
4414                                             const SDLoc &DL,
4415                                             EVT VT) const {
4416   return Op.getValueType().bitsLE(VT) ?
4417       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4418       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4419 }
4420 
4421 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4422   assert(Op.getValueType() == MVT::f16 &&
4423          "Do not know how to custom lower FP_ROUND for non-f16 type");
4424 
4425   SDValue Src = Op.getOperand(0);
4426   EVT SrcVT = Src.getValueType();
4427   if (SrcVT != MVT::f64)
4428     return Op;
4429 
4430   SDLoc DL(Op);
4431 
4432   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4433   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4434   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4435 }
4436 
4437 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4438                                                SelectionDAG &DAG) const {
4439   EVT VT = Op.getValueType();
4440   const MachineFunction &MF = DAG.getMachineFunction();
4441   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4442   bool IsIEEEMode = Info->getMode().IEEE;
4443 
4444   // FIXME: Assert during eslection that this is only selected for
4445   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4446   // mode functions, but this happens to be OK since it's only done in cases
4447   // where there is known no sNaN.
4448   if (IsIEEEMode)
4449     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4450 
4451   if (VT == MVT::v4f16)
4452     return splitBinaryVectorOp(Op, DAG);
4453   return Op;
4454 }
4455 
4456 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4457   SDLoc SL(Op);
4458   SDValue Chain = Op.getOperand(0);
4459 
4460   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4461       !Subtarget->isTrapHandlerEnabled())
4462     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4463 
4464   MachineFunction &MF = DAG.getMachineFunction();
4465   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4466   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4467   assert(UserSGPR != AMDGPU::NoRegister);
4468   SDValue QueuePtr = CreateLiveInRegister(
4469     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4470   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4471   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4472                                    QueuePtr, SDValue());
4473   SDValue Ops[] = {
4474     ToReg,
4475     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4476     SGPR01,
4477     ToReg.getValue(1)
4478   };
4479   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4480 }
4481 
4482 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4483   SDLoc SL(Op);
4484   SDValue Chain = Op.getOperand(0);
4485   MachineFunction &MF = DAG.getMachineFunction();
4486 
4487   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4488       !Subtarget->isTrapHandlerEnabled()) {
4489     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4490                                      "debugtrap handler not supported",
4491                                      Op.getDebugLoc(),
4492                                      DS_Warning);
4493     LLVMContext &Ctx = MF.getFunction().getContext();
4494     Ctx.diagnose(NoTrap);
4495     return Chain;
4496   }
4497 
4498   SDValue Ops[] = {
4499     Chain,
4500     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4501   };
4502   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4503 }
4504 
4505 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4506                                              SelectionDAG &DAG) const {
4507   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4508   if (Subtarget->hasApertureRegs()) {
4509     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4510         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4511         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4512     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4513         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4514         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4515     unsigned Encoding =
4516         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4517         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4518         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4519 
4520     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4521     SDValue ApertureReg = SDValue(
4522         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4523     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4524     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4525   }
4526 
4527   MachineFunction &MF = DAG.getMachineFunction();
4528   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4529   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4530   assert(UserSGPR != AMDGPU::NoRegister);
4531 
4532   SDValue QueuePtr = CreateLiveInRegister(
4533     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4534 
4535   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4536   // private_segment_aperture_base_hi.
4537   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4538 
4539   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4540 
4541   // TODO: Use custom target PseudoSourceValue.
4542   // TODO: We should use the value from the IR intrinsic call, but it might not
4543   // be available and how do we get it?
4544   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4545                                               AMDGPUAS::CONSTANT_ADDRESS));
4546 
4547   MachinePointerInfo PtrInfo(V, StructOffset);
4548   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4549                      MinAlign(64, StructOffset),
4550                      MachineMemOperand::MODereferenceable |
4551                          MachineMemOperand::MOInvariant);
4552 }
4553 
4554 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4555                                              SelectionDAG &DAG) const {
4556   SDLoc SL(Op);
4557   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4558 
4559   SDValue Src = ASC->getOperand(0);
4560   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4561 
4562   const AMDGPUTargetMachine &TM =
4563     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4564 
4565   // flat -> local/private
4566   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4567     unsigned DestAS = ASC->getDestAddressSpace();
4568 
4569     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4570         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4571       unsigned NullVal = TM.getNullPointerValue(DestAS);
4572       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4573       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4574       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4575 
4576       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4577                          NonNull, Ptr, SegmentNullPtr);
4578     }
4579   }
4580 
4581   // local/private -> flat
4582   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4583     unsigned SrcAS = ASC->getSrcAddressSpace();
4584 
4585     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4586         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4587       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4588       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4589 
4590       SDValue NonNull
4591         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4592 
4593       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4594       SDValue CvtPtr
4595         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4596 
4597       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4598                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4599                          FlatNullPtr);
4600     }
4601   }
4602 
4603   // global <-> flat are no-ops and never emitted.
4604 
4605   const MachineFunction &MF = DAG.getMachineFunction();
4606   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4607     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4608   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4609 
4610   return DAG.getUNDEF(ASC->getValueType(0));
4611 }
4612 
4613 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4614 // the small vector and inserting them into the big vector. That is better than
4615 // the default expansion of doing it via a stack slot. Even though the use of
4616 // the stack slot would be optimized away afterwards, the stack slot itself
4617 // remains.
4618 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4619                                                 SelectionDAG &DAG) const {
4620   SDValue Vec = Op.getOperand(0);
4621   SDValue Ins = Op.getOperand(1);
4622   SDValue Idx = Op.getOperand(2);
4623   EVT VecVT = Vec.getValueType();
4624   EVT InsVT = Ins.getValueType();
4625   EVT EltVT = VecVT.getVectorElementType();
4626   unsigned InsNumElts = InsVT.getVectorNumElements();
4627   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4628   SDLoc SL(Op);
4629 
4630   for (unsigned I = 0; I != InsNumElts; ++I) {
4631     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4632                               DAG.getConstant(I, SL, MVT::i32));
4633     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4634                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
4635   }
4636   return Vec;
4637 }
4638 
4639 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4640                                                  SelectionDAG &DAG) const {
4641   SDValue Vec = Op.getOperand(0);
4642   SDValue InsVal = Op.getOperand(1);
4643   SDValue Idx = Op.getOperand(2);
4644   EVT VecVT = Vec.getValueType();
4645   EVT EltVT = VecVT.getVectorElementType();
4646   unsigned VecSize = VecVT.getSizeInBits();
4647   unsigned EltSize = EltVT.getSizeInBits();
4648 
4649 
4650   assert(VecSize <= 64);
4651 
4652   unsigned NumElts = VecVT.getVectorNumElements();
4653   SDLoc SL(Op);
4654   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4655 
4656   if (NumElts == 4 && EltSize == 16 && KIdx) {
4657     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4658 
4659     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4660                                  DAG.getConstant(0, SL, MVT::i32));
4661     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4662                                  DAG.getConstant(1, SL, MVT::i32));
4663 
4664     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4665     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4666 
4667     unsigned Idx = KIdx->getZExtValue();
4668     bool InsertLo = Idx < 2;
4669     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4670       InsertLo ? LoVec : HiVec,
4671       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4672       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4673 
4674     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4675 
4676     SDValue Concat = InsertLo ?
4677       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4678       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4679 
4680     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4681   }
4682 
4683   if (isa<ConstantSDNode>(Idx))
4684     return SDValue();
4685 
4686   MVT IntVT = MVT::getIntegerVT(VecSize);
4687 
4688   // Avoid stack access for dynamic indexing.
4689   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4690 
4691   // Create a congruent vector with the target value in each element so that
4692   // the required element can be masked and ORed into the target vector.
4693   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4694                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
4695 
4696   assert(isPowerOf2_32(EltSize));
4697   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4698 
4699   // Convert vector index to bit-index.
4700   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4701 
4702   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4703   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4704                             DAG.getConstant(0xffff, SL, IntVT),
4705                             ScaledIdx);
4706 
4707   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4708   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4709                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4710 
4711   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4712   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4713 }
4714 
4715 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4716                                                   SelectionDAG &DAG) const {
4717   SDLoc SL(Op);
4718 
4719   EVT ResultVT = Op.getValueType();
4720   SDValue Vec = Op.getOperand(0);
4721   SDValue Idx = Op.getOperand(1);
4722   EVT VecVT = Vec.getValueType();
4723   unsigned VecSize = VecVT.getSizeInBits();
4724   EVT EltVT = VecVT.getVectorElementType();
4725   assert(VecSize <= 64);
4726 
4727   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4728 
4729   // Make sure we do any optimizations that will make it easier to fold
4730   // source modifiers before obscuring it with bit operations.
4731 
4732   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4733   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4734     return Combined;
4735 
4736   unsigned EltSize = EltVT.getSizeInBits();
4737   assert(isPowerOf2_32(EltSize));
4738 
4739   MVT IntVT = MVT::getIntegerVT(VecSize);
4740   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4741 
4742   // Convert vector index to bit-index (* EltSize)
4743   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4744 
4745   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4746   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4747 
4748   if (ResultVT == MVT::f16) {
4749     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4750     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4751   }
4752 
4753   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4754 }
4755 
4756 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
4757   assert(Elt % 2 == 0);
4758   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
4759 }
4760 
4761 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4762                                               SelectionDAG &DAG) const {
4763   SDLoc SL(Op);
4764   EVT ResultVT = Op.getValueType();
4765   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
4766 
4767   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
4768   EVT EltVT = PackVT.getVectorElementType();
4769   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
4770 
4771   // vector_shuffle <0,1,6,7> lhs, rhs
4772   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
4773   //
4774   // vector_shuffle <6,7,2,3> lhs, rhs
4775   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
4776   //
4777   // vector_shuffle <6,7,0,1> lhs, rhs
4778   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
4779 
4780   // Avoid scalarizing when both halves are reading from consecutive elements.
4781   SmallVector<SDValue, 4> Pieces;
4782   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
4783     if (elementPairIsContiguous(SVN->getMask(), I)) {
4784       const int Idx = SVN->getMaskElt(I);
4785       int VecIdx = Idx < SrcNumElts ? 0 : 1;
4786       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
4787       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
4788                                     PackVT, SVN->getOperand(VecIdx),
4789                                     DAG.getConstant(EltIdx, SL, MVT::i32));
4790       Pieces.push_back(SubVec);
4791     } else {
4792       const int Idx0 = SVN->getMaskElt(I);
4793       const int Idx1 = SVN->getMaskElt(I + 1);
4794       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
4795       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
4796       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
4797       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
4798 
4799       SDValue Vec0 = SVN->getOperand(VecIdx0);
4800       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4801                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
4802 
4803       SDValue Vec1 = SVN->getOperand(VecIdx1);
4804       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4805                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
4806       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
4807     }
4808   }
4809 
4810   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
4811 }
4812 
4813 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4814                                             SelectionDAG &DAG) const {
4815   SDLoc SL(Op);
4816   EVT VT = Op.getValueType();
4817 
4818   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4819     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4820 
4821     // Turn into pair of packed build_vectors.
4822     // TODO: Special case for constants that can be materialized with s_mov_b64.
4823     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4824                                     { Op.getOperand(0), Op.getOperand(1) });
4825     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4826                                     { Op.getOperand(2), Op.getOperand(3) });
4827 
4828     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4829     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4830 
4831     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4832     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4833   }
4834 
4835   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4836   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
4837 
4838   SDValue Lo = Op.getOperand(0);
4839   SDValue Hi = Op.getOperand(1);
4840 
4841   // Avoid adding defined bits with the zero_extend.
4842   if (Hi.isUndef()) {
4843     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4844     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
4845     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
4846   }
4847 
4848   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4849   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4850 
4851   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4852                               DAG.getConstant(16, SL, MVT::i32));
4853   if (Lo.isUndef())
4854     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
4855 
4856   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4857   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4858 
4859   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4860   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4861 }
4862 
4863 bool
4864 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4865   // We can fold offsets for anything that doesn't require a GOT relocation.
4866   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4867           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4868           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4869          !shouldEmitGOTReloc(GA->getGlobal());
4870 }
4871 
4872 static SDValue
4873 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4874                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
4875                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
4876   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4877   // lowered to the following code sequence:
4878   //
4879   // For constant address space:
4880   //   s_getpc_b64 s[0:1]
4881   //   s_add_u32 s0, s0, $symbol
4882   //   s_addc_u32 s1, s1, 0
4883   //
4884   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4885   //   a fixup or relocation is emitted to replace $symbol with a literal
4886   //   constant, which is a pc-relative offset from the encoding of the $symbol
4887   //   operand to the global variable.
4888   //
4889   // For global address space:
4890   //   s_getpc_b64 s[0:1]
4891   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4892   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4893   //
4894   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4895   //   fixups or relocations are emitted to replace $symbol@*@lo and
4896   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
4897   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
4898   //   operand to the global variable.
4899   //
4900   // What we want here is an offset from the value returned by s_getpc
4901   // (which is the address of the s_add_u32 instruction) to the global
4902   // variable, but since the encoding of $symbol starts 4 bytes after the start
4903   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
4904   // small. This requires us to add 4 to the global variable offset in order to
4905   // compute the correct address.
4906   unsigned LoFlags = GAFlags;
4907   if (LoFlags == SIInstrInfo::MO_NONE)
4908     LoFlags = SIInstrInfo::MO_REL32;
4909   SDValue PtrLo =
4910       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, LoFlags);
4911   SDValue PtrHi;
4912   if (GAFlags == SIInstrInfo::MO_NONE) {
4913     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
4914   } else {
4915     PtrHi =
4916         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
4917   }
4918   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
4919 }
4920 
4921 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
4922                                              SDValue Op,
4923                                              SelectionDAG &DAG) const {
4924   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
4925   const GlobalValue *GV = GSD->getGlobal();
4926   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
4927        (!GV->hasExternalLinkage() ||
4928         getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4929         getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) ||
4930       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
4931       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
4932     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
4933 
4934   SDLoc DL(GSD);
4935   EVT PtrVT = Op.getValueType();
4936 
4937   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
4938     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
4939                                             SIInstrInfo::MO_ABS32_LO);
4940     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
4941   }
4942 
4943   if (shouldEmitFixup(GV))
4944     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
4945   else if (shouldEmitPCReloc(GV))
4946     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
4947                                    SIInstrInfo::MO_REL32);
4948 
4949   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
4950                                             SIInstrInfo::MO_GOTPCREL32);
4951 
4952   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
4953   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
4954   const DataLayout &DataLayout = DAG.getDataLayout();
4955   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
4956   MachinePointerInfo PtrInfo
4957     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
4958 
4959   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
4960                      MachineMemOperand::MODereferenceable |
4961                          MachineMemOperand::MOInvariant);
4962 }
4963 
4964 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
4965                                    const SDLoc &DL, SDValue V) const {
4966   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
4967   // the destination register.
4968   //
4969   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
4970   // so we will end up with redundant moves to m0.
4971   //
4972   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
4973 
4974   // A Null SDValue creates a glue result.
4975   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
4976                                   V, Chain);
4977   return SDValue(M0, 0);
4978 }
4979 
4980 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
4981                                                  SDValue Op,
4982                                                  MVT VT,
4983                                                  unsigned Offset) const {
4984   SDLoc SL(Op);
4985   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
4986                                            DAG.getEntryNode(), Offset, 4, false);
4987   // The local size values will have the hi 16-bits as zero.
4988   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
4989                      DAG.getValueType(VT));
4990 }
4991 
4992 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4993                                         EVT VT) {
4994   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4995                                       "non-hsa intrinsic with hsa target",
4996                                       DL.getDebugLoc());
4997   DAG.getContext()->diagnose(BadIntrin);
4998   return DAG.getUNDEF(VT);
4999 }
5000 
5001 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5002                                          EVT VT) {
5003   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5004                                       "intrinsic not supported on subtarget",
5005                                       DL.getDebugLoc());
5006   DAG.getContext()->diagnose(BadIntrin);
5007   return DAG.getUNDEF(VT);
5008 }
5009 
5010 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5011                                     ArrayRef<SDValue> Elts) {
5012   assert(!Elts.empty());
5013   MVT Type;
5014   unsigned NumElts;
5015 
5016   if (Elts.size() == 1) {
5017     Type = MVT::f32;
5018     NumElts = 1;
5019   } else if (Elts.size() == 2) {
5020     Type = MVT::v2f32;
5021     NumElts = 2;
5022   } else if (Elts.size() <= 4) {
5023     Type = MVT::v4f32;
5024     NumElts = 4;
5025   } else if (Elts.size() <= 8) {
5026     Type = MVT::v8f32;
5027     NumElts = 8;
5028   } else {
5029     assert(Elts.size() <= 16);
5030     Type = MVT::v16f32;
5031     NumElts = 16;
5032   }
5033 
5034   SmallVector<SDValue, 16> VecElts(NumElts);
5035   for (unsigned i = 0; i < Elts.size(); ++i) {
5036     SDValue Elt = Elts[i];
5037     if (Elt.getValueType() != MVT::f32)
5038       Elt = DAG.getBitcast(MVT::f32, Elt);
5039     VecElts[i] = Elt;
5040   }
5041   for (unsigned i = Elts.size(); i < NumElts; ++i)
5042     VecElts[i] = DAG.getUNDEF(MVT::f32);
5043 
5044   if (NumElts == 1)
5045     return VecElts[0];
5046   return DAG.getBuildVector(Type, DL, VecElts);
5047 }
5048 
5049 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5050                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5051   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5052 
5053   uint64_t Value = CachePolicyConst->getZExtValue();
5054   SDLoc DL(CachePolicy);
5055   if (GLC) {
5056     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5057     Value &= ~(uint64_t)0x1;
5058   }
5059   if (SLC) {
5060     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5061     Value &= ~(uint64_t)0x2;
5062   }
5063   if (DLC) {
5064     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5065     Value &= ~(uint64_t)0x4;
5066   }
5067 
5068   return Value == 0;
5069 }
5070 
5071 // Re-construct the required return value for a image load intrinsic.
5072 // This is more complicated due to the optional use TexFailCtrl which means the required
5073 // return type is an aggregate
5074 static SDValue constructRetValue(SelectionDAG &DAG,
5075                                  MachineSDNode *Result,
5076                                  ArrayRef<EVT> ResultTypes,
5077                                  bool IsTexFail, bool Unpacked, bool IsD16,
5078                                  int DMaskPop, int NumVDataDwords,
5079                                  const SDLoc &DL, LLVMContext &Context) {
5080   // Determine the required return type. This is the same regardless of IsTexFail flag
5081   EVT ReqRetVT = ResultTypes[0];
5082   EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT;
5083   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5084   EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT;
5085   EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts)
5086                                            : AdjEltVT
5087                        : ReqRetVT;
5088 
5089   // Extract data part of the result
5090   // Bitcast the result to the same type as the required return type
5091   int NumElts;
5092   if (IsD16 && !Unpacked)
5093     NumElts = NumVDataDwords << 1;
5094   else
5095     NumElts = NumVDataDwords;
5096 
5097   EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts)
5098                            : AdjEltVT;
5099 
5100   // Special case for v6f16. Rather than add support for this, use v3i32 to
5101   // extract the data elements
5102   bool V6F16Special = false;
5103   if (NumElts == 6) {
5104     CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2);
5105     DMaskPop >>= 1;
5106     ReqRetNumElts >>= 1;
5107     V6F16Special = true;
5108     AdjVT = MVT::v2i32;
5109   }
5110 
5111   SDValue N = SDValue(Result, 0);
5112   SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N);
5113 
5114   // Iterate over the result
5115   SmallVector<SDValue, 4> BVElts;
5116 
5117   if (CastVT.isVector()) {
5118     DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop);
5119   } else {
5120     BVElts.push_back(CastRes);
5121   }
5122   int ExtraElts = ReqRetNumElts - DMaskPop;
5123   while(ExtraElts--)
5124     BVElts.push_back(DAG.getUNDEF(AdjEltVT));
5125 
5126   SDValue PreTFCRes;
5127   if (ReqRetNumElts > 1) {
5128     SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts);
5129     if (IsD16 && Unpacked)
5130       PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked);
5131     else
5132       PreTFCRes = NewVec;
5133   } else {
5134     PreTFCRes = BVElts[0];
5135   }
5136 
5137   if (V6F16Special)
5138     PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes);
5139 
5140   if (!IsTexFail) {
5141     if (Result->getNumValues() > 1)
5142       return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL);
5143     else
5144       return PreTFCRes;
5145   }
5146 
5147   // Extract the TexFail result and insert into aggregate return
5148   SmallVector<SDValue, 1> TFCElt;
5149   DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1);
5150   SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]);
5151   return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL);
5152 }
5153 
5154 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5155                          SDValue *LWE, bool &IsTexFail) {
5156   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5157 
5158   uint64_t Value = TexFailCtrlConst->getZExtValue();
5159   if (Value) {
5160     IsTexFail = true;
5161   }
5162 
5163   SDLoc DL(TexFailCtrlConst);
5164   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5165   Value &= ~(uint64_t)0x1;
5166   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5167   Value &= ~(uint64_t)0x2;
5168 
5169   return Value == 0;
5170 }
5171 
5172 SDValue SITargetLowering::lowerImage(SDValue Op,
5173                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5174                                      SelectionDAG &DAG) const {
5175   SDLoc DL(Op);
5176   MachineFunction &MF = DAG.getMachineFunction();
5177   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5178   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5179       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5180   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5181   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5182       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5183   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5184       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5185   unsigned IntrOpcode = Intr->BaseOpcode;
5186   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5187 
5188   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5189   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5190   bool IsD16 = false;
5191   bool IsA16 = false;
5192   SDValue VData;
5193   int NumVDataDwords;
5194   bool AdjustRetType = false;
5195 
5196   unsigned AddrIdx; // Index of first address argument
5197   unsigned DMask;
5198   unsigned DMaskLanes = 0;
5199 
5200   if (BaseOpcode->Atomic) {
5201     VData = Op.getOperand(2);
5202 
5203     bool Is64Bit = VData.getValueType() == MVT::i64;
5204     if (BaseOpcode->AtomicX2) {
5205       SDValue VData2 = Op.getOperand(3);
5206       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5207                                  {VData, VData2});
5208       if (Is64Bit)
5209         VData = DAG.getBitcast(MVT::v4i32, VData);
5210 
5211       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5212       DMask = Is64Bit ? 0xf : 0x3;
5213       NumVDataDwords = Is64Bit ? 4 : 2;
5214       AddrIdx = 4;
5215     } else {
5216       DMask = Is64Bit ? 0x3 : 0x1;
5217       NumVDataDwords = Is64Bit ? 2 : 1;
5218       AddrIdx = 3;
5219     }
5220   } else {
5221     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5222     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5223     DMask = DMaskConst->getZExtValue();
5224     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5225 
5226     if (BaseOpcode->Store) {
5227       VData = Op.getOperand(2);
5228 
5229       MVT StoreVT = VData.getSimpleValueType();
5230       if (StoreVT.getScalarType() == MVT::f16) {
5231         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5232           return Op; // D16 is unsupported for this instruction
5233 
5234         IsD16 = true;
5235         VData = handleD16VData(VData, DAG);
5236       }
5237 
5238       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5239     } else {
5240       // Work out the num dwords based on the dmask popcount and underlying type
5241       // and whether packing is supported.
5242       MVT LoadVT = ResultTypes[0].getSimpleVT();
5243       if (LoadVT.getScalarType() == MVT::f16) {
5244         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5245           return Op; // D16 is unsupported for this instruction
5246 
5247         IsD16 = true;
5248       }
5249 
5250       // Confirm that the return type is large enough for the dmask specified
5251       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5252           (!LoadVT.isVector() && DMaskLanes > 1))
5253           return Op;
5254 
5255       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5256         NumVDataDwords = (DMaskLanes + 1) / 2;
5257       else
5258         NumVDataDwords = DMaskLanes;
5259 
5260       AdjustRetType = true;
5261     }
5262 
5263     AddrIdx = DMaskIdx + 1;
5264   }
5265 
5266   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5267   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5268   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5269   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5270                        NumCoords + NumLCM;
5271   unsigned NumMIVAddrs = NumVAddrs;
5272 
5273   SmallVector<SDValue, 4> VAddrs;
5274 
5275   // Optimize _L to _LZ when _L is zero
5276   if (LZMappingInfo) {
5277     if (auto ConstantLod =
5278          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5279       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5280         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5281         NumMIVAddrs--;               // remove 'lod'
5282       }
5283     }
5284   }
5285 
5286   // Optimize _mip away, when 'lod' is zero
5287   if (MIPMappingInfo) {
5288     if (auto ConstantLod =
5289          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5290       if (ConstantLod->isNullValue()) {
5291         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5292         NumMIVAddrs--;               // remove 'lod'
5293       }
5294     }
5295   }
5296 
5297   // Check for 16 bit addresses and pack if true.
5298   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5299   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5300   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5301   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) &&
5302       ST->hasFeature(AMDGPU::FeatureR128A16)) {
5303     IsA16 = true;
5304     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5305     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5306       SDValue AddrLo, AddrHi;
5307       // Push back extra arguments.
5308       if (i < DimIdx) {
5309         AddrLo = Op.getOperand(i);
5310       } else {
5311         AddrLo = Op.getOperand(i);
5312         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5313         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5314         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5315             ((NumGradients / 2) % 2 == 1 &&
5316             (i == DimIdx + (NumGradients / 2) - 1 ||
5317              i == DimIdx + NumGradients - 1))) {
5318           AddrHi = DAG.getUNDEF(MVT::f16);
5319         } else {
5320           AddrHi = Op.getOperand(i + 1);
5321           i++;
5322         }
5323         AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT,
5324                              {AddrLo, AddrHi});
5325         AddrLo = DAG.getBitcast(MVT::i32, AddrLo);
5326       }
5327       VAddrs.push_back(AddrLo);
5328     }
5329   } else {
5330     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5331       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5332   }
5333 
5334   // If the register allocator cannot place the address registers contiguously
5335   // without introducing moves, then using the non-sequential address encoding
5336   // is always preferable, since it saves VALU instructions and is usually a
5337   // wash in terms of code size or even better.
5338   //
5339   // However, we currently have no way of hinting to the register allocator that
5340   // MIMG addresses should be placed contiguously when it is possible to do so,
5341   // so force non-NSA for the common 2-address case as a heuristic.
5342   //
5343   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5344   // allocation when possible.
5345   bool UseNSA =
5346       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5347   SDValue VAddr;
5348   if (!UseNSA)
5349     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5350 
5351   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5352   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5353   unsigned CtrlIdx; // Index of texfailctrl argument
5354   SDValue Unorm;
5355   if (!BaseOpcode->Sampler) {
5356     Unorm = True;
5357     CtrlIdx = AddrIdx + NumVAddrs + 1;
5358   } else {
5359     auto UnormConst =
5360         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5361 
5362     Unorm = UnormConst->getZExtValue() ? True : False;
5363     CtrlIdx = AddrIdx + NumVAddrs + 3;
5364   }
5365 
5366   SDValue TFE;
5367   SDValue LWE;
5368   SDValue TexFail = Op.getOperand(CtrlIdx);
5369   bool IsTexFail = false;
5370   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5371     return Op;
5372 
5373   if (IsTexFail) {
5374     if (!DMaskLanes) {
5375       // Expecting to get an error flag since TFC is on - and dmask is 0
5376       // Force dmask to be at least 1 otherwise the instruction will fail
5377       DMask = 0x1;
5378       DMaskLanes = 1;
5379       NumVDataDwords = 1;
5380     }
5381     NumVDataDwords += 1;
5382     AdjustRetType = true;
5383   }
5384 
5385   // Has something earlier tagged that the return type needs adjusting
5386   // This happens if the instruction is a load or has set TexFailCtrl flags
5387   if (AdjustRetType) {
5388     // NumVDataDwords reflects the true number of dwords required in the return type
5389     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5390       // This is a no-op load. This can be eliminated
5391       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5392       if (isa<MemSDNode>(Op))
5393         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5394       return Undef;
5395     }
5396 
5397     EVT NewVT = NumVDataDwords > 1 ?
5398                   EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords)
5399                 : MVT::f32;
5400 
5401     ResultTypes[0] = NewVT;
5402     if (ResultTypes.size() == 3) {
5403       // Original result was aggregate type used for TexFailCtrl results
5404       // The actual instruction returns as a vector type which has now been
5405       // created. Remove the aggregate result.
5406       ResultTypes.erase(&ResultTypes[1]);
5407     }
5408   }
5409 
5410   SDValue GLC;
5411   SDValue SLC;
5412   SDValue DLC;
5413   if (BaseOpcode->Atomic) {
5414     GLC = True; // TODO no-return optimization
5415     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5416                           IsGFX10 ? &DLC : nullptr))
5417       return Op;
5418   } else {
5419     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5420                           IsGFX10 ? &DLC : nullptr))
5421       return Op;
5422   }
5423 
5424   SmallVector<SDValue, 26> Ops;
5425   if (BaseOpcode->Store || BaseOpcode->Atomic)
5426     Ops.push_back(VData); // vdata
5427   if (UseNSA) {
5428     for (const SDValue &Addr : VAddrs)
5429       Ops.push_back(Addr);
5430   } else {
5431     Ops.push_back(VAddr);
5432   }
5433   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5434   if (BaseOpcode->Sampler)
5435     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5436   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5437   if (IsGFX10)
5438     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5439   Ops.push_back(Unorm);
5440   if (IsGFX10)
5441     Ops.push_back(DLC);
5442   Ops.push_back(GLC);
5443   Ops.push_back(SLC);
5444   Ops.push_back(IsA16 &&  // a16 or r128
5445                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5446   Ops.push_back(TFE); // tfe
5447   Ops.push_back(LWE); // lwe
5448   if (!IsGFX10)
5449     Ops.push_back(DimInfo->DA ? True : False);
5450   if (BaseOpcode->HasD16)
5451     Ops.push_back(IsD16 ? True : False);
5452   if (isa<MemSDNode>(Op))
5453     Ops.push_back(Op.getOperand(0)); // chain
5454 
5455   int NumVAddrDwords =
5456       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5457   int Opcode = -1;
5458 
5459   if (IsGFX10) {
5460     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5461                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5462                                           : AMDGPU::MIMGEncGfx10Default,
5463                                    NumVDataDwords, NumVAddrDwords);
5464   } else {
5465     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5466       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5467                                      NumVDataDwords, NumVAddrDwords);
5468     if (Opcode == -1)
5469       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5470                                      NumVDataDwords, NumVAddrDwords);
5471   }
5472   assert(Opcode != -1);
5473 
5474   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5475   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5476     MachineMemOperand *MemRef = MemOp->getMemOperand();
5477     DAG.setNodeMemRefs(NewNode, {MemRef});
5478   }
5479 
5480   if (BaseOpcode->AtomicX2) {
5481     SmallVector<SDValue, 1> Elt;
5482     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5483     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5484   } else if (!BaseOpcode->Store) {
5485     return constructRetValue(DAG, NewNode,
5486                              OrigResultTypes, IsTexFail,
5487                              Subtarget->hasUnpackedD16VMem(), IsD16,
5488                              DMaskLanes, NumVDataDwords, DL,
5489                              *DAG.getContext());
5490   }
5491 
5492   return SDValue(NewNode, 0);
5493 }
5494 
5495 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5496                                        SDValue Offset, SDValue GLC, SDValue DLC,
5497                                        SelectionDAG &DAG) const {
5498   MachineFunction &MF = DAG.getMachineFunction();
5499   MachineMemOperand *MMO = MF.getMachineMemOperand(
5500       MachinePointerInfo(),
5501       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5502           MachineMemOperand::MOInvariant,
5503       VT.getStoreSize(), VT.getStoreSize());
5504 
5505   if (!Offset->isDivergent()) {
5506     SDValue Ops[] = {
5507         Rsrc,
5508         Offset, // Offset
5509         GLC,
5510         DLC,
5511     };
5512     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5513                                    DAG.getVTList(VT), Ops, VT, MMO);
5514   }
5515 
5516   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5517   // assume that the buffer is unswizzled.
5518   SmallVector<SDValue, 4> Loads;
5519   unsigned NumLoads = 1;
5520   MVT LoadVT = VT.getSimpleVT();
5521   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5522   assert((LoadVT.getScalarType() == MVT::i32 ||
5523           LoadVT.getScalarType() == MVT::f32) &&
5524          isPowerOf2_32(NumElts));
5525 
5526   if (NumElts == 8 || NumElts == 16) {
5527     NumLoads = NumElts == 16 ? 4 : 2;
5528     LoadVT = MVT::v4i32;
5529   }
5530 
5531   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5532   unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue();
5533   SDValue Ops[] = {
5534       DAG.getEntryNode(),                         // Chain
5535       Rsrc,                                       // rsrc
5536       DAG.getConstant(0, DL, MVT::i32),           // vindex
5537       {},                                         // voffset
5538       {},                                         // soffset
5539       {},                                         // offset
5540       DAG.getConstant(CachePolicy, DL, MVT::i32), // cachepolicy
5541       DAG.getConstant(0, DL, MVT::i1),            // idxen
5542   };
5543 
5544   // Use the alignment to ensure that the required offsets will fit into the
5545   // immediate offsets.
5546   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5547 
5548   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5549   for (unsigned i = 0; i < NumLoads; ++i) {
5550     Ops[5] = DAG.getConstant(InstOffset + 16 * i, DL, MVT::i32);
5551     Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList,
5552                                             Ops, LoadVT, MMO));
5553   }
5554 
5555   if (VT == MVT::v8i32 || VT == MVT::v16i32)
5556     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5557 
5558   return Loads[0];
5559 }
5560 
5561 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5562                                                   SelectionDAG &DAG) const {
5563   MachineFunction &MF = DAG.getMachineFunction();
5564   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5565 
5566   EVT VT = Op.getValueType();
5567   SDLoc DL(Op);
5568   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5569 
5570   // TODO: Should this propagate fast-math-flags?
5571 
5572   switch (IntrinsicID) {
5573   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5574     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5575       return emitNonHSAIntrinsicError(DAG, DL, VT);
5576     return getPreloadedValue(DAG, *MFI, VT,
5577                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5578   }
5579   case Intrinsic::amdgcn_dispatch_ptr:
5580   case Intrinsic::amdgcn_queue_ptr: {
5581     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5582       DiagnosticInfoUnsupported BadIntrin(
5583           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5584           DL.getDebugLoc());
5585       DAG.getContext()->diagnose(BadIntrin);
5586       return DAG.getUNDEF(VT);
5587     }
5588 
5589     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5590       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5591     return getPreloadedValue(DAG, *MFI, VT, RegID);
5592   }
5593   case Intrinsic::amdgcn_implicitarg_ptr: {
5594     if (MFI->isEntryFunction())
5595       return getImplicitArgPtr(DAG, DL);
5596     return getPreloadedValue(DAG, *MFI, VT,
5597                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5598   }
5599   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5600     return getPreloadedValue(DAG, *MFI, VT,
5601                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5602   }
5603   case Intrinsic::amdgcn_dispatch_id: {
5604     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5605   }
5606   case Intrinsic::amdgcn_rcp:
5607     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5608   case Intrinsic::amdgcn_rsq:
5609     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5610   case Intrinsic::amdgcn_rsq_legacy:
5611     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5612       return emitRemovedIntrinsicError(DAG, DL, VT);
5613 
5614     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5615   case Intrinsic::amdgcn_rcp_legacy:
5616     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5617       return emitRemovedIntrinsicError(DAG, DL, VT);
5618     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5619   case Intrinsic::amdgcn_rsq_clamp: {
5620     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5621       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5622 
5623     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5624     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5625     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5626 
5627     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5628     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5629                               DAG.getConstantFP(Max, DL, VT));
5630     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5631                        DAG.getConstantFP(Min, DL, VT));
5632   }
5633   case Intrinsic::r600_read_ngroups_x:
5634     if (Subtarget->isAmdHsaOS())
5635       return emitNonHSAIntrinsicError(DAG, DL, VT);
5636 
5637     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5638                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
5639   case Intrinsic::r600_read_ngroups_y:
5640     if (Subtarget->isAmdHsaOS())
5641       return emitNonHSAIntrinsicError(DAG, DL, VT);
5642 
5643     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5644                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5645   case Intrinsic::r600_read_ngroups_z:
5646     if (Subtarget->isAmdHsaOS())
5647       return emitNonHSAIntrinsicError(DAG, DL, VT);
5648 
5649     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5650                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5651   case Intrinsic::r600_read_global_size_x:
5652     if (Subtarget->isAmdHsaOS())
5653       return emitNonHSAIntrinsicError(DAG, DL, VT);
5654 
5655     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5656                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5657   case Intrinsic::r600_read_global_size_y:
5658     if (Subtarget->isAmdHsaOS())
5659       return emitNonHSAIntrinsicError(DAG, DL, VT);
5660 
5661     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5662                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5663   case Intrinsic::r600_read_global_size_z:
5664     if (Subtarget->isAmdHsaOS())
5665       return emitNonHSAIntrinsicError(DAG, DL, VT);
5666 
5667     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5668                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5669   case Intrinsic::r600_read_local_size_x:
5670     if (Subtarget->isAmdHsaOS())
5671       return emitNonHSAIntrinsicError(DAG, DL, VT);
5672 
5673     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5674                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
5675   case Intrinsic::r600_read_local_size_y:
5676     if (Subtarget->isAmdHsaOS())
5677       return emitNonHSAIntrinsicError(DAG, DL, VT);
5678 
5679     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5680                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
5681   case Intrinsic::r600_read_local_size_z:
5682     if (Subtarget->isAmdHsaOS())
5683       return emitNonHSAIntrinsicError(DAG, DL, VT);
5684 
5685     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5686                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
5687   case Intrinsic::amdgcn_workgroup_id_x:
5688   case Intrinsic::r600_read_tgid_x:
5689     return getPreloadedValue(DAG, *MFI, VT,
5690                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5691   case Intrinsic::amdgcn_workgroup_id_y:
5692   case Intrinsic::r600_read_tgid_y:
5693     return getPreloadedValue(DAG, *MFI, VT,
5694                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5695   case Intrinsic::amdgcn_workgroup_id_z:
5696   case Intrinsic::r600_read_tgid_z:
5697     return getPreloadedValue(DAG, *MFI, VT,
5698                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5699   case Intrinsic::amdgcn_workitem_id_x:
5700   case Intrinsic::r600_read_tidig_x:
5701     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5702                           SDLoc(DAG.getEntryNode()),
5703                           MFI->getArgInfo().WorkItemIDX);
5704   case Intrinsic::amdgcn_workitem_id_y:
5705   case Intrinsic::r600_read_tidig_y:
5706     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5707                           SDLoc(DAG.getEntryNode()),
5708                           MFI->getArgInfo().WorkItemIDY);
5709   case Intrinsic::amdgcn_workitem_id_z:
5710   case Intrinsic::r600_read_tidig_z:
5711     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5712                           SDLoc(DAG.getEntryNode()),
5713                           MFI->getArgInfo().WorkItemIDZ);
5714   case Intrinsic::amdgcn_wavefrontsize:
5715     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
5716                            SDLoc(Op), MVT::i32);
5717   case Intrinsic::amdgcn_s_buffer_load: {
5718     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5719     SDValue GLC;
5720     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5721     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5722                           IsGFX10 ? &DLC : nullptr))
5723       return Op;
5724     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC,
5725                         DAG);
5726   }
5727   case Intrinsic::amdgcn_fdiv_fast:
5728     return lowerFDIV_FAST(Op, DAG);
5729   case Intrinsic::amdgcn_interp_mov: {
5730     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5731     SDValue Glue = M0.getValue(1);
5732     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
5733                        Op.getOperand(2), Op.getOperand(3), Glue);
5734   }
5735   case Intrinsic::amdgcn_interp_p1: {
5736     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5737     SDValue Glue = M0.getValue(1);
5738     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
5739                        Op.getOperand(2), Op.getOperand(3), Glue);
5740   }
5741   case Intrinsic::amdgcn_interp_p2: {
5742     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5743     SDValue Glue = SDValue(M0.getNode(), 1);
5744     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
5745                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
5746                        Glue);
5747   }
5748   case Intrinsic::amdgcn_interp_p1_f16: {
5749     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5750     SDValue Glue = M0.getValue(1);
5751     if (getSubtarget()->getLDSBankCount() == 16) {
5752       // 16 bank LDS
5753       SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
5754                               DAG.getConstant(2, DL, MVT::i32), // P0
5755                               Op.getOperand(2), // Attrchan
5756                               Op.getOperand(3), // Attr
5757                               Glue);
5758       SDValue Ops[] = {
5759         Op.getOperand(1), // Src0
5760         Op.getOperand(2), // Attrchan
5761         Op.getOperand(3), // Attr
5762         DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5763         S, // Src2 - holds two f16 values selected by high
5764         DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers
5765         Op.getOperand(4), // high
5766         DAG.getConstant(0, DL, MVT::i1), // $clamp
5767         DAG.getConstant(0, DL, MVT::i32) // $omod
5768       };
5769       return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops);
5770     } else {
5771       // 32 bank LDS
5772       SDValue Ops[] = {
5773         Op.getOperand(1), // Src0
5774         Op.getOperand(2), // Attrchan
5775         Op.getOperand(3), // Attr
5776         DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5777         Op.getOperand(4), // high
5778         DAG.getConstant(0, DL, MVT::i1), // $clamp
5779         DAG.getConstant(0, DL, MVT::i32), // $omod
5780         Glue
5781       };
5782       return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops);
5783     }
5784   }
5785   case Intrinsic::amdgcn_interp_p2_f16: {
5786     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6));
5787     SDValue Glue = SDValue(M0.getNode(), 1);
5788     SDValue Ops[] = {
5789       Op.getOperand(2), // Src0
5790       Op.getOperand(3), // Attrchan
5791       Op.getOperand(4), // Attr
5792       DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5793       Op.getOperand(1), // Src2
5794       DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers
5795       Op.getOperand(5), // high
5796       DAG.getConstant(0, DL, MVT::i1), // $clamp
5797       Glue
5798     };
5799     return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops);
5800   }
5801   case Intrinsic::amdgcn_sin:
5802     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5803 
5804   case Intrinsic::amdgcn_cos:
5805     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5806 
5807   case Intrinsic::amdgcn_log_clamp: {
5808     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5809       return SDValue();
5810 
5811     DiagnosticInfoUnsupported BadIntrin(
5812       MF.getFunction(), "intrinsic not supported on subtarget",
5813       DL.getDebugLoc());
5814       DAG.getContext()->diagnose(BadIntrin);
5815       return DAG.getUNDEF(VT);
5816   }
5817   case Intrinsic::amdgcn_ldexp:
5818     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5819                        Op.getOperand(1), Op.getOperand(2));
5820 
5821   case Intrinsic::amdgcn_fract:
5822     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5823 
5824   case Intrinsic::amdgcn_class:
5825     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5826                        Op.getOperand(1), Op.getOperand(2));
5827   case Intrinsic::amdgcn_div_fmas:
5828     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5829                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5830                        Op.getOperand(4));
5831 
5832   case Intrinsic::amdgcn_div_fixup:
5833     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5834                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5835 
5836   case Intrinsic::amdgcn_trig_preop:
5837     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5838                        Op.getOperand(1), Op.getOperand(2));
5839   case Intrinsic::amdgcn_div_scale: {
5840     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5841 
5842     // Translate to the operands expected by the machine instruction. The
5843     // first parameter must be the same as the first instruction.
5844     SDValue Numerator = Op.getOperand(1);
5845     SDValue Denominator = Op.getOperand(2);
5846 
5847     // Note this order is opposite of the machine instruction's operations,
5848     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
5849     // intrinsic has the numerator as the first operand to match a normal
5850     // division operation.
5851 
5852     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
5853 
5854     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
5855                        Denominator, Numerator);
5856   }
5857   case Intrinsic::amdgcn_icmp: {
5858     // There is a Pat that handles this variant, so return it as-is.
5859     if (Op.getOperand(1).getValueType() == MVT::i1 &&
5860         Op.getConstantOperandVal(2) == 0 &&
5861         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
5862       return Op;
5863     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
5864   }
5865   case Intrinsic::amdgcn_fcmp: {
5866     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
5867   }
5868   case Intrinsic::amdgcn_fmed3:
5869     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
5870                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5871   case Intrinsic::amdgcn_fdot2:
5872     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
5873                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5874                        Op.getOperand(4));
5875   case Intrinsic::amdgcn_fmul_legacy:
5876     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
5877                        Op.getOperand(1), Op.getOperand(2));
5878   case Intrinsic::amdgcn_sffbh:
5879     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
5880   case Intrinsic::amdgcn_sbfe:
5881     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
5882                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5883   case Intrinsic::amdgcn_ubfe:
5884     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
5885                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5886   case Intrinsic::amdgcn_cvt_pkrtz:
5887   case Intrinsic::amdgcn_cvt_pknorm_i16:
5888   case Intrinsic::amdgcn_cvt_pknorm_u16:
5889   case Intrinsic::amdgcn_cvt_pk_i16:
5890   case Intrinsic::amdgcn_cvt_pk_u16: {
5891     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
5892     EVT VT = Op.getValueType();
5893     unsigned Opcode;
5894 
5895     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
5896       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
5897     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
5898       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5899     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
5900       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5901     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
5902       Opcode = AMDGPUISD::CVT_PK_I16_I32;
5903     else
5904       Opcode = AMDGPUISD::CVT_PK_U16_U32;
5905 
5906     if (isTypeLegal(VT))
5907       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
5908 
5909     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
5910                                Op.getOperand(1), Op.getOperand(2));
5911     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
5912   }
5913   case Intrinsic::amdgcn_wqm: {
5914     SDValue Src = Op.getOperand(1);
5915     return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
5916                    0);
5917   }
5918   case Intrinsic::amdgcn_wwm: {
5919     SDValue Src = Op.getOperand(1);
5920     return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
5921                    0);
5922   }
5923   case Intrinsic::amdgcn_fmad_ftz:
5924     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
5925                        Op.getOperand(2), Op.getOperand(3));
5926 
5927   case Intrinsic::amdgcn_if_break:
5928     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
5929                                       Op->getOperand(1), Op->getOperand(2)), 0);
5930 
5931   case Intrinsic::amdgcn_groupstaticsize: {
5932     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
5933     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
5934       return Op;
5935 
5936     const Module *M = MF.getFunction().getParent();
5937     const GlobalValue *GV =
5938         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
5939     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
5940                                             SIInstrInfo::MO_ABS32_LO);
5941     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
5942   }
5943   default:
5944     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5945             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5946       return lowerImage(Op, ImageDimIntr, DAG);
5947 
5948     return Op;
5949   }
5950 }
5951 
5952 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
5953                                                  SelectionDAG &DAG) const {
5954   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5955   SDLoc DL(Op);
5956 
5957   switch (IntrID) {
5958   case Intrinsic::amdgcn_ds_ordered_add:
5959   case Intrinsic::amdgcn_ds_ordered_swap: {
5960     MemSDNode *M = cast<MemSDNode>(Op);
5961     SDValue Chain = M->getOperand(0);
5962     SDValue M0 = M->getOperand(2);
5963     SDValue Value = M->getOperand(3);
5964     unsigned IndexOperand = M->getConstantOperandVal(7);
5965     unsigned WaveRelease = M->getConstantOperandVal(8);
5966     unsigned WaveDone = M->getConstantOperandVal(9);
5967     unsigned ShaderType;
5968     unsigned Instruction;
5969 
5970     unsigned OrderedCountIndex = IndexOperand & 0x3f;
5971     IndexOperand &= ~0x3f;
5972     unsigned CountDw = 0;
5973 
5974     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
5975       CountDw = (IndexOperand >> 24) & 0xf;
5976       IndexOperand &= ~(0xf << 24);
5977 
5978       if (CountDw < 1 || CountDw > 4) {
5979         report_fatal_error(
5980             "ds_ordered_count: dword count must be between 1 and 4");
5981       }
5982     }
5983 
5984     if (IndexOperand)
5985       report_fatal_error("ds_ordered_count: bad index operand");
5986 
5987     switch (IntrID) {
5988     case Intrinsic::amdgcn_ds_ordered_add:
5989       Instruction = 0;
5990       break;
5991     case Intrinsic::amdgcn_ds_ordered_swap:
5992       Instruction = 1;
5993       break;
5994     }
5995 
5996     if (WaveDone && !WaveRelease)
5997       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
5998 
5999     switch (DAG.getMachineFunction().getFunction().getCallingConv()) {
6000     case CallingConv::AMDGPU_CS:
6001     case CallingConv::AMDGPU_KERNEL:
6002       ShaderType = 0;
6003       break;
6004     case CallingConv::AMDGPU_PS:
6005       ShaderType = 1;
6006       break;
6007     case CallingConv::AMDGPU_VS:
6008       ShaderType = 2;
6009       break;
6010     case CallingConv::AMDGPU_GS:
6011       ShaderType = 3;
6012       break;
6013     default:
6014       report_fatal_error("ds_ordered_count unsupported for this calling conv");
6015     }
6016 
6017     unsigned Offset0 = OrderedCountIndex << 2;
6018     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6019                        (Instruction << 4);
6020 
6021     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6022       Offset1 |= (CountDw - 1) << 6;
6023 
6024     unsigned Offset = Offset0 | (Offset1 << 8);
6025 
6026     SDValue Ops[] = {
6027       Chain,
6028       Value,
6029       DAG.getTargetConstant(Offset, DL, MVT::i16),
6030       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6031     };
6032     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6033                                    M->getVTList(), Ops, M->getMemoryVT(),
6034                                    M->getMemOperand());
6035   }
6036   case Intrinsic::amdgcn_ds_fadd: {
6037     MemSDNode *M = cast<MemSDNode>(Op);
6038     unsigned Opc;
6039     switch (IntrID) {
6040     case Intrinsic::amdgcn_ds_fadd:
6041       Opc = ISD::ATOMIC_LOAD_FADD;
6042       break;
6043     }
6044 
6045     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6046                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6047                          M->getMemOperand());
6048   }
6049   case Intrinsic::amdgcn_atomic_inc:
6050   case Intrinsic::amdgcn_atomic_dec:
6051   case Intrinsic::amdgcn_ds_fmin:
6052   case Intrinsic::amdgcn_ds_fmax: {
6053     MemSDNode *M = cast<MemSDNode>(Op);
6054     unsigned Opc;
6055     switch (IntrID) {
6056     case Intrinsic::amdgcn_atomic_inc:
6057       Opc = AMDGPUISD::ATOMIC_INC;
6058       break;
6059     case Intrinsic::amdgcn_atomic_dec:
6060       Opc = AMDGPUISD::ATOMIC_DEC;
6061       break;
6062     case Intrinsic::amdgcn_ds_fmin:
6063       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6064       break;
6065     case Intrinsic::amdgcn_ds_fmax:
6066       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6067       break;
6068     default:
6069       llvm_unreachable("Unknown intrinsic!");
6070     }
6071     SDValue Ops[] = {
6072       M->getOperand(0), // Chain
6073       M->getOperand(2), // Ptr
6074       M->getOperand(3)  // Value
6075     };
6076 
6077     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6078                                    M->getMemoryVT(), M->getMemOperand());
6079   }
6080   case Intrinsic::amdgcn_buffer_load:
6081   case Intrinsic::amdgcn_buffer_load_format: {
6082     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6083     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6084     unsigned IdxEn = 1;
6085     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6086       IdxEn = Idx->getZExtValue() != 0;
6087     SDValue Ops[] = {
6088       Op.getOperand(0), // Chain
6089       Op.getOperand(2), // rsrc
6090       Op.getOperand(3), // vindex
6091       SDValue(),        // voffset -- will be set by setBufferOffsets
6092       SDValue(),        // soffset -- will be set by setBufferOffsets
6093       SDValue(),        // offset -- will be set by setBufferOffsets
6094       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6095       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6096     };
6097 
6098     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6099     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6100         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6101 
6102     EVT VT = Op.getValueType();
6103     EVT IntVT = VT.changeTypeToInteger();
6104     auto *M = cast<MemSDNode>(Op);
6105     EVT LoadVT = Op.getValueType();
6106 
6107     if (LoadVT.getScalarType() == MVT::f16)
6108       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6109                                  M, DAG, Ops);
6110 
6111     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6112     if (LoadVT.getScalarType() == MVT::i8 ||
6113         LoadVT.getScalarType() == MVT::i16)
6114       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6115 
6116     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6117                                M->getMemOperand(), DAG);
6118   }
6119   case Intrinsic::amdgcn_raw_buffer_load:
6120   case Intrinsic::amdgcn_raw_buffer_load_format: {
6121     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6122     SDValue Ops[] = {
6123       Op.getOperand(0), // Chain
6124       Op.getOperand(2), // rsrc
6125       DAG.getConstant(0, DL, MVT::i32), // vindex
6126       Offsets.first,    // voffset
6127       Op.getOperand(4), // soffset
6128       Offsets.second,   // offset
6129       Op.getOperand(5), // cachepolicy
6130       DAG.getConstant(0, DL, MVT::i1), // idxen
6131     };
6132 
6133     unsigned Opc = (IntrID == Intrinsic::amdgcn_raw_buffer_load) ?
6134         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6135 
6136     EVT VT = Op.getValueType();
6137     EVT IntVT = VT.changeTypeToInteger();
6138     auto *M = cast<MemSDNode>(Op);
6139     EVT LoadVT = Op.getValueType();
6140 
6141     if (LoadVT.getScalarType() == MVT::f16)
6142       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6143                                  M, DAG, Ops);
6144 
6145     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6146     if (LoadVT.getScalarType() == MVT::i8 ||
6147         LoadVT.getScalarType() == MVT::i16)
6148       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6149 
6150     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6151                                M->getMemOperand(), DAG);
6152   }
6153   case Intrinsic::amdgcn_struct_buffer_load:
6154   case Intrinsic::amdgcn_struct_buffer_load_format: {
6155     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6156     SDValue Ops[] = {
6157       Op.getOperand(0), // Chain
6158       Op.getOperand(2), // rsrc
6159       Op.getOperand(3), // vindex
6160       Offsets.first,    // voffset
6161       Op.getOperand(5), // soffset
6162       Offsets.second,   // offset
6163       Op.getOperand(6), // cachepolicy
6164       DAG.getConstant(1, DL, MVT::i1), // idxen
6165     };
6166 
6167     unsigned Opc = (IntrID == Intrinsic::amdgcn_struct_buffer_load) ?
6168         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6169 
6170     EVT VT = Op.getValueType();
6171     EVT IntVT = VT.changeTypeToInteger();
6172     auto *M = cast<MemSDNode>(Op);
6173     EVT LoadVT = Op.getValueType();
6174 
6175     if (LoadVT.getScalarType() == MVT::f16)
6176       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6177                                  M, DAG, Ops);
6178 
6179     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6180     if (LoadVT.getScalarType() == MVT::i8 ||
6181         LoadVT.getScalarType() == MVT::i16)
6182       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6183 
6184     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6185                                M->getMemOperand(), DAG);
6186   }
6187   case Intrinsic::amdgcn_tbuffer_load: {
6188     MemSDNode *M = cast<MemSDNode>(Op);
6189     EVT LoadVT = Op.getValueType();
6190 
6191     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6192     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6193     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6194     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6195     unsigned IdxEn = 1;
6196     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6197       IdxEn = Idx->getZExtValue() != 0;
6198     SDValue Ops[] = {
6199       Op.getOperand(0),  // Chain
6200       Op.getOperand(2),  // rsrc
6201       Op.getOperand(3),  // vindex
6202       Op.getOperand(4),  // voffset
6203       Op.getOperand(5),  // soffset
6204       Op.getOperand(6),  // offset
6205       DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6206       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6207       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6208     };
6209 
6210     if (LoadVT.getScalarType() == MVT::f16)
6211       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6212                                  M, DAG, Ops);
6213     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6214                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6215                                DAG);
6216   }
6217   case Intrinsic::amdgcn_raw_tbuffer_load: {
6218     MemSDNode *M = cast<MemSDNode>(Op);
6219     EVT LoadVT = Op.getValueType();
6220     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6221 
6222     SDValue Ops[] = {
6223       Op.getOperand(0),  // Chain
6224       Op.getOperand(2),  // rsrc
6225       DAG.getConstant(0, DL, MVT::i32), // vindex
6226       Offsets.first,     // voffset
6227       Op.getOperand(4),  // soffset
6228       Offsets.second,    // offset
6229       Op.getOperand(5),  // format
6230       Op.getOperand(6),  // cachepolicy
6231       DAG.getConstant(0, DL, MVT::i1), // idxen
6232     };
6233 
6234     if (LoadVT.getScalarType() == MVT::f16)
6235       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6236                                  M, DAG, Ops);
6237     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6238                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6239                                DAG);
6240   }
6241   case Intrinsic::amdgcn_struct_tbuffer_load: {
6242     MemSDNode *M = cast<MemSDNode>(Op);
6243     EVT LoadVT = Op.getValueType();
6244     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6245 
6246     SDValue Ops[] = {
6247       Op.getOperand(0),  // Chain
6248       Op.getOperand(2),  // rsrc
6249       Op.getOperand(3),  // vindex
6250       Offsets.first,     // voffset
6251       Op.getOperand(5),  // soffset
6252       Offsets.second,    // offset
6253       Op.getOperand(6),  // format
6254       Op.getOperand(7),  // cachepolicy
6255       DAG.getConstant(1, DL, MVT::i1), // idxen
6256     };
6257 
6258     if (LoadVT.getScalarType() == MVT::f16)
6259       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6260                                  M, DAG, Ops);
6261     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6262                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6263                                DAG);
6264   }
6265   case Intrinsic::amdgcn_buffer_atomic_swap:
6266   case Intrinsic::amdgcn_buffer_atomic_add:
6267   case Intrinsic::amdgcn_buffer_atomic_sub:
6268   case Intrinsic::amdgcn_buffer_atomic_smin:
6269   case Intrinsic::amdgcn_buffer_atomic_umin:
6270   case Intrinsic::amdgcn_buffer_atomic_smax:
6271   case Intrinsic::amdgcn_buffer_atomic_umax:
6272   case Intrinsic::amdgcn_buffer_atomic_and:
6273   case Intrinsic::amdgcn_buffer_atomic_or:
6274   case Intrinsic::amdgcn_buffer_atomic_xor: {
6275     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6276     unsigned IdxEn = 1;
6277     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6278       IdxEn = Idx->getZExtValue() != 0;
6279     SDValue Ops[] = {
6280       Op.getOperand(0), // Chain
6281       Op.getOperand(2), // vdata
6282       Op.getOperand(3), // rsrc
6283       Op.getOperand(4), // vindex
6284       SDValue(),        // voffset -- will be set by setBufferOffsets
6285       SDValue(),        // soffset -- will be set by setBufferOffsets
6286       SDValue(),        // offset -- will be set by setBufferOffsets
6287       DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6288       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6289     };
6290     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6291     EVT VT = Op.getValueType();
6292 
6293     auto *M = cast<MemSDNode>(Op);
6294     unsigned Opcode = 0;
6295 
6296     switch (IntrID) {
6297     case Intrinsic::amdgcn_buffer_atomic_swap:
6298       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6299       break;
6300     case Intrinsic::amdgcn_buffer_atomic_add:
6301       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6302       break;
6303     case Intrinsic::amdgcn_buffer_atomic_sub:
6304       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6305       break;
6306     case Intrinsic::amdgcn_buffer_atomic_smin:
6307       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6308       break;
6309     case Intrinsic::amdgcn_buffer_atomic_umin:
6310       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6311       break;
6312     case Intrinsic::amdgcn_buffer_atomic_smax:
6313       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6314       break;
6315     case Intrinsic::amdgcn_buffer_atomic_umax:
6316       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6317       break;
6318     case Intrinsic::amdgcn_buffer_atomic_and:
6319       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6320       break;
6321     case Intrinsic::amdgcn_buffer_atomic_or:
6322       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6323       break;
6324     case Intrinsic::amdgcn_buffer_atomic_xor:
6325       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6326       break;
6327     default:
6328       llvm_unreachable("unhandled atomic opcode");
6329     }
6330 
6331     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6332                                    M->getMemOperand());
6333   }
6334   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6335   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6336   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6337   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6338   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6339   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6340   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6341   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6342   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6343   case Intrinsic::amdgcn_raw_buffer_atomic_xor: {
6344     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6345     SDValue Ops[] = {
6346       Op.getOperand(0), // Chain
6347       Op.getOperand(2), // vdata
6348       Op.getOperand(3), // rsrc
6349       DAG.getConstant(0, DL, MVT::i32), // vindex
6350       Offsets.first,    // voffset
6351       Op.getOperand(5), // soffset
6352       Offsets.second,   // offset
6353       Op.getOperand(6), // cachepolicy
6354       DAG.getConstant(0, DL, MVT::i1), // idxen
6355     };
6356     EVT VT = Op.getValueType();
6357 
6358     auto *M = cast<MemSDNode>(Op);
6359     unsigned Opcode = 0;
6360 
6361     switch (IntrID) {
6362     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6363       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6364       break;
6365     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6366       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6367       break;
6368     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6369       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6370       break;
6371     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6372       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6373       break;
6374     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6375       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6376       break;
6377     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6378       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6379       break;
6380     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6381       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6382       break;
6383     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6384       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6385       break;
6386     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6387       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6388       break;
6389     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6390       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6391       break;
6392     default:
6393       llvm_unreachable("unhandled atomic opcode");
6394     }
6395 
6396     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6397                                    M->getMemOperand());
6398   }
6399   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6400   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6401   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6402   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6403   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6404   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6405   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6406   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6407   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6408   case Intrinsic::amdgcn_struct_buffer_atomic_xor: {
6409     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6410     SDValue Ops[] = {
6411       Op.getOperand(0), // Chain
6412       Op.getOperand(2), // vdata
6413       Op.getOperand(3), // rsrc
6414       Op.getOperand(4), // vindex
6415       Offsets.first,    // voffset
6416       Op.getOperand(6), // soffset
6417       Offsets.second,   // offset
6418       Op.getOperand(7), // cachepolicy
6419       DAG.getConstant(1, DL, MVT::i1), // idxen
6420     };
6421     EVT VT = Op.getValueType();
6422 
6423     auto *M = cast<MemSDNode>(Op);
6424     unsigned Opcode = 0;
6425 
6426     switch (IntrID) {
6427     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6428       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6429       break;
6430     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6431       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6432       break;
6433     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6434       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6435       break;
6436     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6437       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6438       break;
6439     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6440       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6441       break;
6442     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6443       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6444       break;
6445     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6446       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6447       break;
6448     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6449       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6450       break;
6451     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6452       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6453       break;
6454     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6455       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6456       break;
6457     default:
6458       llvm_unreachable("unhandled atomic opcode");
6459     }
6460 
6461     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6462                                    M->getMemOperand());
6463   }
6464   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6465     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6466     unsigned IdxEn = 1;
6467     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6468       IdxEn = Idx->getZExtValue() != 0;
6469     SDValue Ops[] = {
6470       Op.getOperand(0), // Chain
6471       Op.getOperand(2), // src
6472       Op.getOperand(3), // cmp
6473       Op.getOperand(4), // rsrc
6474       Op.getOperand(5), // vindex
6475       SDValue(),        // voffset -- will be set by setBufferOffsets
6476       SDValue(),        // soffset -- will be set by setBufferOffsets
6477       SDValue(),        // offset -- will be set by setBufferOffsets
6478       DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6479       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6480     };
6481     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6482     EVT VT = Op.getValueType();
6483     auto *M = cast<MemSDNode>(Op);
6484 
6485     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6486                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6487   }
6488   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6489     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6490     SDValue Ops[] = {
6491       Op.getOperand(0), // Chain
6492       Op.getOperand(2), // src
6493       Op.getOperand(3), // cmp
6494       Op.getOperand(4), // rsrc
6495       DAG.getConstant(0, DL, MVT::i32), // vindex
6496       Offsets.first,    // voffset
6497       Op.getOperand(6), // soffset
6498       Offsets.second,   // offset
6499       Op.getOperand(7), // cachepolicy
6500       DAG.getConstant(0, DL, MVT::i1), // idxen
6501     };
6502     EVT VT = Op.getValueType();
6503     auto *M = cast<MemSDNode>(Op);
6504 
6505     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6506                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6507   }
6508   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6509     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6510     SDValue Ops[] = {
6511       Op.getOperand(0), // Chain
6512       Op.getOperand(2), // src
6513       Op.getOperand(3), // cmp
6514       Op.getOperand(4), // rsrc
6515       Op.getOperand(5), // vindex
6516       Offsets.first,    // voffset
6517       Op.getOperand(7), // soffset
6518       Offsets.second,   // offset
6519       Op.getOperand(8), // cachepolicy
6520       DAG.getConstant(1, DL, MVT::i1), // idxen
6521     };
6522     EVT VT = Op.getValueType();
6523     auto *M = cast<MemSDNode>(Op);
6524 
6525     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6526                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6527   }
6528 
6529   default:
6530     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6531             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6532       return lowerImage(Op, ImageDimIntr, DAG);
6533 
6534     return SDValue();
6535   }
6536 }
6537 
6538 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6539 // dwordx4 if on SI.
6540 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6541                                               SDVTList VTList,
6542                                               ArrayRef<SDValue> Ops, EVT MemVT,
6543                                               MachineMemOperand *MMO,
6544                                               SelectionDAG &DAG) const {
6545   EVT VT = VTList.VTs[0];
6546   EVT WidenedVT = VT;
6547   EVT WidenedMemVT = MemVT;
6548   if (!Subtarget->hasDwordx3LoadStores() &&
6549       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6550     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6551                                  WidenedVT.getVectorElementType(), 4);
6552     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6553                                     WidenedMemVT.getVectorElementType(), 4);
6554     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6555   }
6556 
6557   assert(VTList.NumVTs == 2);
6558   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6559 
6560   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6561                                        WidenedMemVT, MMO);
6562   if (WidenedVT != VT) {
6563     auto Extract = DAG.getNode(
6564         ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6565         DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout())));
6566     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6567   }
6568   return NewOp;
6569 }
6570 
6571 SDValue SITargetLowering::handleD16VData(SDValue VData,
6572                                          SelectionDAG &DAG) const {
6573   EVT StoreVT = VData.getValueType();
6574 
6575   // No change for f16 and legal vector D16 types.
6576   if (!StoreVT.isVector())
6577     return VData;
6578 
6579   SDLoc DL(VData);
6580   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6581 
6582   if (Subtarget->hasUnpackedD16VMem()) {
6583     // We need to unpack the packed data to store.
6584     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6585     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6586 
6587     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6588                                         StoreVT.getVectorNumElements());
6589     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6590     return DAG.UnrollVectorOp(ZExt.getNode());
6591   }
6592 
6593   assert(isTypeLegal(StoreVT));
6594   return VData;
6595 }
6596 
6597 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6598                                               SelectionDAG &DAG) const {
6599   SDLoc DL(Op);
6600   SDValue Chain = Op.getOperand(0);
6601   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6602   MachineFunction &MF = DAG.getMachineFunction();
6603 
6604   switch (IntrinsicID) {
6605   case Intrinsic::amdgcn_exp: {
6606     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6607     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6608     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
6609     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
6610 
6611     const SDValue Ops[] = {
6612       Chain,
6613       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6614       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
6615       Op.getOperand(4), // src0
6616       Op.getOperand(5), // src1
6617       Op.getOperand(6), // src2
6618       Op.getOperand(7), // src3
6619       DAG.getTargetConstant(0, DL, MVT::i1), // compr
6620       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6621     };
6622 
6623     unsigned Opc = Done->isNullValue() ?
6624       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6625     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6626   }
6627   case Intrinsic::amdgcn_exp_compr: {
6628     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6629     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6630     SDValue Src0 = Op.getOperand(4);
6631     SDValue Src1 = Op.getOperand(5);
6632     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6633     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
6634 
6635     SDValue Undef = DAG.getUNDEF(MVT::f32);
6636     const SDValue Ops[] = {
6637       Chain,
6638       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6639       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
6640       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
6641       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
6642       Undef, // src2
6643       Undef, // src3
6644       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6645       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6646     };
6647 
6648     unsigned Opc = Done->isNullValue() ?
6649       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6650     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6651   }
6652   case Intrinsic::amdgcn_s_sendmsg:
6653   case Intrinsic::amdgcn_s_sendmsghalt: {
6654     unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
6655       AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
6656     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
6657     SDValue Glue = Chain.getValue(1);
6658     return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
6659                        Op.getOperand(2), Glue);
6660   }
6661   case Intrinsic::amdgcn_init_exec: {
6662     return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
6663                        Op.getOperand(2));
6664   }
6665   case Intrinsic::amdgcn_init_exec_from_input: {
6666     return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
6667                        Op.getOperand(2), Op.getOperand(3));
6668   }
6669   case Intrinsic::amdgcn_s_barrier: {
6670     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6671       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6672       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6673       if (WGSize <= ST.getWavefrontSize())
6674         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6675                                           Op.getOperand(0)), 0);
6676     }
6677     return SDValue();
6678   };
6679   case Intrinsic::amdgcn_tbuffer_store: {
6680     SDValue VData = Op.getOperand(2);
6681     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6682     if (IsD16)
6683       VData = handleD16VData(VData, DAG);
6684     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6685     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6686     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6687     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6688     unsigned IdxEn = 1;
6689     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6690       IdxEn = Idx->getZExtValue() != 0;
6691     SDValue Ops[] = {
6692       Chain,
6693       VData,             // vdata
6694       Op.getOperand(3),  // rsrc
6695       Op.getOperand(4),  // vindex
6696       Op.getOperand(5),  // voffset
6697       Op.getOperand(6),  // soffset
6698       Op.getOperand(7),  // offset
6699       DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6700       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6701       DAG.getConstant(IdxEn, DL, MVT::i1), // idexen
6702     };
6703     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6704                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6705     MemSDNode *M = cast<MemSDNode>(Op);
6706     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6707                                    M->getMemoryVT(), M->getMemOperand());
6708   }
6709 
6710   case Intrinsic::amdgcn_struct_tbuffer_store: {
6711     SDValue VData = Op.getOperand(2);
6712     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6713     if (IsD16)
6714       VData = handleD16VData(VData, DAG);
6715     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6716     SDValue Ops[] = {
6717       Chain,
6718       VData,             // vdata
6719       Op.getOperand(3),  // rsrc
6720       Op.getOperand(4),  // vindex
6721       Offsets.first,     // voffset
6722       Op.getOperand(6),  // soffset
6723       Offsets.second,    // offset
6724       Op.getOperand(7),  // format
6725       Op.getOperand(8),  // cachepolicy
6726       DAG.getConstant(1, DL, MVT::i1), // idexen
6727     };
6728     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6729                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6730     MemSDNode *M = cast<MemSDNode>(Op);
6731     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6732                                    M->getMemoryVT(), M->getMemOperand());
6733   }
6734 
6735   case Intrinsic::amdgcn_raw_tbuffer_store: {
6736     SDValue VData = Op.getOperand(2);
6737     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6738     if (IsD16)
6739       VData = handleD16VData(VData, DAG);
6740     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6741     SDValue Ops[] = {
6742       Chain,
6743       VData,             // vdata
6744       Op.getOperand(3),  // rsrc
6745       DAG.getConstant(0, DL, MVT::i32), // vindex
6746       Offsets.first,     // voffset
6747       Op.getOperand(5),  // soffset
6748       Offsets.second,    // offset
6749       Op.getOperand(6),  // format
6750       Op.getOperand(7),  // cachepolicy
6751       DAG.getConstant(0, DL, MVT::i1), // idexen
6752     };
6753     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6754                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6755     MemSDNode *M = cast<MemSDNode>(Op);
6756     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6757                                    M->getMemoryVT(), M->getMemOperand());
6758   }
6759 
6760   case Intrinsic::amdgcn_buffer_store:
6761   case Intrinsic::amdgcn_buffer_store_format: {
6762     SDValue VData = Op.getOperand(2);
6763     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6764     if (IsD16)
6765       VData = handleD16VData(VData, DAG);
6766     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6767     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6768     unsigned IdxEn = 1;
6769     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6770       IdxEn = Idx->getZExtValue() != 0;
6771     SDValue Ops[] = {
6772       Chain,
6773       VData,
6774       Op.getOperand(3), // rsrc
6775       Op.getOperand(4), // vindex
6776       SDValue(), // voffset -- will be set by setBufferOffsets
6777       SDValue(), // soffset -- will be set by setBufferOffsets
6778       SDValue(), // offset -- will be set by setBufferOffsets
6779       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6780       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6781     };
6782     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6783     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6784                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6785     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6786     MemSDNode *M = cast<MemSDNode>(Op);
6787 
6788     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6789     EVT VDataType = VData.getValueType().getScalarType();
6790     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6791       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6792 
6793     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6794                                    M->getMemoryVT(), M->getMemOperand());
6795   }
6796 
6797   case Intrinsic::amdgcn_raw_buffer_store:
6798   case Intrinsic::amdgcn_raw_buffer_store_format: {
6799     SDValue VData = Op.getOperand(2);
6800     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6801     if (IsD16)
6802       VData = handleD16VData(VData, DAG);
6803     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6804     SDValue Ops[] = {
6805       Chain,
6806       VData,
6807       Op.getOperand(3), // rsrc
6808       DAG.getConstant(0, DL, MVT::i32), // vindex
6809       Offsets.first,    // voffset
6810       Op.getOperand(5), // soffset
6811       Offsets.second,   // offset
6812       Op.getOperand(6), // cachepolicy
6813       DAG.getConstant(0, DL, MVT::i1), // idxen
6814     };
6815     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_raw_buffer_store ?
6816                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6817     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6818     MemSDNode *M = cast<MemSDNode>(Op);
6819 
6820     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6821     EVT VDataType = VData.getValueType().getScalarType();
6822     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6823       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6824 
6825     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6826                                    M->getMemoryVT(), M->getMemOperand());
6827   }
6828 
6829   case Intrinsic::amdgcn_struct_buffer_store:
6830   case Intrinsic::amdgcn_struct_buffer_store_format: {
6831     SDValue VData = Op.getOperand(2);
6832     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6833     if (IsD16)
6834       VData = handleD16VData(VData, DAG);
6835     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6836     SDValue Ops[] = {
6837       Chain,
6838       VData,
6839       Op.getOperand(3), // rsrc
6840       Op.getOperand(4), // vindex
6841       Offsets.first,    // voffset
6842       Op.getOperand(6), // soffset
6843       Offsets.second,   // offset
6844       Op.getOperand(7), // cachepolicy
6845       DAG.getConstant(1, DL, MVT::i1), // idxen
6846     };
6847     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
6848                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6849     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6850     MemSDNode *M = cast<MemSDNode>(Op);
6851 
6852     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6853     EVT VDataType = VData.getValueType().getScalarType();
6854     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6855       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6856 
6857     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6858                                    M->getMemoryVT(), M->getMemOperand());
6859   }
6860 
6861   case Intrinsic::amdgcn_end_cf:
6862     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
6863                                       Op->getOperand(2), Chain), 0);
6864 
6865   default: {
6866     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6867             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6868       return lowerImage(Op, ImageDimIntr, DAG);
6869 
6870     return Op;
6871   }
6872   }
6873 }
6874 
6875 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
6876 // offset (the offset that is included in bounds checking and swizzling, to be
6877 // split between the instruction's voffset and immoffset fields) and soffset
6878 // (the offset that is excluded from bounds checking and swizzling, to go in
6879 // the instruction's soffset field).  This function takes the first kind of
6880 // offset and figures out how to split it between voffset and immoffset.
6881 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
6882     SDValue Offset, SelectionDAG &DAG) const {
6883   SDLoc DL(Offset);
6884   const unsigned MaxImm = 4095;
6885   SDValue N0 = Offset;
6886   ConstantSDNode *C1 = nullptr;
6887 
6888   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
6889     N0 = SDValue();
6890   else if (DAG.isBaseWithConstantOffset(N0)) {
6891     C1 = cast<ConstantSDNode>(N0.getOperand(1));
6892     N0 = N0.getOperand(0);
6893   }
6894 
6895   if (C1) {
6896     unsigned ImmOffset = C1->getZExtValue();
6897     // If the immediate value is too big for the immoffset field, put the value
6898     // and -4096 into the immoffset field so that the value that is copied/added
6899     // for the voffset field is a multiple of 4096, and it stands more chance
6900     // of being CSEd with the copy/add for another similar load/store.
6901     // However, do not do that rounding down to a multiple of 4096 if that is a
6902     // negative number, as it appears to be illegal to have a negative offset
6903     // in the vgpr, even if adding the immediate offset makes it positive.
6904     unsigned Overflow = ImmOffset & ~MaxImm;
6905     ImmOffset -= Overflow;
6906     if ((int32_t)Overflow < 0) {
6907       Overflow += ImmOffset;
6908       ImmOffset = 0;
6909     }
6910     C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32));
6911     if (Overflow) {
6912       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
6913       if (!N0)
6914         N0 = OverflowVal;
6915       else {
6916         SDValue Ops[] = { N0, OverflowVal };
6917         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
6918       }
6919     }
6920   }
6921   if (!N0)
6922     N0 = DAG.getConstant(0, DL, MVT::i32);
6923   if (!C1)
6924     C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32));
6925   return {N0, SDValue(C1, 0)};
6926 }
6927 
6928 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
6929 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
6930 // pointed to by Offsets.
6931 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
6932                                         SelectionDAG &DAG, SDValue *Offsets,
6933                                         unsigned Align) const {
6934   SDLoc DL(CombinedOffset);
6935   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
6936     uint32_t Imm = C->getZExtValue();
6937     uint32_t SOffset, ImmOffset;
6938     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
6939       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
6940       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
6941       Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
6942       return;
6943     }
6944   }
6945   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
6946     SDValue N0 = CombinedOffset.getOperand(0);
6947     SDValue N1 = CombinedOffset.getOperand(1);
6948     uint32_t SOffset, ImmOffset;
6949     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
6950     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
6951                                                 Subtarget, Align)) {
6952       Offsets[0] = N0;
6953       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
6954       Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
6955       return;
6956     }
6957   }
6958   Offsets[0] = CombinedOffset;
6959   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
6960   Offsets[2] = DAG.getConstant(0, DL, MVT::i32);
6961 }
6962 
6963 // Handle 8 bit and 16 bit buffer loads
6964 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
6965                                                      EVT LoadVT, SDLoc DL,
6966                                                      ArrayRef<SDValue> Ops,
6967                                                      MemSDNode *M) const {
6968   EVT IntVT = LoadVT.changeTypeToInteger();
6969   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
6970          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
6971 
6972   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
6973   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
6974                                                Ops, IntVT,
6975                                                M->getMemOperand());
6976   SDValue BufferLoadTrunc = DAG.getNode(ISD::TRUNCATE, DL,
6977                                         LoadVT.getScalarType(), BufferLoad);
6978   return DAG.getMergeValues({BufferLoadTrunc, BufferLoad.getValue(1)}, DL);
6979 }
6980 
6981 // Handle 8 bit and 16 bit buffer stores
6982 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
6983                                                       EVT VDataType, SDLoc DL,
6984                                                       SDValue Ops[],
6985                                                       MemSDNode *M) const {
6986   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
6987   Ops[1] = BufferStoreExt;
6988   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
6989                                  AMDGPUISD::BUFFER_STORE_SHORT;
6990   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
6991   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
6992                                      M->getMemOperand());
6993 }
6994 
6995 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
6996                                  ISD::LoadExtType ExtType, SDValue Op,
6997                                  const SDLoc &SL, EVT VT) {
6998   if (VT.bitsLT(Op.getValueType()))
6999     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7000 
7001   switch (ExtType) {
7002   case ISD::SEXTLOAD:
7003     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7004   case ISD::ZEXTLOAD:
7005     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7006   case ISD::EXTLOAD:
7007     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7008   case ISD::NON_EXTLOAD:
7009     return Op;
7010   }
7011 
7012   llvm_unreachable("invalid ext type");
7013 }
7014 
7015 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7016   SelectionDAG &DAG = DCI.DAG;
7017   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7018     return SDValue();
7019 
7020   // FIXME: Constant loads should all be marked invariant.
7021   unsigned AS = Ld->getAddressSpace();
7022   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7023       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7024       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7025     return SDValue();
7026 
7027   // Don't do this early, since it may interfere with adjacent load merging for
7028   // illegal types. We can avoid losing alignment information for exotic types
7029   // pre-legalize.
7030   EVT MemVT = Ld->getMemoryVT();
7031   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7032       MemVT.getSizeInBits() >= 32)
7033     return SDValue();
7034 
7035   SDLoc SL(Ld);
7036 
7037   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7038          "unexpected vector extload");
7039 
7040   // TODO: Drop only high part of range.
7041   SDValue Ptr = Ld->getBasePtr();
7042   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7043                                 MVT::i32, SL, Ld->getChain(), Ptr,
7044                                 Ld->getOffset(),
7045                                 Ld->getPointerInfo(), MVT::i32,
7046                                 Ld->getAlignment(),
7047                                 Ld->getMemOperand()->getFlags(),
7048                                 Ld->getAAInfo(),
7049                                 nullptr); // Drop ranges
7050 
7051   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7052   if (MemVT.isFloatingPoint()) {
7053     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7054            "unexpected fp extload");
7055     TruncVT = MemVT.changeTypeToInteger();
7056   }
7057 
7058   SDValue Cvt = NewLoad;
7059   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7060     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7061                       DAG.getValueType(TruncVT));
7062   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7063              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7064     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7065   } else {
7066     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7067   }
7068 
7069   EVT VT = Ld->getValueType(0);
7070   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7071 
7072   DCI.AddToWorklist(Cvt.getNode());
7073 
7074   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7075   // the appropriate extension from the 32-bit load.
7076   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7077   DCI.AddToWorklist(Cvt.getNode());
7078 
7079   // Handle conversion back to floating point if necessary.
7080   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7081 
7082   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7083 }
7084 
7085 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7086   SDLoc DL(Op);
7087   LoadSDNode *Load = cast<LoadSDNode>(Op);
7088   ISD::LoadExtType ExtType = Load->getExtensionType();
7089   EVT MemVT = Load->getMemoryVT();
7090 
7091   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7092     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7093       return SDValue();
7094 
7095     // FIXME: Copied from PPC
7096     // First, load into 32 bits, then truncate to 1 bit.
7097 
7098     SDValue Chain = Load->getChain();
7099     SDValue BasePtr = Load->getBasePtr();
7100     MachineMemOperand *MMO = Load->getMemOperand();
7101 
7102     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7103 
7104     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7105                                    BasePtr, RealMemVT, MMO);
7106 
7107     if (!MemVT.isVector()) {
7108       SDValue Ops[] = {
7109         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7110         NewLD.getValue(1)
7111       };
7112 
7113       return DAG.getMergeValues(Ops, DL);
7114     }
7115 
7116     SmallVector<SDValue, 3> Elts;
7117     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7118       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7119                                 DAG.getConstant(I, DL, MVT::i32));
7120 
7121       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7122     }
7123 
7124     SDValue Ops[] = {
7125       DAG.getBuildVector(MemVT, DL, Elts),
7126       NewLD.getValue(1)
7127     };
7128 
7129     return DAG.getMergeValues(Ops, DL);
7130   }
7131 
7132   if (!MemVT.isVector())
7133     return SDValue();
7134 
7135   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7136          "Custom lowering for non-i32 vectors hasn't been implemented.");
7137 
7138   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
7139                           *Load->getMemOperand())) {
7140     SDValue Ops[2];
7141     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7142     return DAG.getMergeValues(Ops, DL);
7143   }
7144 
7145   unsigned Alignment = Load->getAlignment();
7146   unsigned AS = Load->getAddressSpace();
7147   if (Subtarget->hasLDSMisalignedBug() &&
7148       AS == AMDGPUAS::FLAT_ADDRESS &&
7149       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7150     return SplitVectorLoad(Op, DAG);
7151   }
7152 
7153   MachineFunction &MF = DAG.getMachineFunction();
7154   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7155   // If there is a possibilty that flat instruction access scratch memory
7156   // then we need to use the same legalization rules we use for private.
7157   if (AS == AMDGPUAS::FLAT_ADDRESS)
7158     AS = MFI->hasFlatScratchInit() ?
7159          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7160 
7161   unsigned NumElements = MemVT.getVectorNumElements();
7162 
7163   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7164       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7165     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7166       if (MemVT.isPow2VectorType())
7167         return SDValue();
7168       if (NumElements == 3)
7169         return WidenVectorLoad(Op, DAG);
7170       return SplitVectorLoad(Op, DAG);
7171     }
7172     // Non-uniform loads will be selected to MUBUF instructions, so they
7173     // have the same legalization requirements as global and private
7174     // loads.
7175     //
7176   }
7177 
7178   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7179       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7180       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7181     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7182         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7183         Alignment >= 4 && NumElements < 32) {
7184       if (MemVT.isPow2VectorType())
7185         return SDValue();
7186       if (NumElements == 3)
7187         return WidenVectorLoad(Op, DAG);
7188       return SplitVectorLoad(Op, DAG);
7189     }
7190     // Non-uniform loads will be selected to MUBUF instructions, so they
7191     // have the same legalization requirements as global and private
7192     // loads.
7193     //
7194   }
7195   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7196       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7197       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7198       AS == AMDGPUAS::FLAT_ADDRESS) {
7199     if (NumElements > 4)
7200       return SplitVectorLoad(Op, DAG);
7201     // v3 loads not supported on SI.
7202     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7203       return WidenVectorLoad(Op, DAG);
7204     // v3 and v4 loads are supported for private and global memory.
7205     return SDValue();
7206   }
7207   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7208     // Depending on the setting of the private_element_size field in the
7209     // resource descriptor, we can only make private accesses up to a certain
7210     // size.
7211     switch (Subtarget->getMaxPrivateElementSize()) {
7212     case 4:
7213       return scalarizeVectorLoad(Load, DAG);
7214     case 8:
7215       if (NumElements > 2)
7216         return SplitVectorLoad(Op, DAG);
7217       return SDValue();
7218     case 16:
7219       // Same as global/flat
7220       if (NumElements > 4)
7221         return SplitVectorLoad(Op, DAG);
7222       // v3 loads not supported on SI.
7223       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7224         return WidenVectorLoad(Op, DAG);
7225       return SDValue();
7226     default:
7227       llvm_unreachable("unsupported private_element_size");
7228     }
7229   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7230     // Use ds_read_b128 if possible.
7231     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7232         MemVT.getStoreSize() == 16)
7233       return SDValue();
7234 
7235     if (NumElements > 2)
7236       return SplitVectorLoad(Op, DAG);
7237 
7238     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7239     // address is negative, then the instruction is incorrectly treated as
7240     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7241     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7242     // load later in the SILoadStoreOptimizer.
7243     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7244         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7245         Load->getAlignment() < 8) {
7246       return SplitVectorLoad(Op, DAG);
7247     }
7248   }
7249   return SDValue();
7250 }
7251 
7252 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7253   EVT VT = Op.getValueType();
7254   assert(VT.getSizeInBits() == 64);
7255 
7256   SDLoc DL(Op);
7257   SDValue Cond = Op.getOperand(0);
7258 
7259   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7260   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7261 
7262   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7263   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7264 
7265   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7266   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7267 
7268   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7269 
7270   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7271   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7272 
7273   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7274 
7275   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7276   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7277 }
7278 
7279 // Catch division cases where we can use shortcuts with rcp and rsq
7280 // instructions.
7281 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7282                                               SelectionDAG &DAG) const {
7283   SDLoc SL(Op);
7284   SDValue LHS = Op.getOperand(0);
7285   SDValue RHS = Op.getOperand(1);
7286   EVT VT = Op.getValueType();
7287   const SDNodeFlags Flags = Op->getFlags();
7288   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
7289 
7290   if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
7291     return SDValue();
7292 
7293   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7294     if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
7295       if (CLHS->isExactlyValue(1.0)) {
7296         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7297         // the CI documentation has a worst case error of 1 ulp.
7298         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7299         // use it as long as we aren't trying to use denormals.
7300         //
7301         // v_rcp_f16 and v_rsq_f16 DO support denormals.
7302 
7303         // 1.0 / sqrt(x) -> rsq(x)
7304 
7305         // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7306         // error seems really high at 2^29 ULP.
7307         if (RHS.getOpcode() == ISD::FSQRT)
7308           return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7309 
7310         // 1.0 / x -> rcp(x)
7311         return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7312       }
7313 
7314       // Same as for 1.0, but expand the sign out of the constant.
7315       if (CLHS->isExactlyValue(-1.0)) {
7316         // -1.0 / x -> rcp (fneg x)
7317         SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7318         return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7319       }
7320     }
7321   }
7322 
7323   if (Unsafe) {
7324     // Turn into multiply by the reciprocal.
7325     // x / y -> x * (1.0 / y)
7326     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7327     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7328   }
7329 
7330   return SDValue();
7331 }
7332 
7333 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7334                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7335   if (GlueChain->getNumValues() <= 1) {
7336     return DAG.getNode(Opcode, SL, VT, A, B);
7337   }
7338 
7339   assert(GlueChain->getNumValues() == 3);
7340 
7341   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7342   switch (Opcode) {
7343   default: llvm_unreachable("no chain equivalent for opcode");
7344   case ISD::FMUL:
7345     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7346     break;
7347   }
7348 
7349   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7350                      GlueChain.getValue(2));
7351 }
7352 
7353 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7354                            EVT VT, SDValue A, SDValue B, SDValue C,
7355                            SDValue GlueChain) {
7356   if (GlueChain->getNumValues() <= 1) {
7357     return DAG.getNode(Opcode, SL, VT, A, B, C);
7358   }
7359 
7360   assert(GlueChain->getNumValues() == 3);
7361 
7362   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7363   switch (Opcode) {
7364   default: llvm_unreachable("no chain equivalent for opcode");
7365   case ISD::FMA:
7366     Opcode = AMDGPUISD::FMA_W_CHAIN;
7367     break;
7368   }
7369 
7370   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7371                      GlueChain.getValue(2));
7372 }
7373 
7374 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7375   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7376     return FastLowered;
7377 
7378   SDLoc SL(Op);
7379   SDValue Src0 = Op.getOperand(0);
7380   SDValue Src1 = Op.getOperand(1);
7381 
7382   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7383   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7384 
7385   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7386   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7387 
7388   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7389   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7390 
7391   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7392 }
7393 
7394 // Faster 2.5 ULP division that does not support denormals.
7395 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7396   SDLoc SL(Op);
7397   SDValue LHS = Op.getOperand(1);
7398   SDValue RHS = Op.getOperand(2);
7399 
7400   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7401 
7402   const APFloat K0Val(BitsToFloat(0x6f800000));
7403   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7404 
7405   const APFloat K1Val(BitsToFloat(0x2f800000));
7406   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7407 
7408   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7409 
7410   EVT SetCCVT =
7411     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7412 
7413   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7414 
7415   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7416 
7417   // TODO: Should this propagate fast-math-flags?
7418   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7419 
7420   // rcp does not support denormals.
7421   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7422 
7423   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7424 
7425   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7426 }
7427 
7428 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7429   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7430     return FastLowered;
7431 
7432   SDLoc SL(Op);
7433   SDValue LHS = Op.getOperand(0);
7434   SDValue RHS = Op.getOperand(1);
7435 
7436   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7437 
7438   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7439 
7440   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7441                                           RHS, RHS, LHS);
7442   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7443                                         LHS, RHS, LHS);
7444 
7445   // Denominator is scaled to not be denormal, so using rcp is ok.
7446   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7447                                   DenominatorScaled);
7448   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7449                                      DenominatorScaled);
7450 
7451   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7452                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7453                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7454 
7455   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7456 
7457   if (!Subtarget->hasFP32Denormals()) {
7458     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7459     const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7460                                                       SL, MVT::i32);
7461     SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7462                                        DAG.getEntryNode(),
7463                                        EnableDenormValue, BitField);
7464     SDValue Ops[3] = {
7465       NegDivScale0,
7466       EnableDenorm.getValue(0),
7467       EnableDenorm.getValue(1)
7468     };
7469 
7470     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7471   }
7472 
7473   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7474                              ApproxRcp, One, NegDivScale0);
7475 
7476   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7477                              ApproxRcp, Fma0);
7478 
7479   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7480                            Fma1, Fma1);
7481 
7482   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7483                              NumeratorScaled, Mul);
7484 
7485   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7486 
7487   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7488                              NumeratorScaled, Fma3);
7489 
7490   if (!Subtarget->hasFP32Denormals()) {
7491     const SDValue DisableDenormValue =
7492         DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7493     SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7494                                         Fma4.getValue(1),
7495                                         DisableDenormValue,
7496                                         BitField,
7497                                         Fma4.getValue(2));
7498 
7499     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7500                                       DisableDenorm, DAG.getRoot());
7501     DAG.setRoot(OutputChain);
7502   }
7503 
7504   SDValue Scale = NumeratorScaled.getValue(1);
7505   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7506                              Fma4, Fma1, Fma3, Scale);
7507 
7508   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7509 }
7510 
7511 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7512   if (DAG.getTarget().Options.UnsafeFPMath)
7513     return lowerFastUnsafeFDIV(Op, DAG);
7514 
7515   SDLoc SL(Op);
7516   SDValue X = Op.getOperand(0);
7517   SDValue Y = Op.getOperand(1);
7518 
7519   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7520 
7521   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7522 
7523   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7524 
7525   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7526 
7527   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7528 
7529   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7530 
7531   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7532 
7533   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7534 
7535   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7536 
7537   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7538   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7539 
7540   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7541                              NegDivScale0, Mul, DivScale1);
7542 
7543   SDValue Scale;
7544 
7545   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
7546     // Workaround a hardware bug on SI where the condition output from div_scale
7547     // is not usable.
7548 
7549     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7550 
7551     // Figure out if the scale to use for div_fmas.
7552     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7553     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7554     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7555     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7556 
7557     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7558     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7559 
7560     SDValue Scale0Hi
7561       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7562     SDValue Scale1Hi
7563       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7564 
7565     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7566     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7567     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7568   } else {
7569     Scale = DivScale1.getValue(1);
7570   }
7571 
7572   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7573                              Fma4, Fma3, Mul, Scale);
7574 
7575   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7576 }
7577 
7578 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7579   EVT VT = Op.getValueType();
7580 
7581   if (VT == MVT::f32)
7582     return LowerFDIV32(Op, DAG);
7583 
7584   if (VT == MVT::f64)
7585     return LowerFDIV64(Op, DAG);
7586 
7587   if (VT == MVT::f16)
7588     return LowerFDIV16(Op, DAG);
7589 
7590   llvm_unreachable("Unexpected type for fdiv");
7591 }
7592 
7593 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7594   SDLoc DL(Op);
7595   StoreSDNode *Store = cast<StoreSDNode>(Op);
7596   EVT VT = Store->getMemoryVT();
7597 
7598   if (VT == MVT::i1) {
7599     return DAG.getTruncStore(Store->getChain(), DL,
7600        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7601        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
7602   }
7603 
7604   assert(VT.isVector() &&
7605          Store->getValue().getValueType().getScalarType() == MVT::i32);
7606 
7607   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7608                           *Store->getMemOperand())) {
7609     return expandUnalignedStore(Store, DAG);
7610   }
7611 
7612   unsigned AS = Store->getAddressSpace();
7613   if (Subtarget->hasLDSMisalignedBug() &&
7614       AS == AMDGPUAS::FLAT_ADDRESS &&
7615       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7616     return SplitVectorStore(Op, DAG);
7617   }
7618 
7619   MachineFunction &MF = DAG.getMachineFunction();
7620   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7621   // If there is a possibilty that flat instruction access scratch memory
7622   // then we need to use the same legalization rules we use for private.
7623   if (AS == AMDGPUAS::FLAT_ADDRESS)
7624     AS = MFI->hasFlatScratchInit() ?
7625          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7626 
7627   unsigned NumElements = VT.getVectorNumElements();
7628   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7629       AS == AMDGPUAS::FLAT_ADDRESS) {
7630     if (NumElements > 4)
7631       return SplitVectorStore(Op, DAG);
7632     // v3 stores not supported on SI.
7633     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7634       return SplitVectorStore(Op, DAG);
7635     return SDValue();
7636   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7637     switch (Subtarget->getMaxPrivateElementSize()) {
7638     case 4:
7639       return scalarizeVectorStore(Store, DAG);
7640     case 8:
7641       if (NumElements > 2)
7642         return SplitVectorStore(Op, DAG);
7643       return SDValue();
7644     case 16:
7645       if (NumElements > 4 || NumElements == 3)
7646         return SplitVectorStore(Op, DAG);
7647       return SDValue();
7648     default:
7649       llvm_unreachable("unsupported private_element_size");
7650     }
7651   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7652     // Use ds_write_b128 if possible.
7653     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
7654         VT.getStoreSize() == 16 && NumElements != 3)
7655       return SDValue();
7656 
7657     if (NumElements > 2)
7658       return SplitVectorStore(Op, DAG);
7659 
7660     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7661     // address is negative, then the instruction is incorrectly treated as
7662     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7663     // stores here to avoid emitting ds_write2_b32. We may re-combine the
7664     // store later in the SILoadStoreOptimizer.
7665     if (!Subtarget->hasUsableDSOffset() &&
7666         NumElements == 2 && VT.getStoreSize() == 8 &&
7667         Store->getAlignment() < 8) {
7668       return SplitVectorStore(Op, DAG);
7669     }
7670 
7671     return SDValue();
7672   } else {
7673     llvm_unreachable("unhandled address space");
7674   }
7675 }
7676 
7677 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
7678   SDLoc DL(Op);
7679   EVT VT = Op.getValueType();
7680   SDValue Arg = Op.getOperand(0);
7681   SDValue TrigVal;
7682 
7683   // TODO: Should this propagate fast-math-flags?
7684 
7685   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7686 
7687   if (Subtarget->hasTrigReducedRange()) {
7688     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7689     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7690   } else {
7691     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7692   }
7693 
7694   switch (Op.getOpcode()) {
7695   case ISD::FCOS:
7696     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7697   case ISD::FSIN:
7698     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7699   default:
7700     llvm_unreachable("Wrong trig opcode");
7701   }
7702 }
7703 
7704 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7705   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7706   assert(AtomicNode->isCompareAndSwap());
7707   unsigned AS = AtomicNode->getAddressSpace();
7708 
7709   // No custom lowering required for local address space
7710   if (!isFlatGlobalAddrSpace(AS))
7711     return Op;
7712 
7713   // Non-local address space requires custom lowering for atomic compare
7714   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
7715   SDLoc DL(Op);
7716   SDValue ChainIn = Op.getOperand(0);
7717   SDValue Addr = Op.getOperand(1);
7718   SDValue Old = Op.getOperand(2);
7719   SDValue New = Op.getOperand(3);
7720   EVT VT = Op.getValueType();
7721   MVT SimpleVT = VT.getSimpleVT();
7722   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
7723 
7724   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
7725   SDValue Ops[] = { ChainIn, Addr, NewOld };
7726 
7727   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
7728                                  Ops, VT, AtomicNode->getMemOperand());
7729 }
7730 
7731 //===----------------------------------------------------------------------===//
7732 // Custom DAG optimizations
7733 //===----------------------------------------------------------------------===//
7734 
7735 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
7736                                                      DAGCombinerInfo &DCI) const {
7737   EVT VT = N->getValueType(0);
7738   EVT ScalarVT = VT.getScalarType();
7739   if (ScalarVT != MVT::f32)
7740     return SDValue();
7741 
7742   SelectionDAG &DAG = DCI.DAG;
7743   SDLoc DL(N);
7744 
7745   SDValue Src = N->getOperand(0);
7746   EVT SrcVT = Src.getValueType();
7747 
7748   // TODO: We could try to match extracting the higher bytes, which would be
7749   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
7750   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
7751   // about in practice.
7752   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
7753     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
7754       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
7755       DCI.AddToWorklist(Cvt.getNode());
7756       return Cvt;
7757     }
7758   }
7759 
7760   return SDValue();
7761 }
7762 
7763 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
7764 
7765 // This is a variant of
7766 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
7767 //
7768 // The normal DAG combiner will do this, but only if the add has one use since
7769 // that would increase the number of instructions.
7770 //
7771 // This prevents us from seeing a constant offset that can be folded into a
7772 // memory instruction's addressing mode. If we know the resulting add offset of
7773 // a pointer can be folded into an addressing offset, we can replace the pointer
7774 // operand with the add of new constant offset. This eliminates one of the uses,
7775 // and may allow the remaining use to also be simplified.
7776 //
7777 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
7778                                                unsigned AddrSpace,
7779                                                EVT MemVT,
7780                                                DAGCombinerInfo &DCI) const {
7781   SDValue N0 = N->getOperand(0);
7782   SDValue N1 = N->getOperand(1);
7783 
7784   // We only do this to handle cases where it's profitable when there are
7785   // multiple uses of the add, so defer to the standard combine.
7786   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
7787       N0->hasOneUse())
7788     return SDValue();
7789 
7790   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
7791   if (!CN1)
7792     return SDValue();
7793 
7794   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7795   if (!CAdd)
7796     return SDValue();
7797 
7798   // If the resulting offset is too large, we can't fold it into the addressing
7799   // mode offset.
7800   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
7801   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
7802 
7803   AddrMode AM;
7804   AM.HasBaseReg = true;
7805   AM.BaseOffs = Offset.getSExtValue();
7806   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
7807     return SDValue();
7808 
7809   SelectionDAG &DAG = DCI.DAG;
7810   SDLoc SL(N);
7811   EVT VT = N->getValueType(0);
7812 
7813   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
7814   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
7815 
7816   SDNodeFlags Flags;
7817   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
7818                           (N0.getOpcode() == ISD::OR ||
7819                            N0->getFlags().hasNoUnsignedWrap()));
7820 
7821   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
7822 }
7823 
7824 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
7825                                                   DAGCombinerInfo &DCI) const {
7826   SDValue Ptr = N->getBasePtr();
7827   SelectionDAG &DAG = DCI.DAG;
7828   SDLoc SL(N);
7829 
7830   // TODO: We could also do this for multiplies.
7831   if (Ptr.getOpcode() == ISD::SHL) {
7832     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
7833                                           N->getMemoryVT(), DCI);
7834     if (NewPtr) {
7835       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
7836 
7837       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
7838       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
7839     }
7840   }
7841 
7842   return SDValue();
7843 }
7844 
7845 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
7846   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
7847          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
7848          (Opc == ISD::XOR && Val == 0);
7849 }
7850 
7851 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
7852 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
7853 // integer combine opportunities since most 64-bit operations are decomposed
7854 // this way.  TODO: We won't want this for SALU especially if it is an inline
7855 // immediate.
7856 SDValue SITargetLowering::splitBinaryBitConstantOp(
7857   DAGCombinerInfo &DCI,
7858   const SDLoc &SL,
7859   unsigned Opc, SDValue LHS,
7860   const ConstantSDNode *CRHS) const {
7861   uint64_t Val = CRHS->getZExtValue();
7862   uint32_t ValLo = Lo_32(Val);
7863   uint32_t ValHi = Hi_32(Val);
7864   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7865 
7866     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
7867          bitOpWithConstantIsReducible(Opc, ValHi)) ||
7868         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
7869     // If we need to materialize a 64-bit immediate, it will be split up later
7870     // anyway. Avoid creating the harder to understand 64-bit immediate
7871     // materialization.
7872     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
7873   }
7874 
7875   return SDValue();
7876 }
7877 
7878 // Returns true if argument is a boolean value which is not serialized into
7879 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
7880 static bool isBoolSGPR(SDValue V) {
7881   if (V.getValueType() != MVT::i1)
7882     return false;
7883   switch (V.getOpcode()) {
7884   default: break;
7885   case ISD::SETCC:
7886   case ISD::AND:
7887   case ISD::OR:
7888   case ISD::XOR:
7889   case AMDGPUISD::FP_CLASS:
7890     return true;
7891   }
7892   return false;
7893 }
7894 
7895 // If a constant has all zeroes or all ones within each byte return it.
7896 // Otherwise return 0.
7897 static uint32_t getConstantPermuteMask(uint32_t C) {
7898   // 0xff for any zero byte in the mask
7899   uint32_t ZeroByteMask = 0;
7900   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
7901   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
7902   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
7903   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
7904   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
7905   if ((NonZeroByteMask & C) != NonZeroByteMask)
7906     return 0; // Partial bytes selected.
7907   return C;
7908 }
7909 
7910 // Check if a node selects whole bytes from its operand 0 starting at a byte
7911 // boundary while masking the rest. Returns select mask as in the v_perm_b32
7912 // or -1 if not succeeded.
7913 // Note byte select encoding:
7914 // value 0-3 selects corresponding source byte;
7915 // value 0xc selects zero;
7916 // value 0xff selects 0xff.
7917 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
7918   assert(V.getValueSizeInBits() == 32);
7919 
7920   if (V.getNumOperands() != 2)
7921     return ~0;
7922 
7923   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
7924   if (!N1)
7925     return ~0;
7926 
7927   uint32_t C = N1->getZExtValue();
7928 
7929   switch (V.getOpcode()) {
7930   default:
7931     break;
7932   case ISD::AND:
7933     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
7934       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
7935     }
7936     break;
7937 
7938   case ISD::OR:
7939     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
7940       return (0x03020100 & ~ConstMask) | ConstMask;
7941     }
7942     break;
7943 
7944   case ISD::SHL:
7945     if (C % 8)
7946       return ~0;
7947 
7948     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
7949 
7950   case ISD::SRL:
7951     if (C % 8)
7952       return ~0;
7953 
7954     return uint32_t(0x0c0c0c0c03020100ull >> C);
7955   }
7956 
7957   return ~0;
7958 }
7959 
7960 SDValue SITargetLowering::performAndCombine(SDNode *N,
7961                                             DAGCombinerInfo &DCI) const {
7962   if (DCI.isBeforeLegalize())
7963     return SDValue();
7964 
7965   SelectionDAG &DAG = DCI.DAG;
7966   EVT VT = N->getValueType(0);
7967   SDValue LHS = N->getOperand(0);
7968   SDValue RHS = N->getOperand(1);
7969 
7970 
7971   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
7972   if (VT == MVT::i64 && CRHS) {
7973     if (SDValue Split
7974         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
7975       return Split;
7976   }
7977 
7978   if (CRHS && VT == MVT::i32) {
7979     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
7980     // nb = number of trailing zeroes in mask
7981     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
7982     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
7983     uint64_t Mask = CRHS->getZExtValue();
7984     unsigned Bits = countPopulation(Mask);
7985     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
7986         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
7987       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
7988         unsigned Shift = CShift->getZExtValue();
7989         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
7990         unsigned Offset = NB + Shift;
7991         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
7992           SDLoc SL(N);
7993           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
7994                                     LHS->getOperand(0),
7995                                     DAG.getConstant(Offset, SL, MVT::i32),
7996                                     DAG.getConstant(Bits, SL, MVT::i32));
7997           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7998           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
7999                                     DAG.getValueType(NarrowVT));
8000           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8001                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8002           return Shl;
8003         }
8004       }
8005     }
8006 
8007     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8008     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8009         isa<ConstantSDNode>(LHS.getOperand(2))) {
8010       uint32_t Sel = getConstantPermuteMask(Mask);
8011       if (!Sel)
8012         return SDValue();
8013 
8014       // Select 0xc for all zero bytes
8015       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8016       SDLoc DL(N);
8017       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8018                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8019     }
8020   }
8021 
8022   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8023   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8024   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8025     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8026     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8027 
8028     SDValue X = LHS.getOperand(0);
8029     SDValue Y = RHS.getOperand(0);
8030     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8031       return SDValue();
8032 
8033     if (LCC == ISD::SETO) {
8034       if (X != LHS.getOperand(1))
8035         return SDValue();
8036 
8037       if (RCC == ISD::SETUNE) {
8038         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8039         if (!C1 || !C1->isInfinity() || C1->isNegative())
8040           return SDValue();
8041 
8042         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8043                               SIInstrFlags::N_SUBNORMAL |
8044                               SIInstrFlags::N_ZERO |
8045                               SIInstrFlags::P_ZERO |
8046                               SIInstrFlags::P_SUBNORMAL |
8047                               SIInstrFlags::P_NORMAL;
8048 
8049         static_assert(((~(SIInstrFlags::S_NAN |
8050                           SIInstrFlags::Q_NAN |
8051                           SIInstrFlags::N_INFINITY |
8052                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8053                       "mask not equal");
8054 
8055         SDLoc DL(N);
8056         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8057                            X, DAG.getConstant(Mask, DL, MVT::i32));
8058       }
8059     }
8060   }
8061 
8062   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8063     std::swap(LHS, RHS);
8064 
8065   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8066       RHS.hasOneUse()) {
8067     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8068     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8069     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8070     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8071     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8072         (RHS.getOperand(0) == LHS.getOperand(0) &&
8073          LHS.getOperand(0) == LHS.getOperand(1))) {
8074       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8075       unsigned NewMask = LCC == ISD::SETO ?
8076         Mask->getZExtValue() & ~OrdMask :
8077         Mask->getZExtValue() & OrdMask;
8078 
8079       SDLoc DL(N);
8080       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8081                          DAG.getConstant(NewMask, DL, MVT::i32));
8082     }
8083   }
8084 
8085   if (VT == MVT::i32 &&
8086       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8087     // and x, (sext cc from i1) => select cc, x, 0
8088     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8089       std::swap(LHS, RHS);
8090     if (isBoolSGPR(RHS.getOperand(0)))
8091       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8092                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8093   }
8094 
8095   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8096   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8097   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8098       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8099     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8100     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8101     if (LHSMask != ~0u && RHSMask != ~0u) {
8102       // Canonicalize the expression in an attempt to have fewer unique masks
8103       // and therefore fewer registers used to hold the masks.
8104       if (LHSMask > RHSMask) {
8105         std::swap(LHSMask, RHSMask);
8106         std::swap(LHS, RHS);
8107       }
8108 
8109       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8110       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8111       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8112       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8113 
8114       // Check of we need to combine values from two sources within a byte.
8115       if (!(LHSUsedLanes & RHSUsedLanes) &&
8116           // If we select high and lower word keep it for SDWA.
8117           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8118           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8119         // Each byte in each mask is either selector mask 0-3, or has higher
8120         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8121         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8122         // mask which is not 0xff wins. By anding both masks we have a correct
8123         // result except that 0x0c shall be corrected to give 0x0c only.
8124         uint32_t Mask = LHSMask & RHSMask;
8125         for (unsigned I = 0; I < 32; I += 8) {
8126           uint32_t ByteSel = 0xff << I;
8127           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8128             Mask &= (0x0c << I) & 0xffffffff;
8129         }
8130 
8131         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8132         // or 0x0c.
8133         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8134         SDLoc DL(N);
8135 
8136         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8137                            LHS.getOperand(0), RHS.getOperand(0),
8138                            DAG.getConstant(Sel, DL, MVT::i32));
8139       }
8140     }
8141   }
8142 
8143   return SDValue();
8144 }
8145 
8146 SDValue SITargetLowering::performOrCombine(SDNode *N,
8147                                            DAGCombinerInfo &DCI) const {
8148   SelectionDAG &DAG = DCI.DAG;
8149   SDValue LHS = N->getOperand(0);
8150   SDValue RHS = N->getOperand(1);
8151 
8152   EVT VT = N->getValueType(0);
8153   if (VT == MVT::i1) {
8154     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8155     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8156         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8157       SDValue Src = LHS.getOperand(0);
8158       if (Src != RHS.getOperand(0))
8159         return SDValue();
8160 
8161       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8162       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8163       if (!CLHS || !CRHS)
8164         return SDValue();
8165 
8166       // Only 10 bits are used.
8167       static const uint32_t MaxMask = 0x3ff;
8168 
8169       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8170       SDLoc DL(N);
8171       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8172                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8173     }
8174 
8175     return SDValue();
8176   }
8177 
8178   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8179   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8180       LHS.getOpcode() == AMDGPUISD::PERM &&
8181       isa<ConstantSDNode>(LHS.getOperand(2))) {
8182     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8183     if (!Sel)
8184       return SDValue();
8185 
8186     Sel |= LHS.getConstantOperandVal(2);
8187     SDLoc DL(N);
8188     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8189                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8190   }
8191 
8192   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8193   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8194   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8195       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8196     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8197     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8198     if (LHSMask != ~0u && RHSMask != ~0u) {
8199       // Canonicalize the expression in an attempt to have fewer unique masks
8200       // and therefore fewer registers used to hold the masks.
8201       if (LHSMask > RHSMask) {
8202         std::swap(LHSMask, RHSMask);
8203         std::swap(LHS, RHS);
8204       }
8205 
8206       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8207       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8208       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8209       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8210 
8211       // Check of we need to combine values from two sources within a byte.
8212       if (!(LHSUsedLanes & RHSUsedLanes) &&
8213           // If we select high and lower word keep it for SDWA.
8214           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8215           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8216         // Kill zero bytes selected by other mask. Zero value is 0xc.
8217         LHSMask &= ~RHSUsedLanes;
8218         RHSMask &= ~LHSUsedLanes;
8219         // Add 4 to each active LHS lane
8220         LHSMask |= LHSUsedLanes & 0x04040404;
8221         // Combine masks
8222         uint32_t Sel = LHSMask | RHSMask;
8223         SDLoc DL(N);
8224 
8225         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8226                            LHS.getOperand(0), RHS.getOperand(0),
8227                            DAG.getConstant(Sel, DL, MVT::i32));
8228       }
8229     }
8230   }
8231 
8232   if (VT != MVT::i64)
8233     return SDValue();
8234 
8235   // TODO: This could be a generic combine with a predicate for extracting the
8236   // high half of an integer being free.
8237 
8238   // (or i64:x, (zero_extend i32:y)) ->
8239   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8240   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8241       RHS.getOpcode() != ISD::ZERO_EXTEND)
8242     std::swap(LHS, RHS);
8243 
8244   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8245     SDValue ExtSrc = RHS.getOperand(0);
8246     EVT SrcVT = ExtSrc.getValueType();
8247     if (SrcVT == MVT::i32) {
8248       SDLoc SL(N);
8249       SDValue LowLHS, HiBits;
8250       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8251       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8252 
8253       DCI.AddToWorklist(LowOr.getNode());
8254       DCI.AddToWorklist(HiBits.getNode());
8255 
8256       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8257                                 LowOr, HiBits);
8258       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8259     }
8260   }
8261 
8262   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8263   if (CRHS) {
8264     if (SDValue Split
8265           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8266       return Split;
8267   }
8268 
8269   return SDValue();
8270 }
8271 
8272 SDValue SITargetLowering::performXorCombine(SDNode *N,
8273                                             DAGCombinerInfo &DCI) const {
8274   EVT VT = N->getValueType(0);
8275   if (VT != MVT::i64)
8276     return SDValue();
8277 
8278   SDValue LHS = N->getOperand(0);
8279   SDValue RHS = N->getOperand(1);
8280 
8281   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8282   if (CRHS) {
8283     if (SDValue Split
8284           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8285       return Split;
8286   }
8287 
8288   return SDValue();
8289 }
8290 
8291 // Instructions that will be lowered with a final instruction that zeros the
8292 // high result bits.
8293 // XXX - probably only need to list legal operations.
8294 static bool fp16SrcZerosHighBits(unsigned Opc) {
8295   switch (Opc) {
8296   case ISD::FADD:
8297   case ISD::FSUB:
8298   case ISD::FMUL:
8299   case ISD::FDIV:
8300   case ISD::FREM:
8301   case ISD::FMA:
8302   case ISD::FMAD:
8303   case ISD::FCANONICALIZE:
8304   case ISD::FP_ROUND:
8305   case ISD::UINT_TO_FP:
8306   case ISD::SINT_TO_FP:
8307   case ISD::FABS:
8308     // Fabs is lowered to a bit operation, but it's an and which will clear the
8309     // high bits anyway.
8310   case ISD::FSQRT:
8311   case ISD::FSIN:
8312   case ISD::FCOS:
8313   case ISD::FPOWI:
8314   case ISD::FPOW:
8315   case ISD::FLOG:
8316   case ISD::FLOG2:
8317   case ISD::FLOG10:
8318   case ISD::FEXP:
8319   case ISD::FEXP2:
8320   case ISD::FCEIL:
8321   case ISD::FTRUNC:
8322   case ISD::FRINT:
8323   case ISD::FNEARBYINT:
8324   case ISD::FROUND:
8325   case ISD::FFLOOR:
8326   case ISD::FMINNUM:
8327   case ISD::FMAXNUM:
8328   case AMDGPUISD::FRACT:
8329   case AMDGPUISD::CLAMP:
8330   case AMDGPUISD::COS_HW:
8331   case AMDGPUISD::SIN_HW:
8332   case AMDGPUISD::FMIN3:
8333   case AMDGPUISD::FMAX3:
8334   case AMDGPUISD::FMED3:
8335   case AMDGPUISD::FMAD_FTZ:
8336   case AMDGPUISD::RCP:
8337   case AMDGPUISD::RSQ:
8338   case AMDGPUISD::RCP_IFLAG:
8339   case AMDGPUISD::LDEXP:
8340     return true;
8341   default:
8342     // fcopysign, select and others may be lowered to 32-bit bit operations
8343     // which don't zero the high bits.
8344     return false;
8345   }
8346 }
8347 
8348 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8349                                                    DAGCombinerInfo &DCI) const {
8350   if (!Subtarget->has16BitInsts() ||
8351       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8352     return SDValue();
8353 
8354   EVT VT = N->getValueType(0);
8355   if (VT != MVT::i32)
8356     return SDValue();
8357 
8358   SDValue Src = N->getOperand(0);
8359   if (Src.getValueType() != MVT::i16)
8360     return SDValue();
8361 
8362   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8363   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8364   if (Src.getOpcode() == ISD::BITCAST) {
8365     SDValue BCSrc = Src.getOperand(0);
8366     if (BCSrc.getValueType() == MVT::f16 &&
8367         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8368       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8369   }
8370 
8371   return SDValue();
8372 }
8373 
8374 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8375                                                         DAGCombinerInfo &DCI)
8376                                                         const {
8377   SDValue Src = N->getOperand(0);
8378   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8379 
8380   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8381       VTSign->getVT() == MVT::i8) ||
8382       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8383       VTSign->getVT() == MVT::i16)) &&
8384       Src.hasOneUse()) {
8385     auto *M = cast<MemSDNode>(Src);
8386     SDValue Ops[] = {
8387       Src.getOperand(0), // Chain
8388       Src.getOperand(1), // rsrc
8389       Src.getOperand(2), // vindex
8390       Src.getOperand(3), // voffset
8391       Src.getOperand(4), // soffset
8392       Src.getOperand(5), // offset
8393       Src.getOperand(6),
8394       Src.getOperand(7)
8395     };
8396     // replace with BUFFER_LOAD_BYTE/SHORT
8397     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8398                                          Src.getOperand(0).getValueType());
8399     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8400                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8401     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8402                                                           ResList,
8403                                                           Ops, M->getMemoryVT(),
8404                                                           M->getMemOperand());
8405     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8406                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8407   }
8408   return SDValue();
8409 }
8410 
8411 SDValue SITargetLowering::performClassCombine(SDNode *N,
8412                                               DAGCombinerInfo &DCI) const {
8413   SelectionDAG &DAG = DCI.DAG;
8414   SDValue Mask = N->getOperand(1);
8415 
8416   // fp_class x, 0 -> false
8417   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8418     if (CMask->isNullValue())
8419       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8420   }
8421 
8422   if (N->getOperand(0).isUndef())
8423     return DAG.getUNDEF(MVT::i1);
8424 
8425   return SDValue();
8426 }
8427 
8428 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8429                                             DAGCombinerInfo &DCI) const {
8430   EVT VT = N->getValueType(0);
8431   SDValue N0 = N->getOperand(0);
8432 
8433   if (N0.isUndef())
8434     return N0;
8435 
8436   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8437                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8438     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8439                            N->getFlags());
8440   }
8441 
8442   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8443 }
8444 
8445 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8446                                        unsigned MaxDepth) const {
8447   unsigned Opcode = Op.getOpcode();
8448   if (Opcode == ISD::FCANONICALIZE)
8449     return true;
8450 
8451   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8452     auto F = CFP->getValueAPF();
8453     if (F.isNaN() && F.isSignaling())
8454       return false;
8455     return !F.isDenormal() || denormalsEnabledForType(Op.getValueType());
8456   }
8457 
8458   // If source is a result of another standard FP operation it is already in
8459   // canonical form.
8460   if (MaxDepth == 0)
8461     return false;
8462 
8463   switch (Opcode) {
8464   // These will flush denorms if required.
8465   case ISD::FADD:
8466   case ISD::FSUB:
8467   case ISD::FMUL:
8468   case ISD::FCEIL:
8469   case ISD::FFLOOR:
8470   case ISD::FMA:
8471   case ISD::FMAD:
8472   case ISD::FSQRT:
8473   case ISD::FDIV:
8474   case ISD::FREM:
8475   case ISD::FP_ROUND:
8476   case ISD::FP_EXTEND:
8477   case AMDGPUISD::FMUL_LEGACY:
8478   case AMDGPUISD::FMAD_FTZ:
8479   case AMDGPUISD::RCP:
8480   case AMDGPUISD::RSQ:
8481   case AMDGPUISD::RSQ_CLAMP:
8482   case AMDGPUISD::RCP_LEGACY:
8483   case AMDGPUISD::RSQ_LEGACY:
8484   case AMDGPUISD::RCP_IFLAG:
8485   case AMDGPUISD::TRIG_PREOP:
8486   case AMDGPUISD::DIV_SCALE:
8487   case AMDGPUISD::DIV_FMAS:
8488   case AMDGPUISD::DIV_FIXUP:
8489   case AMDGPUISD::FRACT:
8490   case AMDGPUISD::LDEXP:
8491   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8492   case AMDGPUISD::CVT_F32_UBYTE0:
8493   case AMDGPUISD::CVT_F32_UBYTE1:
8494   case AMDGPUISD::CVT_F32_UBYTE2:
8495   case AMDGPUISD::CVT_F32_UBYTE3:
8496     return true;
8497 
8498   // It can/will be lowered or combined as a bit operation.
8499   // Need to check their input recursively to handle.
8500   case ISD::FNEG:
8501   case ISD::FABS:
8502   case ISD::FCOPYSIGN:
8503     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8504 
8505   case ISD::FSIN:
8506   case ISD::FCOS:
8507   case ISD::FSINCOS:
8508     return Op.getValueType().getScalarType() != MVT::f16;
8509 
8510   case ISD::FMINNUM:
8511   case ISD::FMAXNUM:
8512   case ISD::FMINNUM_IEEE:
8513   case ISD::FMAXNUM_IEEE:
8514   case AMDGPUISD::CLAMP:
8515   case AMDGPUISD::FMED3:
8516   case AMDGPUISD::FMAX3:
8517   case AMDGPUISD::FMIN3: {
8518     // FIXME: Shouldn't treat the generic operations different based these.
8519     // However, we aren't really required to flush the result from
8520     // minnum/maxnum..
8521 
8522     // snans will be quieted, so we only need to worry about denormals.
8523     if (Subtarget->supportsMinMaxDenormModes() ||
8524         denormalsEnabledForType(Op.getValueType()))
8525       return true;
8526 
8527     // Flushing may be required.
8528     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8529     // targets need to check their input recursively.
8530 
8531     // FIXME: Does this apply with clamp? It's implemented with max.
8532     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8533       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8534         return false;
8535     }
8536 
8537     return true;
8538   }
8539   case ISD::SELECT: {
8540     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8541            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8542   }
8543   case ISD::BUILD_VECTOR: {
8544     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8545       SDValue SrcOp = Op.getOperand(i);
8546       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8547         return false;
8548     }
8549 
8550     return true;
8551   }
8552   case ISD::EXTRACT_VECTOR_ELT:
8553   case ISD::EXTRACT_SUBVECTOR: {
8554     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8555   }
8556   case ISD::INSERT_VECTOR_ELT: {
8557     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8558            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8559   }
8560   case ISD::UNDEF:
8561     // Could be anything.
8562     return false;
8563 
8564   case ISD::BITCAST: {
8565     // Hack round the mess we make when legalizing extract_vector_elt
8566     SDValue Src = Op.getOperand(0);
8567     if (Src.getValueType() == MVT::i16 &&
8568         Src.getOpcode() == ISD::TRUNCATE) {
8569       SDValue TruncSrc = Src.getOperand(0);
8570       if (TruncSrc.getValueType() == MVT::i32 &&
8571           TruncSrc.getOpcode() == ISD::BITCAST &&
8572           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8573         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8574       }
8575     }
8576 
8577     return false;
8578   }
8579   case ISD::INTRINSIC_WO_CHAIN: {
8580     unsigned IntrinsicID
8581       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8582     // TODO: Handle more intrinsics
8583     switch (IntrinsicID) {
8584     case Intrinsic::amdgcn_cvt_pkrtz:
8585     case Intrinsic::amdgcn_cubeid:
8586     case Intrinsic::amdgcn_frexp_mant:
8587     case Intrinsic::amdgcn_fdot2:
8588       return true;
8589     default:
8590       break;
8591     }
8592 
8593     LLVM_FALLTHROUGH;
8594   }
8595   default:
8596     return denormalsEnabledForType(Op.getValueType()) &&
8597            DAG.isKnownNeverSNaN(Op);
8598   }
8599 
8600   llvm_unreachable("invalid operation");
8601 }
8602 
8603 // Constant fold canonicalize.
8604 SDValue SITargetLowering::getCanonicalConstantFP(
8605   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8606   // Flush denormals to 0 if not enabled.
8607   if (C.isDenormal() && !denormalsEnabledForType(VT))
8608     return DAG.getConstantFP(0.0, SL, VT);
8609 
8610   if (C.isNaN()) {
8611     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8612     if (C.isSignaling()) {
8613       // Quiet a signaling NaN.
8614       // FIXME: Is this supposed to preserve payload bits?
8615       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8616     }
8617 
8618     // Make sure it is the canonical NaN bitpattern.
8619     //
8620     // TODO: Can we use -1 as the canonical NaN value since it's an inline
8621     // immediate?
8622     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8623       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8624   }
8625 
8626   // Already canonical.
8627   return DAG.getConstantFP(C, SL, VT);
8628 }
8629 
8630 static bool vectorEltWillFoldAway(SDValue Op) {
8631   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8632 }
8633 
8634 SDValue SITargetLowering::performFCanonicalizeCombine(
8635   SDNode *N,
8636   DAGCombinerInfo &DCI) const {
8637   SelectionDAG &DAG = DCI.DAG;
8638   SDValue N0 = N->getOperand(0);
8639   EVT VT = N->getValueType(0);
8640 
8641   // fcanonicalize undef -> qnan
8642   if (N0.isUndef()) {
8643     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
8644     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8645   }
8646 
8647   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
8648     EVT VT = N->getValueType(0);
8649     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
8650   }
8651 
8652   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8653   //                                                   (fcanonicalize k)
8654   //
8655   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8656 
8657   // TODO: This could be better with wider vectors that will be split to v2f16,
8658   // and to consider uses since there aren't that many packed operations.
8659   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8660       isTypeLegal(MVT::v2f16)) {
8661     SDLoc SL(N);
8662     SDValue NewElts[2];
8663     SDValue Lo = N0.getOperand(0);
8664     SDValue Hi = N0.getOperand(1);
8665     EVT EltVT = Lo.getValueType();
8666 
8667     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
8668       for (unsigned I = 0; I != 2; ++I) {
8669         SDValue Op = N0.getOperand(I);
8670         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8671           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8672                                               CFP->getValueAPF());
8673         } else if (Op.isUndef()) {
8674           // Handled below based on what the other operand is.
8675           NewElts[I] = Op;
8676         } else {
8677           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8678         }
8679       }
8680 
8681       // If one half is undef, and one is constant, perfer a splat vector rather
8682       // than the normal qNaN. If it's a register, prefer 0.0 since that's
8683       // cheaper to use and may be free with a packed operation.
8684       if (NewElts[0].isUndef()) {
8685         if (isa<ConstantFPSDNode>(NewElts[1]))
8686           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8687             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8688       }
8689 
8690       if (NewElts[1].isUndef()) {
8691         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8692           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8693       }
8694 
8695       return DAG.getBuildVector(VT, SL, NewElts);
8696     }
8697   }
8698 
8699   unsigned SrcOpc = N0.getOpcode();
8700 
8701   // If it's free to do so, push canonicalizes further up the source, which may
8702   // find a canonical source.
8703   //
8704   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
8705   // sNaNs.
8706   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
8707     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8708     if (CRHS && N0.hasOneUse()) {
8709       SDLoc SL(N);
8710       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
8711                                    N0.getOperand(0));
8712       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
8713       DCI.AddToWorklist(Canon0.getNode());
8714 
8715       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
8716     }
8717   }
8718 
8719   return isCanonicalized(DAG, N0) ? N0 : SDValue();
8720 }
8721 
8722 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
8723   switch (Opc) {
8724   case ISD::FMAXNUM:
8725   case ISD::FMAXNUM_IEEE:
8726     return AMDGPUISD::FMAX3;
8727   case ISD::SMAX:
8728     return AMDGPUISD::SMAX3;
8729   case ISD::UMAX:
8730     return AMDGPUISD::UMAX3;
8731   case ISD::FMINNUM:
8732   case ISD::FMINNUM_IEEE:
8733     return AMDGPUISD::FMIN3;
8734   case ISD::SMIN:
8735     return AMDGPUISD::SMIN3;
8736   case ISD::UMIN:
8737     return AMDGPUISD::UMIN3;
8738   default:
8739     llvm_unreachable("Not a min/max opcode");
8740   }
8741 }
8742 
8743 SDValue SITargetLowering::performIntMed3ImmCombine(
8744   SelectionDAG &DAG, const SDLoc &SL,
8745   SDValue Op0, SDValue Op1, bool Signed) const {
8746   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
8747   if (!K1)
8748     return SDValue();
8749 
8750   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
8751   if (!K0)
8752     return SDValue();
8753 
8754   if (Signed) {
8755     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
8756       return SDValue();
8757   } else {
8758     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
8759       return SDValue();
8760   }
8761 
8762   EVT VT = K0->getValueType(0);
8763   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
8764   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
8765     return DAG.getNode(Med3Opc, SL, VT,
8766                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
8767   }
8768 
8769   // If there isn't a 16-bit med3 operation, convert to 32-bit.
8770   MVT NVT = MVT::i32;
8771   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8772 
8773   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
8774   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
8775   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
8776 
8777   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
8778   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
8779 }
8780 
8781 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
8782   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
8783     return C;
8784 
8785   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
8786     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
8787       return C;
8788   }
8789 
8790   return nullptr;
8791 }
8792 
8793 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
8794                                                   const SDLoc &SL,
8795                                                   SDValue Op0,
8796                                                   SDValue Op1) const {
8797   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
8798   if (!K1)
8799     return SDValue();
8800 
8801   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
8802   if (!K0)
8803     return SDValue();
8804 
8805   // Ordered >= (although NaN inputs should have folded away by now).
8806   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
8807   if (Cmp == APFloat::cmpGreaterThan)
8808     return SDValue();
8809 
8810   const MachineFunction &MF = DAG.getMachineFunction();
8811   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8812 
8813   // TODO: Check IEEE bit enabled?
8814   EVT VT = Op0.getValueType();
8815   if (Info->getMode().DX10Clamp) {
8816     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
8817     // hardware fmed3 behavior converting to a min.
8818     // FIXME: Should this be allowing -0.0?
8819     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
8820       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
8821   }
8822 
8823   // med3 for f16 is only available on gfx9+, and not available for v2f16.
8824   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
8825     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
8826     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
8827     // then give the other result, which is different from med3 with a NaN
8828     // input.
8829     SDValue Var = Op0.getOperand(0);
8830     if (!DAG.isKnownNeverSNaN(Var))
8831       return SDValue();
8832 
8833     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8834 
8835     if ((!K0->hasOneUse() ||
8836          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
8837         (!K1->hasOneUse() ||
8838          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
8839       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
8840                          Var, SDValue(K0, 0), SDValue(K1, 0));
8841     }
8842   }
8843 
8844   return SDValue();
8845 }
8846 
8847 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
8848                                                DAGCombinerInfo &DCI) const {
8849   SelectionDAG &DAG = DCI.DAG;
8850 
8851   EVT VT = N->getValueType(0);
8852   unsigned Opc = N->getOpcode();
8853   SDValue Op0 = N->getOperand(0);
8854   SDValue Op1 = N->getOperand(1);
8855 
8856   // Only do this if the inner op has one use since this will just increases
8857   // register pressure for no benefit.
8858 
8859   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
8860       !VT.isVector() &&
8861       (VT == MVT::i32 || VT == MVT::f32 ||
8862        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
8863     // max(max(a, b), c) -> max3(a, b, c)
8864     // min(min(a, b), c) -> min3(a, b, c)
8865     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
8866       SDLoc DL(N);
8867       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
8868                          DL,
8869                          N->getValueType(0),
8870                          Op0.getOperand(0),
8871                          Op0.getOperand(1),
8872                          Op1);
8873     }
8874 
8875     // Try commuted.
8876     // max(a, max(b, c)) -> max3(a, b, c)
8877     // min(a, min(b, c)) -> min3(a, b, c)
8878     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
8879       SDLoc DL(N);
8880       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
8881                          DL,
8882                          N->getValueType(0),
8883                          Op0,
8884                          Op1.getOperand(0),
8885                          Op1.getOperand(1));
8886     }
8887   }
8888 
8889   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
8890   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
8891     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
8892       return Med3;
8893   }
8894 
8895   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
8896     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
8897       return Med3;
8898   }
8899 
8900   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
8901   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
8902        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
8903        (Opc == AMDGPUISD::FMIN_LEGACY &&
8904         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
8905       (VT == MVT::f32 || VT == MVT::f64 ||
8906        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
8907        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
8908       Op0.hasOneUse()) {
8909     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
8910       return Res;
8911   }
8912 
8913   return SDValue();
8914 }
8915 
8916 static bool isClampZeroToOne(SDValue A, SDValue B) {
8917   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
8918     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
8919       // FIXME: Should this be allowing -0.0?
8920       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
8921              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
8922     }
8923   }
8924 
8925   return false;
8926 }
8927 
8928 // FIXME: Should only worry about snans for version with chain.
8929 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
8930                                               DAGCombinerInfo &DCI) const {
8931   EVT VT = N->getValueType(0);
8932   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
8933   // NaNs. With a NaN input, the order of the operands may change the result.
8934 
8935   SelectionDAG &DAG = DCI.DAG;
8936   SDLoc SL(N);
8937 
8938   SDValue Src0 = N->getOperand(0);
8939   SDValue Src1 = N->getOperand(1);
8940   SDValue Src2 = N->getOperand(2);
8941 
8942   if (isClampZeroToOne(Src0, Src1)) {
8943     // const_a, const_b, x -> clamp is safe in all cases including signaling
8944     // nans.
8945     // FIXME: Should this be allowing -0.0?
8946     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
8947   }
8948 
8949   const MachineFunction &MF = DAG.getMachineFunction();
8950   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8951 
8952   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
8953   // handling no dx10-clamp?
8954   if (Info->getMode().DX10Clamp) {
8955     // If NaNs is clamped to 0, we are free to reorder the inputs.
8956 
8957     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
8958       std::swap(Src0, Src1);
8959 
8960     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
8961       std::swap(Src1, Src2);
8962 
8963     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
8964       std::swap(Src0, Src1);
8965 
8966     if (isClampZeroToOne(Src1, Src2))
8967       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
8968   }
8969 
8970   return SDValue();
8971 }
8972 
8973 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
8974                                                  DAGCombinerInfo &DCI) const {
8975   SDValue Src0 = N->getOperand(0);
8976   SDValue Src1 = N->getOperand(1);
8977   if (Src0.isUndef() && Src1.isUndef())
8978     return DCI.DAG.getUNDEF(N->getValueType(0));
8979   return SDValue();
8980 }
8981 
8982 SDValue SITargetLowering::performExtractVectorEltCombine(
8983   SDNode *N, DAGCombinerInfo &DCI) const {
8984   SDValue Vec = N->getOperand(0);
8985   SelectionDAG &DAG = DCI.DAG;
8986 
8987   EVT VecVT = Vec.getValueType();
8988   EVT EltVT = VecVT.getVectorElementType();
8989 
8990   if ((Vec.getOpcode() == ISD::FNEG ||
8991        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
8992     SDLoc SL(N);
8993     EVT EltVT = N->getValueType(0);
8994     SDValue Idx = N->getOperand(1);
8995     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8996                               Vec.getOperand(0), Idx);
8997     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
8998   }
8999 
9000   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9001   //    =>
9002   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9003   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9004   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9005   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9006     SDLoc SL(N);
9007     EVT EltVT = N->getValueType(0);
9008     SDValue Idx = N->getOperand(1);
9009     unsigned Opc = Vec.getOpcode();
9010 
9011     switch(Opc) {
9012     default:
9013       break;
9014       // TODO: Support other binary operations.
9015     case ISD::FADD:
9016     case ISD::FSUB:
9017     case ISD::FMUL:
9018     case ISD::ADD:
9019     case ISD::UMIN:
9020     case ISD::UMAX:
9021     case ISD::SMIN:
9022     case ISD::SMAX:
9023     case ISD::FMAXNUM:
9024     case ISD::FMINNUM:
9025     case ISD::FMAXNUM_IEEE:
9026     case ISD::FMINNUM_IEEE: {
9027       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9028                                  Vec.getOperand(0), Idx);
9029       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9030                                  Vec.getOperand(1), Idx);
9031 
9032       DCI.AddToWorklist(Elt0.getNode());
9033       DCI.AddToWorklist(Elt1.getNode());
9034       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9035     }
9036     }
9037   }
9038 
9039   unsigned VecSize = VecVT.getSizeInBits();
9040   unsigned EltSize = EltVT.getSizeInBits();
9041 
9042   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9043   // This elminates non-constant index and subsequent movrel or scratch access.
9044   // Sub-dword vectors of size 2 dword or less have better implementation.
9045   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9046   // instructions.
9047   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9048       !isa<ConstantSDNode>(N->getOperand(1))) {
9049     SDLoc SL(N);
9050     SDValue Idx = N->getOperand(1);
9051     EVT IdxVT = Idx.getValueType();
9052     SDValue V;
9053     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9054       SDValue IC = DAG.getConstant(I, SL, IdxVT);
9055       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9056       if (I == 0)
9057         V = Elt;
9058       else
9059         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9060     }
9061     return V;
9062   }
9063 
9064   if (!DCI.isBeforeLegalize())
9065     return SDValue();
9066 
9067   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9068   // elements. This exposes more load reduction opportunities by replacing
9069   // multiple small extract_vector_elements with a single 32-bit extract.
9070   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9071   if (isa<MemSDNode>(Vec) &&
9072       EltSize <= 16 &&
9073       EltVT.isByteSized() &&
9074       VecSize > 32 &&
9075       VecSize % 32 == 0 &&
9076       Idx) {
9077     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9078 
9079     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9080     unsigned EltIdx = BitIndex / 32;
9081     unsigned LeftoverBitIdx = BitIndex % 32;
9082     SDLoc SL(N);
9083 
9084     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9085     DCI.AddToWorklist(Cast.getNode());
9086 
9087     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9088                               DAG.getConstant(EltIdx, SL, MVT::i32));
9089     DCI.AddToWorklist(Elt.getNode());
9090     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9091                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9092     DCI.AddToWorklist(Srl.getNode());
9093 
9094     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9095     DCI.AddToWorklist(Trunc.getNode());
9096     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9097   }
9098 
9099   return SDValue();
9100 }
9101 
9102 SDValue
9103 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9104                                                 DAGCombinerInfo &DCI) const {
9105   SDValue Vec = N->getOperand(0);
9106   SDValue Idx = N->getOperand(2);
9107   EVT VecVT = Vec.getValueType();
9108   EVT EltVT = VecVT.getVectorElementType();
9109   unsigned VecSize = VecVT.getSizeInBits();
9110   unsigned EltSize = EltVT.getSizeInBits();
9111 
9112   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9113   // => BUILD_VECTOR n x select (e, const-idx)
9114   // This elminates non-constant index and subsequent movrel or scratch access.
9115   // Sub-dword vectors of size 2 dword or less have better implementation.
9116   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9117   // instructions.
9118   if (isa<ConstantSDNode>(Idx) ||
9119       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9120     return SDValue();
9121 
9122   SelectionDAG &DAG = DCI.DAG;
9123   SDLoc SL(N);
9124   SDValue Ins = N->getOperand(1);
9125   EVT IdxVT = Idx.getValueType();
9126 
9127   SmallVector<SDValue, 16> Ops;
9128   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9129     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9130     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9131     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9132     Ops.push_back(V);
9133   }
9134 
9135   return DAG.getBuildVector(VecVT, SL, Ops);
9136 }
9137 
9138 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9139                                           const SDNode *N0,
9140                                           const SDNode *N1) const {
9141   EVT VT = N0->getValueType(0);
9142 
9143   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9144   // support denormals ever.
9145   if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
9146        (VT == MVT::f16 && !Subtarget->hasFP16Denormals() &&
9147         getSubtarget()->hasMadF16())) &&
9148        isOperationLegal(ISD::FMAD, VT))
9149     return ISD::FMAD;
9150 
9151   const TargetOptions &Options = DAG.getTarget().Options;
9152   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9153        (N0->getFlags().hasAllowContract() &&
9154         N1->getFlags().hasAllowContract())) &&
9155       isFMAFasterThanFMulAndFAdd(VT)) {
9156     return ISD::FMA;
9157   }
9158 
9159   return 0;
9160 }
9161 
9162 // For a reassociatable opcode perform:
9163 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9164 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9165                                                SelectionDAG &DAG) const {
9166   EVT VT = N->getValueType(0);
9167   if (VT != MVT::i32 && VT != MVT::i64)
9168     return SDValue();
9169 
9170   unsigned Opc = N->getOpcode();
9171   SDValue Op0 = N->getOperand(0);
9172   SDValue Op1 = N->getOperand(1);
9173 
9174   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9175     return SDValue();
9176 
9177   if (Op0->isDivergent())
9178     std::swap(Op0, Op1);
9179 
9180   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9181     return SDValue();
9182 
9183   SDValue Op2 = Op1.getOperand(1);
9184   Op1 = Op1.getOperand(0);
9185   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9186     return SDValue();
9187 
9188   if (Op1->isDivergent())
9189     std::swap(Op1, Op2);
9190 
9191   // If either operand is constant this will conflict with
9192   // DAGCombiner::ReassociateOps().
9193   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9194       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9195     return SDValue();
9196 
9197   SDLoc SL(N);
9198   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9199   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9200 }
9201 
9202 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9203                            EVT VT,
9204                            SDValue N0, SDValue N1, SDValue N2,
9205                            bool Signed) {
9206   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9207   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9208   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9209   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9210 }
9211 
9212 SDValue SITargetLowering::performAddCombine(SDNode *N,
9213                                             DAGCombinerInfo &DCI) const {
9214   SelectionDAG &DAG = DCI.DAG;
9215   EVT VT = N->getValueType(0);
9216   SDLoc SL(N);
9217   SDValue LHS = N->getOperand(0);
9218   SDValue RHS = N->getOperand(1);
9219 
9220   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9221       && Subtarget->hasMad64_32() &&
9222       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9223       VT.getScalarSizeInBits() <= 64) {
9224     if (LHS.getOpcode() != ISD::MUL)
9225       std::swap(LHS, RHS);
9226 
9227     SDValue MulLHS = LHS.getOperand(0);
9228     SDValue MulRHS = LHS.getOperand(1);
9229     SDValue AddRHS = RHS;
9230 
9231     // TODO: Maybe restrict if SGPR inputs.
9232     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9233         numBitsUnsigned(MulRHS, DAG) <= 32) {
9234       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9235       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9236       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9237       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9238     }
9239 
9240     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9241       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9242       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9243       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9244       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9245     }
9246 
9247     return SDValue();
9248   }
9249 
9250   if (SDValue V = reassociateScalarOps(N, DAG)) {
9251     return V;
9252   }
9253 
9254   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9255     return SDValue();
9256 
9257   // add x, zext (setcc) => addcarry x, 0, setcc
9258   // add x, sext (setcc) => subcarry x, 0, setcc
9259   unsigned Opc = LHS.getOpcode();
9260   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9261       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9262     std::swap(RHS, LHS);
9263 
9264   Opc = RHS.getOpcode();
9265   switch (Opc) {
9266   default: break;
9267   case ISD::ZERO_EXTEND:
9268   case ISD::SIGN_EXTEND:
9269   case ISD::ANY_EXTEND: {
9270     auto Cond = RHS.getOperand(0);
9271     if (!isBoolSGPR(Cond))
9272       break;
9273     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9274     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9275     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9276     return DAG.getNode(Opc, SL, VTList, Args);
9277   }
9278   case ISD::ADDCARRY: {
9279     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9280     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9281     if (!C || C->getZExtValue() != 0) break;
9282     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9283     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9284   }
9285   }
9286   return SDValue();
9287 }
9288 
9289 SDValue SITargetLowering::performSubCombine(SDNode *N,
9290                                             DAGCombinerInfo &DCI) const {
9291   SelectionDAG &DAG = DCI.DAG;
9292   EVT VT = N->getValueType(0);
9293 
9294   if (VT != MVT::i32)
9295     return SDValue();
9296 
9297   SDLoc SL(N);
9298   SDValue LHS = N->getOperand(0);
9299   SDValue RHS = N->getOperand(1);
9300 
9301   if (LHS.getOpcode() == ISD::SUBCARRY) {
9302     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9303     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9304     if (!C || !C->isNullValue())
9305       return SDValue();
9306     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9307     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9308   }
9309   return SDValue();
9310 }
9311 
9312 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9313   DAGCombinerInfo &DCI) const {
9314 
9315   if (N->getValueType(0) != MVT::i32)
9316     return SDValue();
9317 
9318   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9319   if (!C || C->getZExtValue() != 0)
9320     return SDValue();
9321 
9322   SelectionDAG &DAG = DCI.DAG;
9323   SDValue LHS = N->getOperand(0);
9324 
9325   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9326   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9327   unsigned LHSOpc = LHS.getOpcode();
9328   unsigned Opc = N->getOpcode();
9329   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9330       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9331     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9332     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9333   }
9334   return SDValue();
9335 }
9336 
9337 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9338                                              DAGCombinerInfo &DCI) const {
9339   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9340     return SDValue();
9341 
9342   SelectionDAG &DAG = DCI.DAG;
9343   EVT VT = N->getValueType(0);
9344 
9345   SDLoc SL(N);
9346   SDValue LHS = N->getOperand(0);
9347   SDValue RHS = N->getOperand(1);
9348 
9349   // These should really be instruction patterns, but writing patterns with
9350   // source modiifiers is a pain.
9351 
9352   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9353   if (LHS.getOpcode() == ISD::FADD) {
9354     SDValue A = LHS.getOperand(0);
9355     if (A == LHS.getOperand(1)) {
9356       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9357       if (FusedOp != 0) {
9358         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9359         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9360       }
9361     }
9362   }
9363 
9364   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9365   if (RHS.getOpcode() == ISD::FADD) {
9366     SDValue A = RHS.getOperand(0);
9367     if (A == RHS.getOperand(1)) {
9368       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9369       if (FusedOp != 0) {
9370         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9371         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9372       }
9373     }
9374   }
9375 
9376   return SDValue();
9377 }
9378 
9379 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9380                                              DAGCombinerInfo &DCI) const {
9381   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9382     return SDValue();
9383 
9384   SelectionDAG &DAG = DCI.DAG;
9385   SDLoc SL(N);
9386   EVT VT = N->getValueType(0);
9387   assert(!VT.isVector());
9388 
9389   // Try to get the fneg to fold into the source modifier. This undoes generic
9390   // DAG combines and folds them into the mad.
9391   //
9392   // Only do this if we are not trying to support denormals. v_mad_f32 does
9393   // not support denormals ever.
9394   SDValue LHS = N->getOperand(0);
9395   SDValue RHS = N->getOperand(1);
9396   if (LHS.getOpcode() == ISD::FADD) {
9397     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9398     SDValue A = LHS.getOperand(0);
9399     if (A == LHS.getOperand(1)) {
9400       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9401       if (FusedOp != 0){
9402         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9403         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9404 
9405         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9406       }
9407     }
9408   }
9409 
9410   if (RHS.getOpcode() == ISD::FADD) {
9411     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9412 
9413     SDValue A = RHS.getOperand(0);
9414     if (A == RHS.getOperand(1)) {
9415       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9416       if (FusedOp != 0){
9417         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9418         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9419       }
9420     }
9421   }
9422 
9423   return SDValue();
9424 }
9425 
9426 SDValue SITargetLowering::performFMACombine(SDNode *N,
9427                                             DAGCombinerInfo &DCI) const {
9428   SelectionDAG &DAG = DCI.DAG;
9429   EVT VT = N->getValueType(0);
9430   SDLoc SL(N);
9431 
9432   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9433     return SDValue();
9434 
9435   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9436   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9437   SDValue Op1 = N->getOperand(0);
9438   SDValue Op2 = N->getOperand(1);
9439   SDValue FMA = N->getOperand(2);
9440 
9441   if (FMA.getOpcode() != ISD::FMA ||
9442       Op1.getOpcode() != ISD::FP_EXTEND ||
9443       Op2.getOpcode() != ISD::FP_EXTEND)
9444     return SDValue();
9445 
9446   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9447   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9448   // is sufficient to allow generaing fdot2.
9449   const TargetOptions &Options = DAG.getTarget().Options;
9450   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9451       (N->getFlags().hasAllowContract() &&
9452        FMA->getFlags().hasAllowContract())) {
9453     Op1 = Op1.getOperand(0);
9454     Op2 = Op2.getOperand(0);
9455     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9456         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9457       return SDValue();
9458 
9459     SDValue Vec1 = Op1.getOperand(0);
9460     SDValue Idx1 = Op1.getOperand(1);
9461     SDValue Vec2 = Op2.getOperand(0);
9462 
9463     SDValue FMAOp1 = FMA.getOperand(0);
9464     SDValue FMAOp2 = FMA.getOperand(1);
9465     SDValue FMAAcc = FMA.getOperand(2);
9466 
9467     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9468         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9469       return SDValue();
9470 
9471     FMAOp1 = FMAOp1.getOperand(0);
9472     FMAOp2 = FMAOp2.getOperand(0);
9473     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9474         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9475       return SDValue();
9476 
9477     SDValue Vec3 = FMAOp1.getOperand(0);
9478     SDValue Vec4 = FMAOp2.getOperand(0);
9479     SDValue Idx2 = FMAOp1.getOperand(1);
9480 
9481     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9482         // Idx1 and Idx2 cannot be the same.
9483         Idx1 == Idx2)
9484       return SDValue();
9485 
9486     if (Vec1 == Vec2 || Vec3 == Vec4)
9487       return SDValue();
9488 
9489     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9490       return SDValue();
9491 
9492     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9493         (Vec1 == Vec4 && Vec2 == Vec3)) {
9494       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9495                          DAG.getTargetConstant(0, SL, MVT::i1));
9496     }
9497   }
9498   return SDValue();
9499 }
9500 
9501 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9502                                               DAGCombinerInfo &DCI) const {
9503   SelectionDAG &DAG = DCI.DAG;
9504   SDLoc SL(N);
9505 
9506   SDValue LHS = N->getOperand(0);
9507   SDValue RHS = N->getOperand(1);
9508   EVT VT = LHS.getValueType();
9509   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9510 
9511   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9512   if (!CRHS) {
9513     CRHS = dyn_cast<ConstantSDNode>(LHS);
9514     if (CRHS) {
9515       std::swap(LHS, RHS);
9516       CC = getSetCCSwappedOperands(CC);
9517     }
9518   }
9519 
9520   if (CRHS) {
9521     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9522         isBoolSGPR(LHS.getOperand(0))) {
9523       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9524       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9525       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9526       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9527       if ((CRHS->isAllOnesValue() &&
9528            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9529           (CRHS->isNullValue() &&
9530            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9531         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9532                            DAG.getConstant(-1, SL, MVT::i1));
9533       if ((CRHS->isAllOnesValue() &&
9534            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9535           (CRHS->isNullValue() &&
9536            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9537         return LHS.getOperand(0);
9538     }
9539 
9540     uint64_t CRHSVal = CRHS->getZExtValue();
9541     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9542         LHS.getOpcode() == ISD::SELECT &&
9543         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9544         isa<ConstantSDNode>(LHS.getOperand(2)) &&
9545         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9546         isBoolSGPR(LHS.getOperand(0))) {
9547       // Given CT != FT:
9548       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9549       // setcc (select cc, CT, CF), CF, ne => cc
9550       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9551       // setcc (select cc, CT, CF), CT, eq => cc
9552       uint64_t CT = LHS.getConstantOperandVal(1);
9553       uint64_t CF = LHS.getConstantOperandVal(2);
9554 
9555       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9556           (CT == CRHSVal && CC == ISD::SETNE))
9557         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9558                            DAG.getConstant(-1, SL, MVT::i1));
9559       if ((CF == CRHSVal && CC == ISD::SETNE) ||
9560           (CT == CRHSVal && CC == ISD::SETEQ))
9561         return LHS.getOperand(0);
9562     }
9563   }
9564 
9565   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9566                                            VT != MVT::f16))
9567     return SDValue();
9568 
9569   // Match isinf/isfinite pattern
9570   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
9571   // (fcmp one (fabs x), inf) -> (fp_class x,
9572   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9573   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
9574     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9575     if (!CRHS)
9576       return SDValue();
9577 
9578     const APFloat &APF = CRHS->getValueAPF();
9579     if (APF.isInfinity() && !APF.isNegative()) {
9580       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9581                                  SIInstrFlags::N_INFINITY;
9582       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9583                                     SIInstrFlags::P_ZERO |
9584                                     SIInstrFlags::N_NORMAL |
9585                                     SIInstrFlags::P_NORMAL |
9586                                     SIInstrFlags::N_SUBNORMAL |
9587                                     SIInstrFlags::P_SUBNORMAL;
9588       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
9589       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9590                          DAG.getConstant(Mask, SL, MVT::i32));
9591     }
9592   }
9593 
9594   return SDValue();
9595 }
9596 
9597 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9598                                                      DAGCombinerInfo &DCI) const {
9599   SelectionDAG &DAG = DCI.DAG;
9600   SDLoc SL(N);
9601   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9602 
9603   SDValue Src = N->getOperand(0);
9604   SDValue Srl = N->getOperand(0);
9605   if (Srl.getOpcode() == ISD::ZERO_EXTEND)
9606     Srl = Srl.getOperand(0);
9607 
9608   // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
9609   if (Srl.getOpcode() == ISD::SRL) {
9610     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9611     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9612     // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
9613 
9614     if (const ConstantSDNode *C =
9615         dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
9616       Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
9617                                EVT(MVT::i32));
9618 
9619       unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
9620       if (SrcOffset < 32 && SrcOffset % 8 == 0) {
9621         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
9622                            MVT::f32, Srl);
9623       }
9624     }
9625   }
9626 
9627   APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9628 
9629   KnownBits Known;
9630   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9631                                         !DCI.isBeforeLegalizeOps());
9632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9633   if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
9634     DCI.CommitTargetLoweringOpt(TLO);
9635   }
9636 
9637   return SDValue();
9638 }
9639 
9640 SDValue SITargetLowering::performClampCombine(SDNode *N,
9641                                               DAGCombinerInfo &DCI) const {
9642   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
9643   if (!CSrc)
9644     return SDValue();
9645 
9646   const MachineFunction &MF = DCI.DAG.getMachineFunction();
9647   const APFloat &F = CSrc->getValueAPF();
9648   APFloat Zero = APFloat::getZero(F.getSemantics());
9649   APFloat::cmpResult Cmp0 = F.compare(Zero);
9650   if (Cmp0 == APFloat::cmpLessThan ||
9651       (Cmp0 == APFloat::cmpUnordered &&
9652        MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
9653     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9654   }
9655 
9656   APFloat One(F.getSemantics(), "1.0");
9657   APFloat::cmpResult Cmp1 = F.compare(One);
9658   if (Cmp1 == APFloat::cmpGreaterThan)
9659     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9660 
9661   return SDValue(CSrc, 0);
9662 }
9663 
9664 
9665 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
9666                                             DAGCombinerInfo &DCI) const {
9667   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9668     return SDValue();
9669   switch (N->getOpcode()) {
9670   default:
9671     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9672   case ISD::ADD:
9673     return performAddCombine(N, DCI);
9674   case ISD::SUB:
9675     return performSubCombine(N, DCI);
9676   case ISD::ADDCARRY:
9677   case ISD::SUBCARRY:
9678     return performAddCarrySubCarryCombine(N, DCI);
9679   case ISD::FADD:
9680     return performFAddCombine(N, DCI);
9681   case ISD::FSUB:
9682     return performFSubCombine(N, DCI);
9683   case ISD::SETCC:
9684     return performSetCCCombine(N, DCI);
9685   case ISD::FMAXNUM:
9686   case ISD::FMINNUM:
9687   case ISD::FMAXNUM_IEEE:
9688   case ISD::FMINNUM_IEEE:
9689   case ISD::SMAX:
9690   case ISD::SMIN:
9691   case ISD::UMAX:
9692   case ISD::UMIN:
9693   case AMDGPUISD::FMIN_LEGACY:
9694   case AMDGPUISD::FMAX_LEGACY:
9695     return performMinMaxCombine(N, DCI);
9696   case ISD::FMA:
9697     return performFMACombine(N, DCI);
9698   case ISD::LOAD: {
9699     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
9700       return Widended;
9701     LLVM_FALLTHROUGH;
9702   }
9703   case ISD::STORE:
9704   case ISD::ATOMIC_LOAD:
9705   case ISD::ATOMIC_STORE:
9706   case ISD::ATOMIC_CMP_SWAP:
9707   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
9708   case ISD::ATOMIC_SWAP:
9709   case ISD::ATOMIC_LOAD_ADD:
9710   case ISD::ATOMIC_LOAD_SUB:
9711   case ISD::ATOMIC_LOAD_AND:
9712   case ISD::ATOMIC_LOAD_OR:
9713   case ISD::ATOMIC_LOAD_XOR:
9714   case ISD::ATOMIC_LOAD_NAND:
9715   case ISD::ATOMIC_LOAD_MIN:
9716   case ISD::ATOMIC_LOAD_MAX:
9717   case ISD::ATOMIC_LOAD_UMIN:
9718   case ISD::ATOMIC_LOAD_UMAX:
9719   case ISD::ATOMIC_LOAD_FADD:
9720   case AMDGPUISD::ATOMIC_INC:
9721   case AMDGPUISD::ATOMIC_DEC:
9722   case AMDGPUISD::ATOMIC_LOAD_FMIN:
9723   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
9724     if (DCI.isBeforeLegalize())
9725       break;
9726     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
9727   case ISD::AND:
9728     return performAndCombine(N, DCI);
9729   case ISD::OR:
9730     return performOrCombine(N, DCI);
9731   case ISD::XOR:
9732     return performXorCombine(N, DCI);
9733   case ISD::ZERO_EXTEND:
9734     return performZeroExtendCombine(N, DCI);
9735   case ISD::SIGN_EXTEND_INREG:
9736     return performSignExtendInRegCombine(N , DCI);
9737   case AMDGPUISD::FP_CLASS:
9738     return performClassCombine(N, DCI);
9739   case ISD::FCANONICALIZE:
9740     return performFCanonicalizeCombine(N, DCI);
9741   case AMDGPUISD::RCP:
9742     return performRcpCombine(N, DCI);
9743   case AMDGPUISD::FRACT:
9744   case AMDGPUISD::RSQ:
9745   case AMDGPUISD::RCP_LEGACY:
9746   case AMDGPUISD::RSQ_LEGACY:
9747   case AMDGPUISD::RCP_IFLAG:
9748   case AMDGPUISD::RSQ_CLAMP:
9749   case AMDGPUISD::LDEXP: {
9750     SDValue Src = N->getOperand(0);
9751     if (Src.isUndef())
9752       return Src;
9753     break;
9754   }
9755   case ISD::SINT_TO_FP:
9756   case ISD::UINT_TO_FP:
9757     return performUCharToFloatCombine(N, DCI);
9758   case AMDGPUISD::CVT_F32_UBYTE0:
9759   case AMDGPUISD::CVT_F32_UBYTE1:
9760   case AMDGPUISD::CVT_F32_UBYTE2:
9761   case AMDGPUISD::CVT_F32_UBYTE3:
9762     return performCvtF32UByteNCombine(N, DCI);
9763   case AMDGPUISD::FMED3:
9764     return performFMed3Combine(N, DCI);
9765   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9766     return performCvtPkRTZCombine(N, DCI);
9767   case AMDGPUISD::CLAMP:
9768     return performClampCombine(N, DCI);
9769   case ISD::SCALAR_TO_VECTOR: {
9770     SelectionDAG &DAG = DCI.DAG;
9771     EVT VT = N->getValueType(0);
9772 
9773     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
9774     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
9775       SDLoc SL(N);
9776       SDValue Src = N->getOperand(0);
9777       EVT EltVT = Src.getValueType();
9778       if (EltVT == MVT::f16)
9779         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
9780 
9781       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
9782       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
9783     }
9784 
9785     break;
9786   }
9787   case ISD::EXTRACT_VECTOR_ELT:
9788     return performExtractVectorEltCombine(N, DCI);
9789   case ISD::INSERT_VECTOR_ELT:
9790     return performInsertVectorEltCombine(N, DCI);
9791   }
9792   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9793 }
9794 
9795 /// Helper function for adjustWritemask
9796 static unsigned SubIdx2Lane(unsigned Idx) {
9797   switch (Idx) {
9798   default: return 0;
9799   case AMDGPU::sub0: return 0;
9800   case AMDGPU::sub1: return 1;
9801   case AMDGPU::sub2: return 2;
9802   case AMDGPU::sub3: return 3;
9803   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
9804   }
9805 }
9806 
9807 /// Adjust the writemask of MIMG instructions
9808 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
9809                                           SelectionDAG &DAG) const {
9810   unsigned Opcode = Node->getMachineOpcode();
9811 
9812   // Subtract 1 because the vdata output is not a MachineSDNode operand.
9813   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
9814   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
9815     return Node; // not implemented for D16
9816 
9817   SDNode *Users[5] = { nullptr };
9818   unsigned Lane = 0;
9819   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
9820   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
9821   unsigned NewDmask = 0;
9822   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
9823   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
9824   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
9825                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
9826   unsigned TFCLane = 0;
9827   bool HasChain = Node->getNumValues() > 1;
9828 
9829   if (OldDmask == 0) {
9830     // These are folded out, but on the chance it happens don't assert.
9831     return Node;
9832   }
9833 
9834   unsigned OldBitsSet = countPopulation(OldDmask);
9835   // Work out which is the TFE/LWE lane if that is enabled.
9836   if (UsesTFC) {
9837     TFCLane = OldBitsSet;
9838   }
9839 
9840   // Try to figure out the used register components
9841   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
9842        I != E; ++I) {
9843 
9844     // Don't look at users of the chain.
9845     if (I.getUse().getResNo() != 0)
9846       continue;
9847 
9848     // Abort if we can't understand the usage
9849     if (!I->isMachineOpcode() ||
9850         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
9851       return Node;
9852 
9853     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
9854     // Note that subregs are packed, i.e. Lane==0 is the first bit set
9855     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
9856     // set, etc.
9857     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
9858 
9859     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
9860     if (UsesTFC && Lane == TFCLane) {
9861       Users[Lane] = *I;
9862     } else {
9863       // Set which texture component corresponds to the lane.
9864       unsigned Comp;
9865       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
9866         Comp = countTrailingZeros(Dmask);
9867         Dmask &= ~(1 << Comp);
9868       }
9869 
9870       // Abort if we have more than one user per component.
9871       if (Users[Lane])
9872         return Node;
9873 
9874       Users[Lane] = *I;
9875       NewDmask |= 1 << Comp;
9876     }
9877   }
9878 
9879   // Don't allow 0 dmask, as hardware assumes one channel enabled.
9880   bool NoChannels = !NewDmask;
9881   if (NoChannels) {
9882     if (!UsesTFC) {
9883       // No uses of the result and not using TFC. Then do nothing.
9884       return Node;
9885     }
9886     // If the original dmask has one channel - then nothing to do
9887     if (OldBitsSet == 1)
9888       return Node;
9889     // Use an arbitrary dmask - required for the instruction to work
9890     NewDmask = 1;
9891   }
9892   // Abort if there's no change
9893   if (NewDmask == OldDmask)
9894     return Node;
9895 
9896   unsigned BitsSet = countPopulation(NewDmask);
9897 
9898   // Check for TFE or LWE - increase the number of channels by one to account
9899   // for the extra return value
9900   // This will need adjustment for D16 if this is also included in
9901   // adjustWriteMask (this function) but at present D16 are excluded.
9902   unsigned NewChannels = BitsSet + UsesTFC;
9903 
9904   int NewOpcode =
9905       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
9906   assert(NewOpcode != -1 &&
9907          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
9908          "failed to find equivalent MIMG op");
9909 
9910   // Adjust the writemask in the node
9911   SmallVector<SDValue, 12> Ops;
9912   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
9913   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
9914   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
9915 
9916   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
9917 
9918   MVT ResultVT = NewChannels == 1 ?
9919     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
9920                            NewChannels == 5 ? 8 : NewChannels);
9921   SDVTList NewVTList = HasChain ?
9922     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
9923 
9924 
9925   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
9926                                               NewVTList, Ops);
9927 
9928   if (HasChain) {
9929     // Update chain.
9930     DAG.setNodeMemRefs(NewNode, Node->memoperands());
9931     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
9932   }
9933 
9934   if (NewChannels == 1) {
9935     assert(Node->hasNUsesOfValue(1, 0));
9936     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
9937                                       SDLoc(Node), Users[Lane]->getValueType(0),
9938                                       SDValue(NewNode, 0));
9939     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
9940     return nullptr;
9941   }
9942 
9943   // Update the users of the node with the new indices
9944   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
9945     SDNode *User = Users[i];
9946     if (!User) {
9947       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
9948       // Users[0] is still nullptr because channel 0 doesn't really have a use.
9949       if (i || !NoChannels)
9950         continue;
9951     } else {
9952       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
9953       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
9954     }
9955 
9956     switch (Idx) {
9957     default: break;
9958     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
9959     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
9960     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
9961     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
9962     }
9963   }
9964 
9965   DAG.RemoveDeadNode(Node);
9966   return nullptr;
9967 }
9968 
9969 static bool isFrameIndexOp(SDValue Op) {
9970   if (Op.getOpcode() == ISD::AssertZext)
9971     Op = Op.getOperand(0);
9972 
9973   return isa<FrameIndexSDNode>(Op);
9974 }
9975 
9976 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
9977 /// with frame index operands.
9978 /// LLVM assumes that inputs are to these instructions are registers.
9979 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
9980                                                         SelectionDAG &DAG) const {
9981   if (Node->getOpcode() == ISD::CopyToReg) {
9982     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
9983     SDValue SrcVal = Node->getOperand(2);
9984 
9985     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
9986     // to try understanding copies to physical registers.
9987     if (SrcVal.getValueType() == MVT::i1 &&
9988         TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
9989       SDLoc SL(Node);
9990       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
9991       SDValue VReg = DAG.getRegister(
9992         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
9993 
9994       SDNode *Glued = Node->getGluedNode();
9995       SDValue ToVReg
9996         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
9997                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
9998       SDValue ToResultReg
9999         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10000                            VReg, ToVReg.getValue(1));
10001       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10002       DAG.RemoveDeadNode(Node);
10003       return ToResultReg.getNode();
10004     }
10005   }
10006 
10007   SmallVector<SDValue, 8> Ops;
10008   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10009     if (!isFrameIndexOp(Node->getOperand(i))) {
10010       Ops.push_back(Node->getOperand(i));
10011       continue;
10012     }
10013 
10014     SDLoc DL(Node);
10015     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10016                                      Node->getOperand(i).getValueType(),
10017                                      Node->getOperand(i)), 0));
10018   }
10019 
10020   return DAG.UpdateNodeOperands(Node, Ops);
10021 }
10022 
10023 /// Fold the instructions after selecting them.
10024 /// Returns null if users were already updated.
10025 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10026                                           SelectionDAG &DAG) const {
10027   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10028   unsigned Opcode = Node->getMachineOpcode();
10029 
10030   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10031       !TII->isGather4(Opcode)) {
10032     return adjustWritemask(Node, DAG);
10033   }
10034 
10035   if (Opcode == AMDGPU::INSERT_SUBREG ||
10036       Opcode == AMDGPU::REG_SEQUENCE) {
10037     legalizeTargetIndependentNode(Node, DAG);
10038     return Node;
10039   }
10040 
10041   switch (Opcode) {
10042   case AMDGPU::V_DIV_SCALE_F32:
10043   case AMDGPU::V_DIV_SCALE_F64: {
10044     // Satisfy the operand register constraint when one of the inputs is
10045     // undefined. Ordinarily each undef value will have its own implicit_def of
10046     // a vreg, so force these to use a single register.
10047     SDValue Src0 = Node->getOperand(0);
10048     SDValue Src1 = Node->getOperand(1);
10049     SDValue Src2 = Node->getOperand(2);
10050 
10051     if ((Src0.isMachineOpcode() &&
10052          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10053         (Src0 == Src1 || Src0 == Src2))
10054       break;
10055 
10056     MVT VT = Src0.getValueType().getSimpleVT();
10057     const TargetRegisterClass *RC =
10058         getRegClassFor(VT, Src0.getNode()->isDivergent());
10059 
10060     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10061     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10062 
10063     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10064                                       UndefReg, Src0, SDValue());
10065 
10066     // src0 must be the same register as src1 or src2, even if the value is
10067     // undefined, so make sure we don't violate this constraint.
10068     if (Src0.isMachineOpcode() &&
10069         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10070       if (Src1.isMachineOpcode() &&
10071           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10072         Src0 = Src1;
10073       else if (Src2.isMachineOpcode() &&
10074                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10075         Src0 = Src2;
10076       else {
10077         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10078         Src0 = UndefReg;
10079         Src1 = UndefReg;
10080       }
10081     } else
10082       break;
10083 
10084     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10085     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10086       Ops.push_back(Node->getOperand(I));
10087 
10088     Ops.push_back(ImpDef.getValue(1));
10089     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10090   }
10091   case AMDGPU::V_PERMLANE16_B32:
10092   case AMDGPU::V_PERMLANEX16_B32: {
10093     ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0));
10094     ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2));
10095     if (!FI->getZExtValue() && !BC->getZExtValue())
10096       break;
10097     SDValue VDstIn = Node->getOperand(6);
10098     if (VDstIn.isMachineOpcode()
10099         && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF)
10100       break;
10101     MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
10102                                                SDLoc(Node), MVT::i32);
10103     SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1),
10104                                     SDValue(BC, 0), Node->getOperand(3),
10105                                     Node->getOperand(4), Node->getOperand(5),
10106                                     SDValue(ImpDef, 0), Node->getOperand(7) };
10107     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10108   }
10109   default:
10110     break;
10111   }
10112 
10113   return Node;
10114 }
10115 
10116 /// Assign the register class depending on the number of
10117 /// bits set in the writemask
10118 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10119                                                      SDNode *Node) const {
10120   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10121 
10122   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10123 
10124   if (TII->isVOP3(MI.getOpcode())) {
10125     // Make sure constant bus requirements are respected.
10126     TII->legalizeOperandsVOP3(MRI, MI);
10127     return;
10128   }
10129 
10130   // Replace unused atomics with the no return version.
10131   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10132   if (NoRetAtomicOp != -1) {
10133     if (!Node->hasAnyUseOfValue(0)) {
10134       MI.setDesc(TII->get(NoRetAtomicOp));
10135       MI.RemoveOperand(0);
10136       return;
10137     }
10138 
10139     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10140     // instruction, because the return type of these instructions is a vec2 of
10141     // the memory type, so it can be tied to the input operand.
10142     // This means these instructions always have a use, so we need to add a
10143     // special case to check if the atomic has only one extract_subreg use,
10144     // which itself has no uses.
10145     if ((Node->hasNUsesOfValue(1, 0) &&
10146          Node->use_begin()->isMachineOpcode() &&
10147          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10148          !Node->use_begin()->hasAnyUseOfValue(0))) {
10149       unsigned Def = MI.getOperand(0).getReg();
10150 
10151       // Change this into a noret atomic.
10152       MI.setDesc(TII->get(NoRetAtomicOp));
10153       MI.RemoveOperand(0);
10154 
10155       // If we only remove the def operand from the atomic instruction, the
10156       // extract_subreg will be left with a use of a vreg without a def.
10157       // So we need to insert an implicit_def to avoid machine verifier
10158       // errors.
10159       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10160               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10161     }
10162     return;
10163   }
10164 }
10165 
10166 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10167                               uint64_t Val) {
10168   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10169   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10170 }
10171 
10172 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10173                                                 const SDLoc &DL,
10174                                                 SDValue Ptr) const {
10175   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10176 
10177   // Build the half of the subregister with the constants before building the
10178   // full 128-bit register. If we are building multiple resource descriptors,
10179   // this will allow CSEing of the 2-component register.
10180   const SDValue Ops0[] = {
10181     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10182     buildSMovImm32(DAG, DL, 0),
10183     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10184     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10185     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10186   };
10187 
10188   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10189                                                 MVT::v2i32, Ops0), 0);
10190 
10191   // Combine the constants and the pointer.
10192   const SDValue Ops1[] = {
10193     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
10194     Ptr,
10195     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10196     SubRegHi,
10197     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10198   };
10199 
10200   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10201 }
10202 
10203 /// Return a resource descriptor with the 'Add TID' bit enabled
10204 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10205 ///        of the resource descriptor) to create an offset, which is added to
10206 ///        the resource pointer.
10207 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10208                                            SDValue Ptr, uint32_t RsrcDword1,
10209                                            uint64_t RsrcDword2And3) const {
10210   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10211   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10212   if (RsrcDword1) {
10213     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10214                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10215                     0);
10216   }
10217 
10218   SDValue DataLo = buildSMovImm32(DAG, DL,
10219                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10220   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10221 
10222   const SDValue Ops[] = {
10223     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
10224     PtrLo,
10225     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10226     PtrHi,
10227     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10228     DataLo,
10229     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10230     DataHi,
10231     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10232   };
10233 
10234   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10235 }
10236 
10237 //===----------------------------------------------------------------------===//
10238 //                         SI Inline Assembly Support
10239 //===----------------------------------------------------------------------===//
10240 
10241 std::pair<unsigned, const TargetRegisterClass *>
10242 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10243                                                StringRef Constraint,
10244                                                MVT VT) const {
10245   const TargetRegisterClass *RC = nullptr;
10246   if (Constraint.size() == 1) {
10247     switch (Constraint[0]) {
10248     default:
10249       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10250     case 's':
10251     case 'r':
10252       switch (VT.getSizeInBits()) {
10253       default:
10254         return std::make_pair(0U, nullptr);
10255       case 32:
10256       case 16:
10257         RC = &AMDGPU::SReg_32_XM0RegClass;
10258         break;
10259       case 64:
10260         RC = &AMDGPU::SGPR_64RegClass;
10261         break;
10262       case 96:
10263         RC = &AMDGPU::SReg_96RegClass;
10264         break;
10265       case 128:
10266         RC = &AMDGPU::SReg_128RegClass;
10267         break;
10268       case 160:
10269         RC = &AMDGPU::SReg_160RegClass;
10270         break;
10271       case 256:
10272         RC = &AMDGPU::SReg_256RegClass;
10273         break;
10274       case 512:
10275         RC = &AMDGPU::SReg_512RegClass;
10276         break;
10277       }
10278       break;
10279     case 'v':
10280       switch (VT.getSizeInBits()) {
10281       default:
10282         return std::make_pair(0U, nullptr);
10283       case 32:
10284       case 16:
10285         RC = &AMDGPU::VGPR_32RegClass;
10286         break;
10287       case 64:
10288         RC = &AMDGPU::VReg_64RegClass;
10289         break;
10290       case 96:
10291         RC = &AMDGPU::VReg_96RegClass;
10292         break;
10293       case 128:
10294         RC = &AMDGPU::VReg_128RegClass;
10295         break;
10296       case 160:
10297         RC = &AMDGPU::VReg_160RegClass;
10298         break;
10299       case 256:
10300         RC = &AMDGPU::VReg_256RegClass;
10301         break;
10302       case 512:
10303         RC = &AMDGPU::VReg_512RegClass;
10304         break;
10305       }
10306       break;
10307     case 'a':
10308       switch (VT.getSizeInBits()) {
10309       default:
10310         return std::make_pair(0U, nullptr);
10311       case 32:
10312       case 16:
10313         RC = &AMDGPU::AGPR_32RegClass;
10314         break;
10315       case 64:
10316         RC = &AMDGPU::AReg_64RegClass;
10317         break;
10318       case 128:
10319         RC = &AMDGPU::AReg_128RegClass;
10320         break;
10321       case 512:
10322         RC = &AMDGPU::AReg_512RegClass;
10323         break;
10324       case 1024:
10325         RC = &AMDGPU::AReg_1024RegClass;
10326         // v32 types are not legal but we support them here.
10327         return std::make_pair(0U, RC);
10328       }
10329       break;
10330     }
10331     // We actually support i128, i16 and f16 as inline parameters
10332     // even if they are not reported as legal
10333     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10334                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10335       return std::make_pair(0U, RC);
10336   }
10337 
10338   if (Constraint.size() > 1) {
10339     if (Constraint[1] == 'v') {
10340       RC = &AMDGPU::VGPR_32RegClass;
10341     } else if (Constraint[1] == 's') {
10342       RC = &AMDGPU::SGPR_32RegClass;
10343     } else if (Constraint[1] == 'a') {
10344       RC = &AMDGPU::AGPR_32RegClass;
10345     }
10346 
10347     if (RC) {
10348       uint32_t Idx;
10349       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10350       if (!Failed && Idx < RC->getNumRegs())
10351         return std::make_pair(RC->getRegister(Idx), RC);
10352     }
10353   }
10354   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10355 }
10356 
10357 SITargetLowering::ConstraintType
10358 SITargetLowering::getConstraintType(StringRef Constraint) const {
10359   if (Constraint.size() == 1) {
10360     switch (Constraint[0]) {
10361     default: break;
10362     case 's':
10363     case 'v':
10364     case 'a':
10365       return C_RegisterClass;
10366     }
10367   }
10368   return TargetLowering::getConstraintType(Constraint);
10369 }
10370 
10371 // Figure out which registers should be reserved for stack access. Only after
10372 // the function is legalized do we know all of the non-spill stack objects or if
10373 // calls are present.
10374 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10375   MachineRegisterInfo &MRI = MF.getRegInfo();
10376   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10377   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10378   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10379 
10380   if (Info->isEntryFunction()) {
10381     // Callable functions have fixed registers used for stack access.
10382     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10383   }
10384 
10385   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10386                              Info->getStackPtrOffsetReg()));
10387   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10388     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10389 
10390   // We need to worry about replacing the default register with itself in case
10391   // of MIR testcases missing the MFI.
10392   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10393     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10394 
10395   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10396     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10397 
10398   if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) {
10399     MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
10400                        Info->getScratchWaveOffsetReg());
10401   }
10402 
10403   Info->limitOccupancy(MF);
10404 
10405   if (ST.isWave32() && !MF.empty()) {
10406     // Add VCC_HI def because many instructions marked as imp-use VCC where
10407     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10408     // having a use of undef.
10409 
10410     const SIInstrInfo *TII = ST.getInstrInfo();
10411     DebugLoc DL;
10412 
10413     MachineBasicBlock &MBB = MF.front();
10414     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10415     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10416 
10417     for (auto &MBB : MF) {
10418       for (auto &MI : MBB) {
10419         TII->fixImplicitOperands(MI);
10420       }
10421     }
10422   }
10423 
10424   TargetLoweringBase::finalizeLowering(MF);
10425 }
10426 
10427 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10428                                                      KnownBits &Known,
10429                                                      const APInt &DemandedElts,
10430                                                      const SelectionDAG &DAG,
10431                                                      unsigned Depth) const {
10432   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10433                                                 DAG, Depth);
10434 
10435   // Set the high bits to zero based on the maximum allowed scratch size per
10436   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10437   // calculation won't overflow, so assume the sign bit is never set.
10438   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10439 }
10440 
10441 unsigned SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10442   const unsigned PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10443   const unsigned CacheLineAlign = 6; // log2(64)
10444 
10445   // Pre-GFX10 target did not benefit from loop alignment
10446   if (!ML || DisableLoopAlignment ||
10447       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10448       getSubtarget()->hasInstFwdPrefetchBug())
10449     return PrefAlign;
10450 
10451   // On GFX10 I$ is 4 x 64 bytes cache lines.
10452   // By default prefetcher keeps one cache line behind and reads two ahead.
10453   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10454   // behind and one ahead.
10455   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10456   // If loop fits 64 bytes it always spans no more than two cache lines and
10457   // does not need an alignment.
10458   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10459   // Else if loop is less or equal 192 bytes we need two lines behind.
10460 
10461   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10462   const MachineBasicBlock *Header = ML->getHeader();
10463   if (Header->getAlignment() != PrefAlign)
10464     return Header->getAlignment(); // Already processed.
10465 
10466   unsigned LoopSize = 0;
10467   for (const MachineBasicBlock *MBB : ML->blocks()) {
10468     // If inner loop block is aligned assume in average half of the alignment
10469     // size to be added as nops.
10470     if (MBB != Header)
10471       LoopSize += (1 << MBB->getAlignment()) / 2;
10472 
10473     for (const MachineInstr &MI : *MBB) {
10474       LoopSize += TII->getInstSizeInBytes(MI);
10475       if (LoopSize > 192)
10476         return PrefAlign;
10477     }
10478   }
10479 
10480   if (LoopSize <= 64)
10481     return PrefAlign;
10482 
10483   if (LoopSize <= 128)
10484     return CacheLineAlign;
10485 
10486   // If any of parent loops is surrounded by prefetch instructions do not
10487   // insert new for inner loop, which would reset parent's settings.
10488   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10489     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10490       auto I = Exit->getFirstNonDebugInstr();
10491       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10492         return CacheLineAlign;
10493     }
10494   }
10495 
10496   MachineBasicBlock *Pre = ML->getLoopPreheader();
10497   MachineBasicBlock *Exit = ML->getExitBlock();
10498 
10499   if (Pre && Exit) {
10500     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10501             TII->get(AMDGPU::S_INST_PREFETCH))
10502       .addImm(1); // prefetch 2 lines behind PC
10503 
10504     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10505             TII->get(AMDGPU::S_INST_PREFETCH))
10506       .addImm(2); // prefetch 1 line behind PC
10507   }
10508 
10509   return CacheLineAlign;
10510 }
10511 
10512 LLVM_ATTRIBUTE_UNUSED
10513 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10514   assert(N->getOpcode() == ISD::CopyFromReg);
10515   do {
10516     // Follow the chain until we find an INLINEASM node.
10517     N = N->getOperand(0).getNode();
10518     if (N->getOpcode() == ISD::INLINEASM ||
10519         N->getOpcode() == ISD::INLINEASM_BR)
10520       return true;
10521   } while (N->getOpcode() == ISD::CopyFromReg);
10522   return false;
10523 }
10524 
10525 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10526   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10527 {
10528   switch (N->getOpcode()) {
10529     case ISD::CopyFromReg:
10530     {
10531       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10532       const MachineFunction * MF = FLI->MF;
10533       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10534       const MachineRegisterInfo &MRI = MF->getRegInfo();
10535       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10536       unsigned Reg = R->getReg();
10537       if (TRI.isPhysicalRegister(Reg))
10538         return !TRI.isSGPRReg(MRI, Reg);
10539 
10540       if (MRI.isLiveIn(Reg)) {
10541         // workitem.id.x workitem.id.y workitem.id.z
10542         // Any VGPR formal argument is also considered divergent
10543         if (!TRI.isSGPRReg(MRI, Reg))
10544           return true;
10545         // Formal arguments of non-entry functions
10546         // are conservatively considered divergent
10547         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10548           return true;
10549         return false;
10550       }
10551       const Value *V = FLI->getValueFromVirtualReg(Reg);
10552       if (V)
10553         return KDA->isDivergent(V);
10554       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10555       return !TRI.isSGPRReg(MRI, Reg);
10556     }
10557     break;
10558     case ISD::LOAD: {
10559       const LoadSDNode *L = cast<LoadSDNode>(N);
10560       unsigned AS = L->getAddressSpace();
10561       // A flat load may access private memory.
10562       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10563     } break;
10564     case ISD::CALLSEQ_END:
10565     return true;
10566     break;
10567     case ISD::INTRINSIC_WO_CHAIN:
10568     {
10569 
10570     }
10571       return AMDGPU::isIntrinsicSourceOfDivergence(
10572       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10573     case ISD::INTRINSIC_W_CHAIN:
10574       return AMDGPU::isIntrinsicSourceOfDivergence(
10575       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10576     // In some cases intrinsics that are a source of divergence have been
10577     // lowered to AMDGPUISD so we also need to check those too.
10578     case AMDGPUISD::INTERP_MOV:
10579     case AMDGPUISD::INTERP_P1:
10580     case AMDGPUISD::INTERP_P2:
10581       return true;
10582   }
10583   return false;
10584 }
10585 
10586 bool SITargetLowering::denormalsEnabledForType(EVT VT) const {
10587   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10588   case MVT::f32:
10589     return Subtarget->hasFP32Denormals();
10590   case MVT::f64:
10591     return Subtarget->hasFP64Denormals();
10592   case MVT::f16:
10593     return Subtarget->hasFP16Denormals();
10594   default:
10595     return false;
10596   }
10597 }
10598 
10599 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
10600                                                     const SelectionDAG &DAG,
10601                                                     bool SNaN,
10602                                                     unsigned Depth) const {
10603   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
10604     const MachineFunction &MF = DAG.getMachineFunction();
10605     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10606 
10607     if (Info->getMode().DX10Clamp)
10608       return true; // Clamped to 0.
10609     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10610   }
10611 
10612   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
10613                                                             SNaN, Depth);
10614 }
10615 
10616 TargetLowering::AtomicExpansionKind
10617 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
10618   switch (RMW->getOperation()) {
10619   case AtomicRMWInst::FAdd: {
10620     Type *Ty = RMW->getType();
10621 
10622     // We don't have a way to support 16-bit atomics now, so just leave them
10623     // as-is.
10624     if (Ty->isHalfTy())
10625       return AtomicExpansionKind::None;
10626 
10627     if (!Ty->isFloatTy())
10628       return AtomicExpansionKind::CmpXChg;
10629 
10630     // TODO: Do have these for flat. Older targets also had them for buffers.
10631     unsigned AS = RMW->getPointerAddressSpace();
10632     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10633       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
10634   }
10635   default:
10636     break;
10637   }
10638 
10639   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
10640 }
10641