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 "MCTargetDesc/AMDGPUMCTargetDesc.h"
24 #include "SIDefines.h"
25 #include "SIInstrInfo.h"
26 #include "SIMachineFunctionInfo.h"
27 #include "SIRegisterInfo.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/Analysis/LegacyDivergenceAnalysis.h"
39 #include "llvm/CodeGen/Analysis.h"
40 #include "llvm/CodeGen/CallingConvLower.h"
41 #include "llvm/CodeGen/DAGCombine.h"
42 #include "llvm/CodeGen/ISDOpcodes.h"
43 #include "llvm/CodeGen/MachineBasicBlock.h"
44 #include "llvm/CodeGen/MachineFrameInfo.h"
45 #include "llvm/CodeGen/MachineFunction.h"
46 #include "llvm/CodeGen/MachineInstr.h"
47 #include "llvm/CodeGen/MachineInstrBuilder.h"
48 #include "llvm/CodeGen/MachineLoopInfo.h"
49 #include "llvm/CodeGen/MachineMemOperand.h"
50 #include "llvm/CodeGen/MachineModuleInfo.h"
51 #include "llvm/CodeGen/MachineOperand.h"
52 #include "llvm/CodeGen/MachineRegisterInfo.h"
53 #include "llvm/CodeGen/SelectionDAG.h"
54 #include "llvm/CodeGen/SelectionDAGNodes.h"
55 #include "llvm/CodeGen/TargetCallingConv.h"
56 #include "llvm/CodeGen/TargetRegisterInfo.h"
57 #include "llvm/CodeGen/ValueTypes.h"
58 #include "llvm/IR/Constants.h"
59 #include "llvm/IR/DataLayout.h"
60 #include "llvm/IR/DebugLoc.h"
61 #include "llvm/IR/DerivedTypes.h"
62 #include "llvm/IR/DiagnosticInfo.h"
63 #include "llvm/IR/Function.h"
64 #include "llvm/IR/GlobalValue.h"
65 #include "llvm/IR/InstrTypes.h"
66 #include "llvm/IR/Instruction.h"
67 #include "llvm/IR/Instructions.h"
68 #include "llvm/IR/IntrinsicInst.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/Support/Casting.h"
71 #include "llvm/Support/CodeGen.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/ErrorHandling.h"
75 #include "llvm/Support/KnownBits.h"
76 #include "llvm/Support/MachineValueType.h"
77 #include "llvm/Support/MathExtras.h"
78 #include "llvm/Target/TargetOptions.h"
79 #include <cassert>
80 #include <cmath>
81 #include <cstdint>
82 #include <iterator>
83 #include <tuple>
84 #include <utility>
85 #include <vector>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "si-lower"
90 
91 STATISTIC(NumTailCalls, "Number of tail calls");
92 
93 static cl::opt<bool> EnableVGPRIndexMode(
94   "amdgpu-vgpr-index-mode",
95   cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
96   cl::init(false));
97 
98 static cl::opt<bool> DisableLoopAlignment(
99   "amdgpu-disable-loop-alignment",
100   cl::desc("Do not align and prefetch loops"),
101   cl::init(false));
102 
103 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
104   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
105   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
106     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
107       return AMDGPU::SGPR0 + Reg;
108     }
109   }
110   llvm_unreachable("Cannot allocate sgpr");
111 }
112 
113 SITargetLowering::SITargetLowering(const TargetMachine &TM,
114                                    const GCNSubtarget &STI)
115     : AMDGPUTargetLowering(TM, STI),
116       Subtarget(&STI) {
117   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
118   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
119 
120   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
121   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
122 
123   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
124   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
125   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
126 
127   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
128   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
129 
130   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
131   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
132 
133   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
134   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
135 
136   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
137   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
138 
139   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
140   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
141 
142   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
143   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
144 
145   if (Subtarget->has16BitInsts()) {
146     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
147     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
148 
149     // Unless there are also VOP3P operations, not operations are really legal.
150     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
151     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
152     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
153     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
154   }
155 
156   if (Subtarget->hasMAIInsts()) {
157     addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
158     addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
159   }
160 
161   computeRegisterProperties(Subtarget->getRegisterInfo());
162 
163   // We need to custom lower vector stores from local memory
164   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
165   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
166   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
167   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
168   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
169   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
170   setOperationAction(ISD::LOAD, MVT::i1, Custom);
171   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
172 
173   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
174   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
175   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
176   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
177   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
178   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
179   setOperationAction(ISD::STORE, MVT::i1, Custom);
180   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
181 
182   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
183   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
184   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
185   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
186   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
187   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
188   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
189   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
190   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
191   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
192   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
193 
194   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
195   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
196 
197   setOperationAction(ISD::SELECT, MVT::i1, Promote);
198   setOperationAction(ISD::SELECT, MVT::i64, Custom);
199   setOperationAction(ISD::SELECT, MVT::f64, Promote);
200   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
201 
202   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
203   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
204   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
205   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
206   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
207 
208   setOperationAction(ISD::SETCC, MVT::i1, Promote);
209   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
210   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
211   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
212 
213   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
214   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
215 
216   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
217   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
218   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
219   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
220   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
221   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
222   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
223   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
224 
225   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
226   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
227   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
228   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
229   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
230   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
231 
232   setOperationAction(ISD::UADDO, MVT::i32, Legal);
233   setOperationAction(ISD::USUBO, MVT::i32, Legal);
234 
235   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
236   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
237 
238   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
239   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
240   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
241 
242 #if 0
243   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
244   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
245 #endif
246 
247   // We only support LOAD/STORE and vector manipulation ops for vectors
248   // with > 4 elements.
249   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
250                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
251                   MVT::v32i32, MVT::v32f32 }) {
252     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
253       switch (Op) {
254       case ISD::LOAD:
255       case ISD::STORE:
256       case ISD::BUILD_VECTOR:
257       case ISD::BITCAST:
258       case ISD::EXTRACT_VECTOR_ELT:
259       case ISD::INSERT_VECTOR_ELT:
260       case ISD::INSERT_SUBVECTOR:
261       case ISD::EXTRACT_SUBVECTOR:
262       case ISD::SCALAR_TO_VECTOR:
263         break;
264       case ISD::CONCAT_VECTORS:
265         setOperationAction(Op, VT, Custom);
266         break;
267       default:
268         setOperationAction(Op, VT, Expand);
269         break;
270       }
271     }
272   }
273 
274   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
275 
276   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
277   // is expanded to avoid having two separate loops in case the index is a VGPR.
278 
279   // Most operations are naturally 32-bit vector operations. We only support
280   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
281   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
282     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
283     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
284 
285     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
286     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
287 
288     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
289     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
290 
291     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
292     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
293   }
294 
295   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
296   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
297   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
298   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
299 
300   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
301   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
302 
303   // Avoid stack access for these.
304   // TODO: Generalize to more vector types.
305   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
306   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
307   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
308   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
309 
310   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
311   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
312   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
313   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
314   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
315 
316   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
317   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
318   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
319 
320   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
321   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
322   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
323   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
324 
325   // Deal with vec3 vector operations when widened to vec4.
326   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
327   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
328   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
329   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
330 
331   // Deal with vec5 vector operations when widened to vec8.
332   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
333   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
334   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
335   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
336 
337   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
338   // and output demarshalling
339   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
340   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
341 
342   // We can't return success/failure, only the old value,
343   // let LLVM add the comparison
344   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
345   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
346 
347   if (Subtarget->hasFlatAddressSpace()) {
348     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
349     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
350   }
351 
352   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
353   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
354 
355   // On SI this is s_memtime and s_memrealtime on VI.
356   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
357   setOperationAction(ISD::TRAP, MVT::Other, Custom);
358   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
359 
360   if (Subtarget->has16BitInsts()) {
361     setOperationAction(ISD::FLOG, MVT::f16, Custom);
362     setOperationAction(ISD::FEXP, MVT::f16, Custom);
363     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
364   }
365 
366   // v_mad_f32 does not support denormals according to some sources.
367   if (!Subtarget->hasFP32Denormals())
368     setOperationAction(ISD::FMAD, MVT::f32, Legal);
369 
370   if (!Subtarget->hasBFI()) {
371     // fcopysign can be done in a single instruction with BFI.
372     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
373     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
374   }
375 
376   if (!Subtarget->hasBCNT(32))
377     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
378 
379   if (!Subtarget->hasBCNT(64))
380     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
381 
382   if (Subtarget->hasFFBH())
383     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
384 
385   if (Subtarget->hasFFBL())
386     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
387 
388   // We only really have 32-bit BFE instructions (and 16-bit on VI).
389   //
390   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
391   // effort to match them now. We want this to be false for i64 cases when the
392   // extraction isn't restricted to the upper or lower half. Ideally we would
393   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
394   // span the midpoint are probably relatively rare, so don't worry about them
395   // for now.
396   if (Subtarget->hasBFE())
397     setHasExtractBitsInsn(true);
398 
399   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
400   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
401   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
402   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
403 
404 
405   // These are really only legal for ieee_mode functions. We should be avoiding
406   // them for functions that don't have ieee_mode enabled, so just say they are
407   // legal.
408   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
409   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
410   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
411   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
412 
413 
414   if (Subtarget->haveRoundOpsF64()) {
415     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
416     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
417     setOperationAction(ISD::FRINT, MVT::f64, Legal);
418   } else {
419     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
420     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
421     setOperationAction(ISD::FRINT, MVT::f64, Custom);
422     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
423   }
424 
425   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
426 
427   setOperationAction(ISD::FSIN, MVT::f32, Custom);
428   setOperationAction(ISD::FCOS, MVT::f32, Custom);
429   setOperationAction(ISD::FDIV, MVT::f32, Custom);
430   setOperationAction(ISD::FDIV, MVT::f64, Custom);
431 
432   if (Subtarget->has16BitInsts()) {
433     setOperationAction(ISD::Constant, MVT::i16, Legal);
434 
435     setOperationAction(ISD::SMIN, MVT::i16, Legal);
436     setOperationAction(ISD::SMAX, MVT::i16, Legal);
437 
438     setOperationAction(ISD::UMIN, MVT::i16, Legal);
439     setOperationAction(ISD::UMAX, MVT::i16, Legal);
440 
441     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
442     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
443 
444     setOperationAction(ISD::ROTR, MVT::i16, Promote);
445     setOperationAction(ISD::ROTL, MVT::i16, Promote);
446 
447     setOperationAction(ISD::SDIV, MVT::i16, Promote);
448     setOperationAction(ISD::UDIV, MVT::i16, Promote);
449     setOperationAction(ISD::SREM, MVT::i16, Promote);
450     setOperationAction(ISD::UREM, MVT::i16, Promote);
451 
452     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
453     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
454 
455     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
456     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
457     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
458     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
459     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
460 
461     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
462 
463     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
464 
465     setOperationAction(ISD::LOAD, MVT::i16, Custom);
466 
467     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
468 
469     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
470     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
471     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
472     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
473 
474     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
475     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
476     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
477     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
478 
479     // F16 - Constant Actions.
480     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
481 
482     // F16 - Load/Store Actions.
483     setOperationAction(ISD::LOAD, MVT::f16, Promote);
484     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
485     setOperationAction(ISD::STORE, MVT::f16, Promote);
486     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
487 
488     // F16 - VOP1 Actions.
489     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
490     setOperationAction(ISD::FCOS, MVT::f16, Promote);
491     setOperationAction(ISD::FSIN, MVT::f16, Promote);
492     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
493     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
494     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
495     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
496     setOperationAction(ISD::FROUND, MVT::f16, Custom);
497 
498     // F16 - VOP2 Actions.
499     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
500     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
501 
502     setOperationAction(ISD::FDIV, MVT::f16, Custom);
503 
504     // F16 - VOP3 Actions.
505     setOperationAction(ISD::FMA, MVT::f16, Legal);
506     if (!Subtarget->hasFP16Denormals() && STI.hasMadF16())
507       setOperationAction(ISD::FMAD, MVT::f16, Legal);
508 
509     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
510       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
511         switch (Op) {
512         case ISD::LOAD:
513         case ISD::STORE:
514         case ISD::BUILD_VECTOR:
515         case ISD::BITCAST:
516         case ISD::EXTRACT_VECTOR_ELT:
517         case ISD::INSERT_VECTOR_ELT:
518         case ISD::INSERT_SUBVECTOR:
519         case ISD::EXTRACT_SUBVECTOR:
520         case ISD::SCALAR_TO_VECTOR:
521           break;
522         case ISD::CONCAT_VECTORS:
523           setOperationAction(Op, VT, Custom);
524           break;
525         default:
526           setOperationAction(Op, VT, Expand);
527           break;
528         }
529       }
530     }
531 
532     // XXX - Do these do anything? Vector constants turn into build_vector.
533     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
534     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
535 
536     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
537     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
538 
539     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
540     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
541     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
542     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
543 
544     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
545     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
546     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
547     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
548 
549     setOperationAction(ISD::AND, MVT::v2i16, Promote);
550     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
551     setOperationAction(ISD::OR, MVT::v2i16, Promote);
552     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
553     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
554     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
555 
556     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
557     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
558     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
559     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
560 
561     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
562     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
563     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
564     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
565 
566     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
567     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
568     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
569     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
570 
571     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
572     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
573     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
574 
575     if (!Subtarget->hasVOP3PInsts()) {
576       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
577       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
578     }
579 
580     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
581     // This isn't really legal, but this avoids the legalizer unrolling it (and
582     // allows matching fneg (fabs x) patterns)
583     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
584 
585     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
586     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
587     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
588     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
589 
590     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
591     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
592 
593     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
594     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
595   }
596 
597   if (Subtarget->hasVOP3PInsts()) {
598     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
599     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
600     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
601     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
602     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
603     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
604     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
605     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
606     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
607     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
608 
609     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
610     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
611     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
612 
613     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
614     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
615 
616     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
617 
618     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
619     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
620 
621     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
622     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
623 
624     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
625     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
626     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
627     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
628     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
629     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
630 
631     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
632     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
633     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
634     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
635 
636     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
637     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
638     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
639 
640     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
641     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
642 
643     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
644     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
645     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
646 
647     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
648     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
649     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
650   }
651 
652   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
653   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
654 
655   if (Subtarget->has16BitInsts()) {
656     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
657     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
658     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
659     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
660   } else {
661     // Legalization hack.
662     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
663     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
664 
665     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
666     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
667   }
668 
669   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
670     setOperationAction(ISD::SELECT, VT, Custom);
671   }
672 
673   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
674   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
675   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
676   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
677   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
678   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
679   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
680 
681   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
682   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
683   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
684   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
685   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
686   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
687   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
688   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
689   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
690 
691   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
692   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
693   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
694   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
695   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
696   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
697   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
698   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
699 
700   setTargetDAGCombine(ISD::ADD);
701   setTargetDAGCombine(ISD::ADDCARRY);
702   setTargetDAGCombine(ISD::SUB);
703   setTargetDAGCombine(ISD::SUBCARRY);
704   setTargetDAGCombine(ISD::FADD);
705   setTargetDAGCombine(ISD::FSUB);
706   setTargetDAGCombine(ISD::FMINNUM);
707   setTargetDAGCombine(ISD::FMAXNUM);
708   setTargetDAGCombine(ISD::FMINNUM_IEEE);
709   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
710   setTargetDAGCombine(ISD::FMA);
711   setTargetDAGCombine(ISD::SMIN);
712   setTargetDAGCombine(ISD::SMAX);
713   setTargetDAGCombine(ISD::UMIN);
714   setTargetDAGCombine(ISD::UMAX);
715   setTargetDAGCombine(ISD::SETCC);
716   setTargetDAGCombine(ISD::AND);
717   setTargetDAGCombine(ISD::OR);
718   setTargetDAGCombine(ISD::XOR);
719   setTargetDAGCombine(ISD::SINT_TO_FP);
720   setTargetDAGCombine(ISD::UINT_TO_FP);
721   setTargetDAGCombine(ISD::FCANONICALIZE);
722   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
723   setTargetDAGCombine(ISD::ZERO_EXTEND);
724   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
725   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
726   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
727 
728   // All memory operations. Some folding on the pointer operand is done to help
729   // matching the constant offsets in the addressing modes.
730   setTargetDAGCombine(ISD::LOAD);
731   setTargetDAGCombine(ISD::STORE);
732   setTargetDAGCombine(ISD::ATOMIC_LOAD);
733   setTargetDAGCombine(ISD::ATOMIC_STORE);
734   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
735   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
736   setTargetDAGCombine(ISD::ATOMIC_SWAP);
737   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
738   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
739   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
740   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
741   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
742   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
743   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
744   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
745   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
746   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
747   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
748 
749   setSchedulingPreference(Sched::RegPressure);
750 }
751 
752 const GCNSubtarget *SITargetLowering::getSubtarget() const {
753   return Subtarget;
754 }
755 
756 //===----------------------------------------------------------------------===//
757 // TargetLowering queries
758 //===----------------------------------------------------------------------===//
759 
760 // v_mad_mix* support a conversion from f16 to f32.
761 //
762 // There is only one special case when denormals are enabled we don't currently,
763 // where this is OK to use.
764 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
765                                        EVT DestVT, EVT SrcVT) const {
766   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
767           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
768          DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
769          SrcVT.getScalarType() == MVT::f16;
770 }
771 
772 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
773   // SI has some legal vector types, but no legal vector operations. Say no
774   // shuffles are legal in order to prefer scalarizing some vector operations.
775   return false;
776 }
777 
778 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
779                                                     CallingConv::ID CC,
780                                                     EVT VT) const {
781   if (CC == CallingConv::AMDGPU_KERNEL)
782     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
783 
784   if (VT.isVector()) {
785     EVT ScalarVT = VT.getScalarType();
786     unsigned Size = ScalarVT.getSizeInBits();
787     if (Size == 32)
788       return ScalarVT.getSimpleVT();
789 
790     if (Size > 32)
791       return MVT::i32;
792 
793     if (Size == 16 && Subtarget->has16BitInsts())
794       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
795   } else if (VT.getSizeInBits() > 32)
796     return MVT::i32;
797 
798   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
799 }
800 
801 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
802                                                          CallingConv::ID CC,
803                                                          EVT VT) const {
804   if (CC == CallingConv::AMDGPU_KERNEL)
805     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
806 
807   if (VT.isVector()) {
808     unsigned NumElts = VT.getVectorNumElements();
809     EVT ScalarVT = VT.getScalarType();
810     unsigned Size = ScalarVT.getSizeInBits();
811 
812     if (Size == 32)
813       return NumElts;
814 
815     if (Size > 32)
816       return NumElts * ((Size + 31) / 32);
817 
818     if (Size == 16 && Subtarget->has16BitInsts())
819       return (NumElts + 1) / 2;
820   } else if (VT.getSizeInBits() > 32)
821     return (VT.getSizeInBits() + 31) / 32;
822 
823   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
824 }
825 
826 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
827   LLVMContext &Context, CallingConv::ID CC,
828   EVT VT, EVT &IntermediateVT,
829   unsigned &NumIntermediates, MVT &RegisterVT) const {
830   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
831     unsigned NumElts = VT.getVectorNumElements();
832     EVT ScalarVT = VT.getScalarType();
833     unsigned Size = ScalarVT.getSizeInBits();
834     if (Size == 32) {
835       RegisterVT = ScalarVT.getSimpleVT();
836       IntermediateVT = RegisterVT;
837       NumIntermediates = NumElts;
838       return NumIntermediates;
839     }
840 
841     if (Size > 32) {
842       RegisterVT = MVT::i32;
843       IntermediateVT = RegisterVT;
844       NumIntermediates = NumElts * ((Size + 31) / 32);
845       return NumIntermediates;
846     }
847 
848     // FIXME: We should fix the ABI to be the same on targets without 16-bit
849     // support, but unless we can properly handle 3-vectors, it will be still be
850     // inconsistent.
851     if (Size == 16 && Subtarget->has16BitInsts()) {
852       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
853       IntermediateVT = RegisterVT;
854       NumIntermediates = (NumElts + 1) / 2;
855       return NumIntermediates;
856     }
857   }
858 
859   return TargetLowering::getVectorTypeBreakdownForCallingConv(
860     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
861 }
862 
863 static MVT memVTFromAggregate(Type *Ty) {
864   // Only limited forms of aggregate type currently expected.
865   assert(Ty->isStructTy() && "Expected struct type");
866 
867 
868   Type *ElementType = nullptr;
869   unsigned NumElts;
870   if (Ty->getContainedType(0)->isVectorTy()) {
871     VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0));
872     ElementType = VecComponent->getElementType();
873     NumElts = VecComponent->getNumElements();
874   } else {
875     ElementType = Ty->getContainedType(0);
876     NumElts = 1;
877   }
878 
879   assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type");
880 
881   // Calculate the size of the memVT type from the aggregate
882   unsigned Pow2Elts = 0;
883   unsigned ElementSize;
884   switch (ElementType->getTypeID()) {
885     default:
886       llvm_unreachable("Unknown type!");
887     case Type::IntegerTyID:
888       ElementSize = cast<IntegerType>(ElementType)->getBitWidth();
889       break;
890     case Type::HalfTyID:
891       ElementSize = 16;
892       break;
893     case Type::FloatTyID:
894       ElementSize = 32;
895       break;
896   }
897   unsigned AdditionalElts = ElementSize == 16 ? 2 : 1;
898   Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts);
899 
900   return MVT::getVectorVT(MVT::getVT(ElementType, false),
901                           Pow2Elts);
902 }
903 
904 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
905                                           const CallInst &CI,
906                                           MachineFunction &MF,
907                                           unsigned IntrID) const {
908   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
909           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
910     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
911                                                   (Intrinsic::ID)IntrID);
912     if (Attr.hasFnAttribute(Attribute::ReadNone))
913       return false;
914 
915     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
916 
917     if (RsrcIntr->IsImage) {
918       Info.ptrVal = MFI->getImagePSV(
919         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
920         CI.getArgOperand(RsrcIntr->RsrcArg));
921       Info.align.reset();
922     } else {
923       Info.ptrVal = MFI->getBufferPSV(
924         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
925         CI.getArgOperand(RsrcIntr->RsrcArg));
926     }
927 
928     Info.flags = MachineMemOperand::MODereferenceable;
929     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
930       Info.opc = ISD::INTRINSIC_W_CHAIN;
931       Info.memVT = MVT::getVT(CI.getType(), true);
932       if (Info.memVT == MVT::Other) {
933         // Some intrinsics return an aggregate type - special case to work out
934         // the correct memVT
935         Info.memVT = memVTFromAggregate(CI.getType());
936       }
937       Info.flags |= MachineMemOperand::MOLoad;
938     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
939       Info.opc = ISD::INTRINSIC_VOID;
940       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
941       Info.flags |= MachineMemOperand::MOStore;
942     } else {
943       // Atomic
944       Info.opc = ISD::INTRINSIC_W_CHAIN;
945       Info.memVT = MVT::getVT(CI.getType());
946       Info.flags = MachineMemOperand::MOLoad |
947                    MachineMemOperand::MOStore |
948                    MachineMemOperand::MODereferenceable;
949 
950       // XXX - Should this be volatile without known ordering?
951       Info.flags |= MachineMemOperand::MOVolatile;
952     }
953     return true;
954   }
955 
956   switch (IntrID) {
957   case Intrinsic::amdgcn_atomic_inc:
958   case Intrinsic::amdgcn_atomic_dec:
959   case Intrinsic::amdgcn_ds_ordered_add:
960   case Intrinsic::amdgcn_ds_ordered_swap:
961   case Intrinsic::amdgcn_ds_fadd:
962   case Intrinsic::amdgcn_ds_fmin:
963   case Intrinsic::amdgcn_ds_fmax: {
964     Info.opc = ISD::INTRINSIC_W_CHAIN;
965     Info.memVT = MVT::getVT(CI.getType());
966     Info.ptrVal = CI.getOperand(0);
967     Info.align.reset();
968     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
969 
970     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
971     if (!Vol->isZero())
972       Info.flags |= MachineMemOperand::MOVolatile;
973 
974     return true;
975   }
976   case Intrinsic::amdgcn_buffer_atomic_fadd: {
977     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
978 
979     Info.opc = ISD::INTRINSIC_VOID;
980     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
981     Info.ptrVal = MFI->getBufferPSV(
982       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
983       CI.getArgOperand(1));
984     Info.align.reset();
985     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
986 
987     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
988     if (!Vol || !Vol->isZero())
989       Info.flags |= MachineMemOperand::MOVolatile;
990 
991     return true;
992   }
993   case Intrinsic::amdgcn_global_atomic_fadd: {
994     Info.opc = ISD::INTRINSIC_VOID;
995     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
996                             ->getPointerElementType());
997     Info.ptrVal = CI.getOperand(0);
998     Info.align.reset();
999     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1000 
1001     return true;
1002   }
1003   case Intrinsic::amdgcn_ds_append:
1004   case Intrinsic::amdgcn_ds_consume: {
1005     Info.opc = ISD::INTRINSIC_W_CHAIN;
1006     Info.memVT = MVT::getVT(CI.getType());
1007     Info.ptrVal = CI.getOperand(0);
1008     Info.align.reset();
1009     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1010 
1011     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1012     if (!Vol->isZero())
1013       Info.flags |= MachineMemOperand::MOVolatile;
1014 
1015     return true;
1016   }
1017   case Intrinsic::amdgcn_ds_gws_init:
1018   case Intrinsic::amdgcn_ds_gws_barrier:
1019   case Intrinsic::amdgcn_ds_gws_sema_v:
1020   case Intrinsic::amdgcn_ds_gws_sema_br:
1021   case Intrinsic::amdgcn_ds_gws_sema_p:
1022   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1023     Info.opc = ISD::INTRINSIC_VOID;
1024 
1025     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1026     Info.ptrVal =
1027         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1028 
1029     // This is an abstract access, but we need to specify a type and size.
1030     Info.memVT = MVT::i32;
1031     Info.size = 4;
1032     Info.align = Align(4);
1033 
1034     Info.flags = MachineMemOperand::MOStore;
1035     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1036       Info.flags = MachineMemOperand::MOLoad;
1037     return true;
1038   }
1039   default:
1040     return false;
1041   }
1042 }
1043 
1044 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1045                                             SmallVectorImpl<Value*> &Ops,
1046                                             Type *&AccessTy) const {
1047   switch (II->getIntrinsicID()) {
1048   case Intrinsic::amdgcn_atomic_inc:
1049   case Intrinsic::amdgcn_atomic_dec:
1050   case Intrinsic::amdgcn_ds_ordered_add:
1051   case Intrinsic::amdgcn_ds_ordered_swap:
1052   case Intrinsic::amdgcn_ds_fadd:
1053   case Intrinsic::amdgcn_ds_fmin:
1054   case Intrinsic::amdgcn_ds_fmax: {
1055     Value *Ptr = II->getArgOperand(0);
1056     AccessTy = II->getType();
1057     Ops.push_back(Ptr);
1058     return true;
1059   }
1060   default:
1061     return false;
1062   }
1063 }
1064 
1065 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1066   if (!Subtarget->hasFlatInstOffsets()) {
1067     // Flat instructions do not have offsets, and only have the register
1068     // address.
1069     return AM.BaseOffs == 0 && AM.Scale == 0;
1070   }
1071 
1072   // GFX9 added a 13-bit signed offset. When using regular flat instructions,
1073   // the sign bit is ignored and is treated as a 12-bit unsigned offset.
1074 
1075   // GFX10 shrinked signed offset to 12 bits. When using regular flat
1076   // instructions, the sign bit is also ignored and is treated as 11-bit
1077   // unsigned offset.
1078 
1079   if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
1080     return isUInt<11>(AM.BaseOffs) && AM.Scale == 0;
1081 
1082   // Just r + i
1083   return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
1084 }
1085 
1086 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1087   if (Subtarget->hasFlatGlobalInsts())
1088     return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
1089 
1090   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1091       // Assume the we will use FLAT for all global memory accesses
1092       // on VI.
1093       // FIXME: This assumption is currently wrong.  On VI we still use
1094       // MUBUF instructions for the r + i addressing mode.  As currently
1095       // implemented, the MUBUF instructions only work on buffer < 4GB.
1096       // It may be possible to support > 4GB buffers with MUBUF instructions,
1097       // by setting the stride value in the resource descriptor which would
1098       // increase the size limit to (stride * 4GB).  However, this is risky,
1099       // because it has never been validated.
1100     return isLegalFlatAddressingMode(AM);
1101   }
1102 
1103   return isLegalMUBUFAddressingMode(AM);
1104 }
1105 
1106 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1107   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1108   // additionally can do r + r + i with addr64. 32-bit has more addressing
1109   // mode options. Depending on the resource constant, it can also do
1110   // (i64 r0) + (i32 r1) * (i14 i).
1111   //
1112   // Private arrays end up using a scratch buffer most of the time, so also
1113   // assume those use MUBUF instructions. Scratch loads / stores are currently
1114   // implemented as mubuf instructions with offen bit set, so slightly
1115   // different than the normal addr64.
1116   if (!isUInt<12>(AM.BaseOffs))
1117     return false;
1118 
1119   // FIXME: Since we can split immediate into soffset and immediate offset,
1120   // would it make sense to allow any immediate?
1121 
1122   switch (AM.Scale) {
1123   case 0: // r + i or just i, depending on HasBaseReg.
1124     return true;
1125   case 1:
1126     return true; // We have r + r or r + i.
1127   case 2:
1128     if (AM.HasBaseReg) {
1129       // Reject 2 * r + r.
1130       return false;
1131     }
1132 
1133     // Allow 2 * r as r + r
1134     // Or  2 * r + i is allowed as r + r + i.
1135     return true;
1136   default: // Don't allow n * r
1137     return false;
1138   }
1139 }
1140 
1141 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1142                                              const AddrMode &AM, Type *Ty,
1143                                              unsigned AS, Instruction *I) const {
1144   // No global is ever allowed as a base.
1145   if (AM.BaseGV)
1146     return false;
1147 
1148   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1149     return isLegalGlobalAddressingMode(AM);
1150 
1151   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1152       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1153       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1154     // If the offset isn't a multiple of 4, it probably isn't going to be
1155     // correctly aligned.
1156     // FIXME: Can we get the real alignment here?
1157     if (AM.BaseOffs % 4 != 0)
1158       return isLegalMUBUFAddressingMode(AM);
1159 
1160     // There are no SMRD extloads, so if we have to do a small type access we
1161     // will use a MUBUF load.
1162     // FIXME?: We also need to do this if unaligned, but we don't know the
1163     // alignment here.
1164     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1165       return isLegalGlobalAddressingMode(AM);
1166 
1167     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1168       // SMRD instructions have an 8-bit, dword offset on SI.
1169       if (!isUInt<8>(AM.BaseOffs / 4))
1170         return false;
1171     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1172       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1173       // in 8-bits, it can use a smaller encoding.
1174       if (!isUInt<32>(AM.BaseOffs / 4))
1175         return false;
1176     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1177       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1178       if (!isUInt<20>(AM.BaseOffs))
1179         return false;
1180     } else
1181       llvm_unreachable("unhandled generation");
1182 
1183     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1184       return true;
1185 
1186     if (AM.Scale == 1 && AM.HasBaseReg)
1187       return true;
1188 
1189     return false;
1190 
1191   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1192     return isLegalMUBUFAddressingMode(AM);
1193   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1194              AS == AMDGPUAS::REGION_ADDRESS) {
1195     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1196     // field.
1197     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1198     // an 8-bit dword offset but we don't know the alignment here.
1199     if (!isUInt<16>(AM.BaseOffs))
1200       return false;
1201 
1202     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1203       return true;
1204 
1205     if (AM.Scale == 1 && AM.HasBaseReg)
1206       return true;
1207 
1208     return false;
1209   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1210              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1211     // For an unknown address space, this usually means that this is for some
1212     // reason being used for pure arithmetic, and not based on some addressing
1213     // computation. We don't have instructions that compute pointers with any
1214     // addressing modes, so treat them as having no offset like flat
1215     // instructions.
1216     return isLegalFlatAddressingMode(AM);
1217   } else {
1218     llvm_unreachable("unhandled address space");
1219   }
1220 }
1221 
1222 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1223                                         const SelectionDAG &DAG) const {
1224   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1225     return (MemVT.getSizeInBits() <= 4 * 32);
1226   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1227     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1228     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1229   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1230     return (MemVT.getSizeInBits() <= 2 * 32);
1231   }
1232   return true;
1233 }
1234 
1235 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1236     unsigned Size, unsigned AddrSpace, unsigned Align,
1237     MachineMemOperand::Flags Flags, bool *IsFast) const {
1238   if (IsFast)
1239     *IsFast = false;
1240 
1241   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1242       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1243     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1244     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1245     // with adjacent offsets.
1246     bool AlignedBy4 = (Align % 4 == 0);
1247     if (IsFast)
1248       *IsFast = AlignedBy4;
1249 
1250     return AlignedBy4;
1251   }
1252 
1253   // FIXME: We have to be conservative here and assume that flat operations
1254   // will access scratch.  If we had access to the IR function, then we
1255   // could determine if any private memory was used in the function.
1256   if (!Subtarget->hasUnalignedScratchAccess() &&
1257       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1258        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1259     bool AlignedBy4 = Align >= 4;
1260     if (IsFast)
1261       *IsFast = AlignedBy4;
1262 
1263     return AlignedBy4;
1264   }
1265 
1266   if (Subtarget->hasUnalignedBufferAccess()) {
1267     // If we have an uniform constant load, it still requires using a slow
1268     // buffer instruction if unaligned.
1269     if (IsFast) {
1270       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1271                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1272         (Align % 4 == 0) : true;
1273     }
1274 
1275     return true;
1276   }
1277 
1278   // Smaller than dword value must be aligned.
1279   if (Size < 32)
1280     return false;
1281 
1282   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1283   // byte-address are ignored, thus forcing Dword alignment.
1284   // This applies to private, global, and constant memory.
1285   if (IsFast)
1286     *IsFast = true;
1287 
1288   return Size >= 32 && Align >= 4;
1289 }
1290 
1291 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1292     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1293     bool *IsFast) const {
1294   if (IsFast)
1295     *IsFast = false;
1296 
1297   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1298   // which isn't a simple VT.
1299   // Until MVT is extended to handle this, simply check for the size and
1300   // rely on the condition below: allow accesses if the size is a multiple of 4.
1301   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1302                            VT.getStoreSize() > 16)) {
1303     return false;
1304   }
1305 
1306   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1307                                             Align, Flags, IsFast);
1308 }
1309 
1310 EVT SITargetLowering::getOptimalMemOpType(
1311     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
1312     bool ZeroMemset, bool MemcpyStrSrc,
1313     const AttributeList &FuncAttributes) const {
1314   // FIXME: Should account for address space here.
1315 
1316   // The default fallback uses the private pointer size as a guess for a type to
1317   // use. Make sure we switch these to 64-bit accesses.
1318 
1319   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1320     return MVT::v4i32;
1321 
1322   if (Size >= 8 && DstAlign >= 4)
1323     return MVT::v2i32;
1324 
1325   // Use the default.
1326   return MVT::Other;
1327 }
1328 
1329 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1330                                            unsigned DestAS) const {
1331   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1332 }
1333 
1334 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1335   const MemSDNode *MemNode = cast<MemSDNode>(N);
1336   const Value *Ptr = MemNode->getMemOperand()->getValue();
1337   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1338   return I && I->getMetadata("amdgpu.noclobber");
1339 }
1340 
1341 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1342                                            unsigned DestAS) const {
1343   // Flat -> private/local is a simple truncate.
1344   // Flat -> global is no-op
1345   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1346     return true;
1347 
1348   return isNoopAddrSpaceCast(SrcAS, DestAS);
1349 }
1350 
1351 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1352   const MemSDNode *MemNode = cast<MemSDNode>(N);
1353 
1354   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1355 }
1356 
1357 TargetLoweringBase::LegalizeTypeAction
1358 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1359   int NumElts = VT.getVectorNumElements();
1360   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1361     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1362   return TargetLoweringBase::getPreferredVectorAction(VT);
1363 }
1364 
1365 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1366                                                          Type *Ty) const {
1367   // FIXME: Could be smarter if called for vector constants.
1368   return true;
1369 }
1370 
1371 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1372   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1373     switch (Op) {
1374     case ISD::LOAD:
1375     case ISD::STORE:
1376 
1377     // These operations are done with 32-bit instructions anyway.
1378     case ISD::AND:
1379     case ISD::OR:
1380     case ISD::XOR:
1381     case ISD::SELECT:
1382       // TODO: Extensions?
1383       return true;
1384     default:
1385       return false;
1386     }
1387   }
1388 
1389   // SimplifySetCC uses this function to determine whether or not it should
1390   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1391   if (VT == MVT::i1 && Op == ISD::SETCC)
1392     return false;
1393 
1394   return TargetLowering::isTypeDesirableForOp(Op, VT);
1395 }
1396 
1397 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1398                                                    const SDLoc &SL,
1399                                                    SDValue Chain,
1400                                                    uint64_t Offset) const {
1401   const DataLayout &DL = DAG.getDataLayout();
1402   MachineFunction &MF = DAG.getMachineFunction();
1403   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1404 
1405   const ArgDescriptor *InputPtrReg;
1406   const TargetRegisterClass *RC;
1407 
1408   std::tie(InputPtrReg, RC)
1409     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1410 
1411   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1412   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1413   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1414     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1415 
1416   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1417 }
1418 
1419 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1420                                             const SDLoc &SL) const {
1421   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1422                                                FIRST_IMPLICIT);
1423   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1424 }
1425 
1426 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1427                                          const SDLoc &SL, SDValue Val,
1428                                          bool Signed,
1429                                          const ISD::InputArg *Arg) const {
1430   // First, if it is a widened vector, narrow it.
1431   if (VT.isVector() &&
1432       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1433     EVT NarrowedVT =
1434         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1435                          VT.getVectorNumElements());
1436     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1437                       DAG.getConstant(0, SL, MVT::i32));
1438   }
1439 
1440   // Then convert the vector elements or scalar value.
1441   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1442       VT.bitsLT(MemVT)) {
1443     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1444     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1445   }
1446 
1447   if (MemVT.isFloatingPoint())
1448     Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1449   else if (Signed)
1450     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1451   else
1452     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1453 
1454   return Val;
1455 }
1456 
1457 SDValue SITargetLowering::lowerKernargMemParameter(
1458   SelectionDAG &DAG, EVT VT, EVT MemVT,
1459   const SDLoc &SL, SDValue Chain,
1460   uint64_t Offset, unsigned Align, bool Signed,
1461   const ISD::InputArg *Arg) const {
1462   Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1463   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
1464   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1465 
1466   // Try to avoid using an extload by loading earlier than the argument address,
1467   // and extracting the relevant bits. The load should hopefully be merged with
1468   // the previous argument.
1469   if (MemVT.getStoreSize() < 4 && Align < 4) {
1470     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1471     int64_t AlignDownOffset = alignDown(Offset, 4);
1472     int64_t OffsetDiff = Offset - AlignDownOffset;
1473 
1474     EVT IntVT = MemVT.changeTypeToInteger();
1475 
1476     // TODO: If we passed in the base kernel offset we could have a better
1477     // alignment than 4, but we don't really need it.
1478     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1479     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1480                                MachineMemOperand::MODereferenceable |
1481                                MachineMemOperand::MOInvariant);
1482 
1483     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1484     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1485 
1486     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1487     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1488     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1489 
1490 
1491     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1492   }
1493 
1494   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1495   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1496                              MachineMemOperand::MODereferenceable |
1497                              MachineMemOperand::MOInvariant);
1498 
1499   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1500   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1501 }
1502 
1503 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1504                                               const SDLoc &SL, SDValue Chain,
1505                                               const ISD::InputArg &Arg) const {
1506   MachineFunction &MF = DAG.getMachineFunction();
1507   MachineFrameInfo &MFI = MF.getFrameInfo();
1508 
1509   if (Arg.Flags.isByVal()) {
1510     unsigned Size = Arg.Flags.getByValSize();
1511     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1512     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1513   }
1514 
1515   unsigned ArgOffset = VA.getLocMemOffset();
1516   unsigned ArgSize = VA.getValVT().getStoreSize();
1517 
1518   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1519 
1520   // Create load nodes to retrieve arguments from the stack.
1521   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1522   SDValue ArgValue;
1523 
1524   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1525   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1526   MVT MemVT = VA.getValVT();
1527 
1528   switch (VA.getLocInfo()) {
1529   default:
1530     break;
1531   case CCValAssign::BCvt:
1532     MemVT = VA.getLocVT();
1533     break;
1534   case CCValAssign::SExt:
1535     ExtType = ISD::SEXTLOAD;
1536     break;
1537   case CCValAssign::ZExt:
1538     ExtType = ISD::ZEXTLOAD;
1539     break;
1540   case CCValAssign::AExt:
1541     ExtType = ISD::EXTLOAD;
1542     break;
1543   }
1544 
1545   ArgValue = DAG.getExtLoad(
1546     ExtType, SL, VA.getLocVT(), Chain, FIN,
1547     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1548     MemVT);
1549   return ArgValue;
1550 }
1551 
1552 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1553   const SIMachineFunctionInfo &MFI,
1554   EVT VT,
1555   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1556   const ArgDescriptor *Reg;
1557   const TargetRegisterClass *RC;
1558 
1559   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1560   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1561 }
1562 
1563 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1564                                    CallingConv::ID CallConv,
1565                                    ArrayRef<ISD::InputArg> Ins,
1566                                    BitVector &Skipped,
1567                                    FunctionType *FType,
1568                                    SIMachineFunctionInfo *Info) {
1569   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1570     const ISD::InputArg *Arg = &Ins[I];
1571 
1572     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1573            "vector type argument should have been split");
1574 
1575     // First check if it's a PS input addr.
1576     if (CallConv == CallingConv::AMDGPU_PS &&
1577         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1578       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1579 
1580       // Inconveniently only the first part of the split is marked as isSplit,
1581       // so skip to the end. We only want to increment PSInputNum once for the
1582       // entire split argument.
1583       if (Arg->Flags.isSplit()) {
1584         while (!Arg->Flags.isSplitEnd()) {
1585           assert((!Arg->VT.isVector() ||
1586                   Arg->VT.getScalarSizeInBits() == 16) &&
1587                  "unexpected vector split in ps argument type");
1588           if (!SkipArg)
1589             Splits.push_back(*Arg);
1590           Arg = &Ins[++I];
1591         }
1592       }
1593 
1594       if (SkipArg) {
1595         // We can safely skip PS inputs.
1596         Skipped.set(Arg->getOrigArgIndex());
1597         ++PSInputNum;
1598         continue;
1599       }
1600 
1601       Info->markPSInputAllocated(PSInputNum);
1602       if (Arg->Used)
1603         Info->markPSInputEnabled(PSInputNum);
1604 
1605       ++PSInputNum;
1606     }
1607 
1608     Splits.push_back(*Arg);
1609   }
1610 }
1611 
1612 // Allocate special inputs passed in VGPRs.
1613 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1614                                                       MachineFunction &MF,
1615                                                       const SIRegisterInfo &TRI,
1616                                                       SIMachineFunctionInfo &Info) const {
1617   const LLT S32 = LLT::scalar(32);
1618   MachineRegisterInfo &MRI = MF.getRegInfo();
1619 
1620   if (Info.hasWorkItemIDX()) {
1621     Register Reg = AMDGPU::VGPR0;
1622     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1623 
1624     CCInfo.AllocateReg(Reg);
1625     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1626   }
1627 
1628   if (Info.hasWorkItemIDY()) {
1629     Register Reg = AMDGPU::VGPR1;
1630     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1631 
1632     CCInfo.AllocateReg(Reg);
1633     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1634   }
1635 
1636   if (Info.hasWorkItemIDZ()) {
1637     Register Reg = AMDGPU::VGPR2;
1638     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1639 
1640     CCInfo.AllocateReg(Reg);
1641     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1642   }
1643 }
1644 
1645 // Try to allocate a VGPR at the end of the argument list, or if no argument
1646 // VGPRs are left allocating a stack slot.
1647 // If \p Mask is is given it indicates bitfield position in the register.
1648 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1649 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1650                                          ArgDescriptor Arg = ArgDescriptor()) {
1651   if (Arg.isSet())
1652     return ArgDescriptor::createArg(Arg, Mask);
1653 
1654   ArrayRef<MCPhysReg> ArgVGPRs
1655     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1656   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1657   if (RegIdx == ArgVGPRs.size()) {
1658     // Spill to stack required.
1659     int64_t Offset = CCInfo.AllocateStack(4, 4);
1660 
1661     return ArgDescriptor::createStack(Offset, Mask);
1662   }
1663 
1664   unsigned Reg = ArgVGPRs[RegIdx];
1665   Reg = CCInfo.AllocateReg(Reg);
1666   assert(Reg != AMDGPU::NoRegister);
1667 
1668   MachineFunction &MF = CCInfo.getMachineFunction();
1669   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1670   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1671   return ArgDescriptor::createRegister(Reg, Mask);
1672 }
1673 
1674 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1675                                              const TargetRegisterClass *RC,
1676                                              unsigned NumArgRegs) {
1677   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1678   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1679   if (RegIdx == ArgSGPRs.size())
1680     report_fatal_error("ran out of SGPRs for arguments");
1681 
1682   unsigned Reg = ArgSGPRs[RegIdx];
1683   Reg = CCInfo.AllocateReg(Reg);
1684   assert(Reg != AMDGPU::NoRegister);
1685 
1686   MachineFunction &MF = CCInfo.getMachineFunction();
1687   MF.addLiveIn(Reg, RC);
1688   return ArgDescriptor::createRegister(Reg);
1689 }
1690 
1691 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1692   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1693 }
1694 
1695 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1696   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1697 }
1698 
1699 void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo,
1700                                                  MachineFunction &MF,
1701                                                  const SIRegisterInfo &TRI,
1702                                                  SIMachineFunctionInfo &Info) const {
1703   const unsigned Mask = 0x3ff;
1704   ArgDescriptor Arg;
1705 
1706   if (Info.hasWorkItemIDX()) {
1707     Arg = allocateVGPR32Input(CCInfo, Mask);
1708     Info.setWorkItemIDX(Arg);
1709   }
1710 
1711   if (Info.hasWorkItemIDY()) {
1712     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1713     Info.setWorkItemIDY(Arg);
1714   }
1715 
1716   if (Info.hasWorkItemIDZ())
1717     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1718 }
1719 
1720 void SITargetLowering::allocateSpecialInputSGPRs(
1721   CCState &CCInfo,
1722   MachineFunction &MF,
1723   const SIRegisterInfo &TRI,
1724   SIMachineFunctionInfo &Info) const {
1725   auto &ArgInfo = Info.getArgInfo();
1726 
1727   // TODO: Unify handling with private memory pointers.
1728 
1729   if (Info.hasDispatchPtr())
1730     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1731 
1732   if (Info.hasQueuePtr())
1733     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1734 
1735   if (Info.hasKernargSegmentPtr())
1736     ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1737 
1738   if (Info.hasDispatchID())
1739     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1740 
1741   // flat_scratch_init is not applicable for non-kernel functions.
1742 
1743   if (Info.hasWorkGroupIDX())
1744     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1745 
1746   if (Info.hasWorkGroupIDY())
1747     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1748 
1749   if (Info.hasWorkGroupIDZ())
1750     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1751 
1752   if (Info.hasImplicitArgPtr())
1753     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1754 }
1755 
1756 // Allocate special inputs passed in user SGPRs.
1757 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1758                                             MachineFunction &MF,
1759                                             const SIRegisterInfo &TRI,
1760                                             SIMachineFunctionInfo &Info) const {
1761   if (Info.hasImplicitBufferPtr()) {
1762     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1763     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1764     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1765   }
1766 
1767   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1768   if (Info.hasPrivateSegmentBuffer()) {
1769     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1770     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1771     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1772   }
1773 
1774   if (Info.hasDispatchPtr()) {
1775     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1776     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1777     CCInfo.AllocateReg(DispatchPtrReg);
1778   }
1779 
1780   if (Info.hasQueuePtr()) {
1781     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1782     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1783     CCInfo.AllocateReg(QueuePtrReg);
1784   }
1785 
1786   if (Info.hasKernargSegmentPtr()) {
1787     MachineRegisterInfo &MRI = MF.getRegInfo();
1788     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1789     CCInfo.AllocateReg(InputPtrReg);
1790 
1791     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1792     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1793   }
1794 
1795   if (Info.hasDispatchID()) {
1796     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1797     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1798     CCInfo.AllocateReg(DispatchIDReg);
1799   }
1800 
1801   if (Info.hasFlatScratchInit()) {
1802     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1803     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1804     CCInfo.AllocateReg(FlatScratchInitReg);
1805   }
1806 
1807   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1808   // these from the dispatch pointer.
1809 }
1810 
1811 // Allocate special input registers that are initialized per-wave.
1812 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1813                                            MachineFunction &MF,
1814                                            SIMachineFunctionInfo &Info,
1815                                            CallingConv::ID CallConv,
1816                                            bool IsShader) const {
1817   if (Info.hasWorkGroupIDX()) {
1818     unsigned Reg = Info.addWorkGroupIDX();
1819     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1820     CCInfo.AllocateReg(Reg);
1821   }
1822 
1823   if (Info.hasWorkGroupIDY()) {
1824     unsigned Reg = Info.addWorkGroupIDY();
1825     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1826     CCInfo.AllocateReg(Reg);
1827   }
1828 
1829   if (Info.hasWorkGroupIDZ()) {
1830     unsigned Reg = Info.addWorkGroupIDZ();
1831     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1832     CCInfo.AllocateReg(Reg);
1833   }
1834 
1835   if (Info.hasWorkGroupInfo()) {
1836     unsigned Reg = Info.addWorkGroupInfo();
1837     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1838     CCInfo.AllocateReg(Reg);
1839   }
1840 
1841   if (Info.hasPrivateSegmentWaveByteOffset()) {
1842     // Scratch wave offset passed in system SGPR.
1843     unsigned PrivateSegmentWaveByteOffsetReg;
1844 
1845     if (IsShader) {
1846       PrivateSegmentWaveByteOffsetReg =
1847         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1848 
1849       // This is true if the scratch wave byte offset doesn't have a fixed
1850       // location.
1851       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1852         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1853         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1854       }
1855     } else
1856       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1857 
1858     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1859     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1860   }
1861 }
1862 
1863 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1864                                      MachineFunction &MF,
1865                                      const SIRegisterInfo &TRI,
1866                                      SIMachineFunctionInfo &Info) {
1867   // Now that we've figured out where the scratch register inputs are, see if
1868   // should reserve the arguments and use them directly.
1869   MachineFrameInfo &MFI = MF.getFrameInfo();
1870   bool HasStackObjects = MFI.hasStackObjects();
1871   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1872 
1873   // Record that we know we have non-spill stack objects so we don't need to
1874   // check all stack objects later.
1875   if (HasStackObjects)
1876     Info.setHasNonSpillStackObjects(true);
1877 
1878   // Everything live out of a block is spilled with fast regalloc, so it's
1879   // almost certain that spilling will be required.
1880   if (TM.getOptLevel() == CodeGenOpt::None)
1881     HasStackObjects = true;
1882 
1883   // For now assume stack access is needed in any callee functions, so we need
1884   // the scratch registers to pass in.
1885   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1886 
1887   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1888     // If we have stack objects, we unquestionably need the private buffer
1889     // resource. For the Code Object V2 ABI, this will be the first 4 user
1890     // SGPR inputs. We can reserve those and use them directly.
1891 
1892     Register PrivateSegmentBufferReg =
1893         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1894     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1895   } else {
1896     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1897     // We tentatively reserve the last registers (skipping the last registers
1898     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1899     // we'll replace these with the ones immediately after those which were
1900     // really allocated. In the prologue copies will be inserted from the
1901     // argument to these reserved registers.
1902 
1903     // Without HSA, relocations are used for the scratch pointer and the
1904     // buffer resource setup is always inserted in the prologue. Scratch wave
1905     // offset is still in an input SGPR.
1906     Info.setScratchRSrcReg(ReservedBufferReg);
1907   }
1908 
1909   // hasFP should be accurate for kernels even before the frame is finalized.
1910   if (ST.getFrameLowering()->hasFP(MF)) {
1911     MachineRegisterInfo &MRI = MF.getRegInfo();
1912 
1913     // Try to use s32 as the SP, but move it if it would interfere with input
1914     // arguments. This won't work with calls though.
1915     //
1916     // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1917     // registers.
1918     if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1919       Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1920     } else {
1921       assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1922 
1923       if (MFI.hasCalls())
1924         report_fatal_error("call in graphics shader with too many input SGPRs");
1925 
1926       for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1927         if (!MRI.isLiveIn(Reg)) {
1928           Info.setStackPtrOffsetReg(Reg);
1929           break;
1930         }
1931       }
1932 
1933       if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1934         report_fatal_error("failed to find register for SP");
1935     }
1936 
1937     if (MFI.hasCalls()) {
1938       Info.setScratchWaveOffsetReg(AMDGPU::SGPR33);
1939       Info.setFrameOffsetReg(AMDGPU::SGPR33);
1940     } else {
1941       unsigned ReservedOffsetReg =
1942         TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1943       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1944       Info.setFrameOffsetReg(ReservedOffsetReg);
1945     }
1946   } else if (RequiresStackAccess) {
1947     assert(!MFI.hasCalls());
1948     // We know there are accesses and they will be done relative to SP, so just
1949     // pin it to the input.
1950     //
1951     // FIXME: Should not do this if inline asm is reading/writing these
1952     // registers.
1953     Register PreloadedSP = Info.getPreloadedReg(
1954         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1955 
1956     Info.setStackPtrOffsetReg(PreloadedSP);
1957     Info.setScratchWaveOffsetReg(PreloadedSP);
1958     Info.setFrameOffsetReg(PreloadedSP);
1959   } else {
1960     assert(!MFI.hasCalls());
1961 
1962     // There may not be stack access at all. There may still be spills, or
1963     // access of a constant pointer (in which cases an extra copy will be
1964     // emitted in the prolog).
1965     unsigned ReservedOffsetReg
1966       = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1967     Info.setStackPtrOffsetReg(ReservedOffsetReg);
1968     Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1969     Info.setFrameOffsetReg(ReservedOffsetReg);
1970   }
1971 }
1972 
1973 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1974   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1975   return !Info->isEntryFunction();
1976 }
1977 
1978 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1979 
1980 }
1981 
1982 void SITargetLowering::insertCopiesSplitCSR(
1983   MachineBasicBlock *Entry,
1984   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1985   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1986 
1987   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1988   if (!IStart)
1989     return;
1990 
1991   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1992   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1993   MachineBasicBlock::iterator MBBI = Entry->begin();
1994   for (const MCPhysReg *I = IStart; *I; ++I) {
1995     const TargetRegisterClass *RC = nullptr;
1996     if (AMDGPU::SReg_64RegClass.contains(*I))
1997       RC = &AMDGPU::SGPR_64RegClass;
1998     else if (AMDGPU::SReg_32RegClass.contains(*I))
1999       RC = &AMDGPU::SGPR_32RegClass;
2000     else
2001       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2002 
2003     Register NewVR = MRI->createVirtualRegister(RC);
2004     // Create copy from CSR to a virtual register.
2005     Entry->addLiveIn(*I);
2006     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2007       .addReg(*I);
2008 
2009     // Insert the copy-back instructions right before the terminator.
2010     for (auto *Exit : Exits)
2011       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2012               TII->get(TargetOpcode::COPY), *I)
2013         .addReg(NewVR);
2014   }
2015 }
2016 
2017 SDValue SITargetLowering::LowerFormalArguments(
2018     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2019     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2020     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2021   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2022 
2023   MachineFunction &MF = DAG.getMachineFunction();
2024   const Function &Fn = MF.getFunction();
2025   FunctionType *FType = MF.getFunction().getFunctionType();
2026   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2027 
2028   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2029     DiagnosticInfoUnsupported NoGraphicsHSA(
2030         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2031     DAG.getContext()->diagnose(NoGraphicsHSA);
2032     return DAG.getEntryNode();
2033   }
2034 
2035   SmallVector<ISD::InputArg, 16> Splits;
2036   SmallVector<CCValAssign, 16> ArgLocs;
2037   BitVector Skipped(Ins.size());
2038   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2039                  *DAG.getContext());
2040 
2041   bool IsShader = AMDGPU::isShader(CallConv);
2042   bool IsKernel = AMDGPU::isKernel(CallConv);
2043   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2044 
2045   if (IsShader) {
2046     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2047 
2048     // At least one interpolation mode must be enabled or else the GPU will
2049     // hang.
2050     //
2051     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2052     // set PSInputAddr, the user wants to enable some bits after the compilation
2053     // based on run-time states. Since we can't know what the final PSInputEna
2054     // will look like, so we shouldn't do anything here and the user should take
2055     // responsibility for the correct programming.
2056     //
2057     // Otherwise, the following restrictions apply:
2058     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2059     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2060     //   enabled too.
2061     if (CallConv == CallingConv::AMDGPU_PS) {
2062       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2063            ((Info->getPSInputAddr() & 0xF) == 0 &&
2064             Info->isPSInputAllocated(11))) {
2065         CCInfo.AllocateReg(AMDGPU::VGPR0);
2066         CCInfo.AllocateReg(AMDGPU::VGPR1);
2067         Info->markPSInputAllocated(0);
2068         Info->markPSInputEnabled(0);
2069       }
2070       if (Subtarget->isAmdPalOS()) {
2071         // For isAmdPalOS, the user does not enable some bits after compilation
2072         // based on run-time states; the register values being generated here are
2073         // the final ones set in hardware. Therefore we need to apply the
2074         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2075         // a bit is set in PSInputAddr but not PSInputEnable is where the
2076         // frontend set up an input arg for a particular interpolation mode, but
2077         // nothing uses that input arg. Really we should have an earlier pass
2078         // that removes such an arg.)
2079         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2080         if ((PsInputBits & 0x7F) == 0 ||
2081             ((PsInputBits & 0xF) == 0 &&
2082              (PsInputBits >> 11 & 1)))
2083           Info->markPSInputEnabled(
2084               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2085       }
2086     }
2087 
2088     assert(!Info->hasDispatchPtr() &&
2089            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2090            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2091            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2092            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2093            !Info->hasWorkItemIDZ());
2094   } else if (IsKernel) {
2095     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2096   } else {
2097     Splits.append(Ins.begin(), Ins.end());
2098   }
2099 
2100   if (IsEntryFunc) {
2101     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2102     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2103   }
2104 
2105   if (IsKernel) {
2106     analyzeFormalArgumentsCompute(CCInfo, Ins);
2107   } else {
2108     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2109     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2110   }
2111 
2112   SmallVector<SDValue, 16> Chains;
2113 
2114   // FIXME: This is the minimum kernel argument alignment. We should improve
2115   // this to the maximum alignment of the arguments.
2116   //
2117   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2118   // kern arg offset.
2119   const unsigned KernelArgBaseAlign = 16;
2120 
2121    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2122     const ISD::InputArg &Arg = Ins[i];
2123     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2124       InVals.push_back(DAG.getUNDEF(Arg.VT));
2125       continue;
2126     }
2127 
2128     CCValAssign &VA = ArgLocs[ArgIdx++];
2129     MVT VT = VA.getLocVT();
2130 
2131     if (IsEntryFunc && VA.isMemLoc()) {
2132       VT = Ins[i].VT;
2133       EVT MemVT = VA.getLocVT();
2134 
2135       const uint64_t Offset = VA.getLocMemOffset();
2136       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2137 
2138       SDValue Arg = lowerKernargMemParameter(
2139         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2140       Chains.push_back(Arg.getValue(1));
2141 
2142       auto *ParamTy =
2143         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2144       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2145           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2146                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2147         // On SI local pointers are just offsets into LDS, so they are always
2148         // less than 16-bits.  On CI and newer they could potentially be
2149         // real pointers, so we can't guarantee their size.
2150         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2151                           DAG.getValueType(MVT::i16));
2152       }
2153 
2154       InVals.push_back(Arg);
2155       continue;
2156     } else if (!IsEntryFunc && VA.isMemLoc()) {
2157       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2158       InVals.push_back(Val);
2159       if (!Arg.Flags.isByVal())
2160         Chains.push_back(Val.getValue(1));
2161       continue;
2162     }
2163 
2164     assert(VA.isRegLoc() && "Parameter must be in a register!");
2165 
2166     Register Reg = VA.getLocReg();
2167     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2168     EVT ValVT = VA.getValVT();
2169 
2170     Reg = MF.addLiveIn(Reg, RC);
2171     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2172 
2173     if (Arg.Flags.isSRet()) {
2174       // The return object should be reasonably addressable.
2175 
2176       // FIXME: This helps when the return is a real sret. If it is a
2177       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2178       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2179       unsigned NumBits
2180         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2181       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2182         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2183     }
2184 
2185     // If this is an 8 or 16-bit value, it is really passed promoted
2186     // to 32 bits. Insert an assert[sz]ext to capture this, then
2187     // truncate to the right size.
2188     switch (VA.getLocInfo()) {
2189     case CCValAssign::Full:
2190       break;
2191     case CCValAssign::BCvt:
2192       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2193       break;
2194     case CCValAssign::SExt:
2195       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2196                         DAG.getValueType(ValVT));
2197       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2198       break;
2199     case CCValAssign::ZExt:
2200       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2201                         DAG.getValueType(ValVT));
2202       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2203       break;
2204     case CCValAssign::AExt:
2205       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2206       break;
2207     default:
2208       llvm_unreachable("Unknown loc info!");
2209     }
2210 
2211     InVals.push_back(Val);
2212   }
2213 
2214   if (!IsEntryFunc) {
2215     // Special inputs come after user arguments.
2216     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2217   }
2218 
2219   // Start adding system SGPRs.
2220   if (IsEntryFunc) {
2221     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2222   } else {
2223     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2224     CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2225     CCInfo.AllocateReg(Info->getFrameOffsetReg());
2226     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2227   }
2228 
2229   auto &ArgUsageInfo =
2230     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2231   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2232 
2233   unsigned StackArgSize = CCInfo.getNextStackOffset();
2234   Info->setBytesInStackArgArea(StackArgSize);
2235 
2236   return Chains.empty() ? Chain :
2237     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2238 }
2239 
2240 // TODO: If return values can't fit in registers, we should return as many as
2241 // possible in registers before passing on stack.
2242 bool SITargetLowering::CanLowerReturn(
2243   CallingConv::ID CallConv,
2244   MachineFunction &MF, bool IsVarArg,
2245   const SmallVectorImpl<ISD::OutputArg> &Outs,
2246   LLVMContext &Context) const {
2247   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2248   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2249   // for shaders. Vector types should be explicitly handled by CC.
2250   if (AMDGPU::isEntryFunctionCC(CallConv))
2251     return true;
2252 
2253   SmallVector<CCValAssign, 16> RVLocs;
2254   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2255   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2256 }
2257 
2258 SDValue
2259 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2260                               bool isVarArg,
2261                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2262                               const SmallVectorImpl<SDValue> &OutVals,
2263                               const SDLoc &DL, SelectionDAG &DAG) const {
2264   MachineFunction &MF = DAG.getMachineFunction();
2265   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2266 
2267   if (AMDGPU::isKernel(CallConv)) {
2268     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2269                                              OutVals, DL, DAG);
2270   }
2271 
2272   bool IsShader = AMDGPU::isShader(CallConv);
2273 
2274   Info->setIfReturnsVoid(Outs.empty());
2275   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2276 
2277   // CCValAssign - represent the assignment of the return value to a location.
2278   SmallVector<CCValAssign, 48> RVLocs;
2279   SmallVector<ISD::OutputArg, 48> Splits;
2280 
2281   // CCState - Info about the registers and stack slots.
2282   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2283                  *DAG.getContext());
2284 
2285   // Analyze outgoing return values.
2286   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2287 
2288   SDValue Flag;
2289   SmallVector<SDValue, 48> RetOps;
2290   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2291 
2292   // Add return address for callable functions.
2293   if (!Info->isEntryFunction()) {
2294     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2295     SDValue ReturnAddrReg = CreateLiveInRegister(
2296       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2297 
2298     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2299         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2300         MVT::i64);
2301     Chain =
2302         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2303     Flag = Chain.getValue(1);
2304     RetOps.push_back(ReturnAddrVirtualReg);
2305   }
2306 
2307   // Copy the result values into the output registers.
2308   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2309        ++I, ++RealRVLocIdx) {
2310     CCValAssign &VA = RVLocs[I];
2311     assert(VA.isRegLoc() && "Can only return in registers!");
2312     // TODO: Partially return in registers if return values don't fit.
2313     SDValue Arg = OutVals[RealRVLocIdx];
2314 
2315     // Copied from other backends.
2316     switch (VA.getLocInfo()) {
2317     case CCValAssign::Full:
2318       break;
2319     case CCValAssign::BCvt:
2320       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2321       break;
2322     case CCValAssign::SExt:
2323       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2324       break;
2325     case CCValAssign::ZExt:
2326       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2327       break;
2328     case CCValAssign::AExt:
2329       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2330       break;
2331     default:
2332       llvm_unreachable("Unknown loc info!");
2333     }
2334 
2335     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2336     Flag = Chain.getValue(1);
2337     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2338   }
2339 
2340   // FIXME: Does sret work properly?
2341   if (!Info->isEntryFunction()) {
2342     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2343     const MCPhysReg *I =
2344       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2345     if (I) {
2346       for (; *I; ++I) {
2347         if (AMDGPU::SReg_64RegClass.contains(*I))
2348           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2349         else if (AMDGPU::SReg_32RegClass.contains(*I))
2350           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2351         else
2352           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2353       }
2354     }
2355   }
2356 
2357   // Update chain and glue.
2358   RetOps[0] = Chain;
2359   if (Flag.getNode())
2360     RetOps.push_back(Flag);
2361 
2362   unsigned Opc = AMDGPUISD::ENDPGM;
2363   if (!IsWaveEnd)
2364     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2365   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2366 }
2367 
2368 SDValue SITargetLowering::LowerCallResult(
2369     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2370     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2371     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2372     SDValue ThisVal) const {
2373   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2374 
2375   // Assign locations to each value returned by this call.
2376   SmallVector<CCValAssign, 16> RVLocs;
2377   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2378                  *DAG.getContext());
2379   CCInfo.AnalyzeCallResult(Ins, RetCC);
2380 
2381   // Copy all of the result registers out of their specified physreg.
2382   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2383     CCValAssign VA = RVLocs[i];
2384     SDValue Val;
2385 
2386     if (VA.isRegLoc()) {
2387       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2388       Chain = Val.getValue(1);
2389       InFlag = Val.getValue(2);
2390     } else if (VA.isMemLoc()) {
2391       report_fatal_error("TODO: return values in memory");
2392     } else
2393       llvm_unreachable("unknown argument location type");
2394 
2395     switch (VA.getLocInfo()) {
2396     case CCValAssign::Full:
2397       break;
2398     case CCValAssign::BCvt:
2399       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2400       break;
2401     case CCValAssign::ZExt:
2402       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2403                         DAG.getValueType(VA.getValVT()));
2404       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2405       break;
2406     case CCValAssign::SExt:
2407       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2408                         DAG.getValueType(VA.getValVT()));
2409       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2410       break;
2411     case CCValAssign::AExt:
2412       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2413       break;
2414     default:
2415       llvm_unreachable("Unknown loc info!");
2416     }
2417 
2418     InVals.push_back(Val);
2419   }
2420 
2421   return Chain;
2422 }
2423 
2424 // Add code to pass special inputs required depending on used features separate
2425 // from the explicit user arguments present in the IR.
2426 void SITargetLowering::passSpecialInputs(
2427     CallLoweringInfo &CLI,
2428     CCState &CCInfo,
2429     const SIMachineFunctionInfo &Info,
2430     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2431     SmallVectorImpl<SDValue> &MemOpChains,
2432     SDValue Chain) const {
2433   // If we don't have a call site, this was a call inserted by
2434   // legalization. These can never use special inputs.
2435   if (!CLI.CS)
2436     return;
2437 
2438   const Function *CalleeFunc = CLI.CS.getCalledFunction();
2439   assert(CalleeFunc);
2440 
2441   SelectionDAG &DAG = CLI.DAG;
2442   const SDLoc &DL = CLI.DL;
2443 
2444   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2445 
2446   auto &ArgUsageInfo =
2447     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2448   const AMDGPUFunctionArgInfo &CalleeArgInfo
2449     = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2450 
2451   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2452 
2453   // TODO: Unify with private memory register handling. This is complicated by
2454   // the fact that at least in kernels, the input argument is not necessarily
2455   // in the same location as the input.
2456   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2457     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2458     AMDGPUFunctionArgInfo::QUEUE_PTR,
2459     AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2460     AMDGPUFunctionArgInfo::DISPATCH_ID,
2461     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2462     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2463     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2464     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2465   };
2466 
2467   for (auto InputID : InputRegs) {
2468     const ArgDescriptor *OutgoingArg;
2469     const TargetRegisterClass *ArgRC;
2470 
2471     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2472     if (!OutgoingArg)
2473       continue;
2474 
2475     const ArgDescriptor *IncomingArg;
2476     const TargetRegisterClass *IncomingArgRC;
2477     std::tie(IncomingArg, IncomingArgRC)
2478       = CallerArgInfo.getPreloadedValue(InputID);
2479     assert(IncomingArgRC == ArgRC);
2480 
2481     // All special arguments are ints for now.
2482     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2483     SDValue InputReg;
2484 
2485     if (IncomingArg) {
2486       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2487     } else {
2488       // The implicit arg ptr is special because it doesn't have a corresponding
2489       // input for kernels, and is computed from the kernarg segment pointer.
2490       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2491       InputReg = getImplicitArgPtr(DAG, DL);
2492     }
2493 
2494     if (OutgoingArg->isRegister()) {
2495       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2496     } else {
2497       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2498       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2499                                               SpecialArgOffset);
2500       MemOpChains.push_back(ArgStore);
2501     }
2502   }
2503 
2504   // Pack workitem IDs into a single register or pass it as is if already
2505   // packed.
2506   const ArgDescriptor *OutgoingArg;
2507   const TargetRegisterClass *ArgRC;
2508 
2509   std::tie(OutgoingArg, ArgRC) =
2510     CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2511   if (!OutgoingArg)
2512     std::tie(OutgoingArg, ArgRC) =
2513       CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2514   if (!OutgoingArg)
2515     std::tie(OutgoingArg, ArgRC) =
2516       CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2517   if (!OutgoingArg)
2518     return;
2519 
2520   const ArgDescriptor *IncomingArgX
2521     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2522   const ArgDescriptor *IncomingArgY
2523     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2524   const ArgDescriptor *IncomingArgZ
2525     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2526 
2527   SDValue InputReg;
2528   SDLoc SL;
2529 
2530   // If incoming ids are not packed we need to pack them.
2531   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX)
2532     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2533 
2534   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) {
2535     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2536     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2537                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2538     InputReg = InputReg.getNode() ?
2539                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2540   }
2541 
2542   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) {
2543     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2544     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2545                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2546     InputReg = InputReg.getNode() ?
2547                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2548   }
2549 
2550   if (!InputReg.getNode()) {
2551     // Workitem ids are already packed, any of present incoming arguments
2552     // will carry all required fields.
2553     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2554       IncomingArgX ? *IncomingArgX :
2555       IncomingArgY ? *IncomingArgY :
2556                      *IncomingArgZ, ~0u);
2557     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2558   }
2559 
2560   if (OutgoingArg->isRegister()) {
2561     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2562   } else {
2563     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2564     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2565                                             SpecialArgOffset);
2566     MemOpChains.push_back(ArgStore);
2567   }
2568 }
2569 
2570 static bool canGuaranteeTCO(CallingConv::ID CC) {
2571   return CC == CallingConv::Fast;
2572 }
2573 
2574 /// Return true if we might ever do TCO for calls with this calling convention.
2575 static bool mayTailCallThisCC(CallingConv::ID CC) {
2576   switch (CC) {
2577   case CallingConv::C:
2578     return true;
2579   default:
2580     return canGuaranteeTCO(CC);
2581   }
2582 }
2583 
2584 bool SITargetLowering::isEligibleForTailCallOptimization(
2585     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2586     const SmallVectorImpl<ISD::OutputArg> &Outs,
2587     const SmallVectorImpl<SDValue> &OutVals,
2588     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2589   if (!mayTailCallThisCC(CalleeCC))
2590     return false;
2591 
2592   MachineFunction &MF = DAG.getMachineFunction();
2593   const Function &CallerF = MF.getFunction();
2594   CallingConv::ID CallerCC = CallerF.getCallingConv();
2595   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2596   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2597 
2598   // Kernels aren't callable, and don't have a live in return address so it
2599   // doesn't make sense to do a tail call with entry functions.
2600   if (!CallerPreserved)
2601     return false;
2602 
2603   bool CCMatch = CallerCC == CalleeCC;
2604 
2605   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2606     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2607       return true;
2608     return false;
2609   }
2610 
2611   // TODO: Can we handle var args?
2612   if (IsVarArg)
2613     return false;
2614 
2615   for (const Argument &Arg : CallerF.args()) {
2616     if (Arg.hasByValAttr())
2617       return false;
2618   }
2619 
2620   LLVMContext &Ctx = *DAG.getContext();
2621 
2622   // Check that the call results are passed in the same way.
2623   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2624                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2625                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2626     return false;
2627 
2628   // The callee has to preserve all registers the caller needs to preserve.
2629   if (!CCMatch) {
2630     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2631     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2632       return false;
2633   }
2634 
2635   // Nothing more to check if the callee is taking no arguments.
2636   if (Outs.empty())
2637     return true;
2638 
2639   SmallVector<CCValAssign, 16> ArgLocs;
2640   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2641 
2642   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2643 
2644   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2645   // If the stack arguments for this call do not fit into our own save area then
2646   // the call cannot be made tail.
2647   // TODO: Is this really necessary?
2648   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2649     return false;
2650 
2651   const MachineRegisterInfo &MRI = MF.getRegInfo();
2652   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2653 }
2654 
2655 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2656   if (!CI->isTailCall())
2657     return false;
2658 
2659   const Function *ParentFn = CI->getParent()->getParent();
2660   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2661     return false;
2662 
2663   auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2664   return (Attr.getValueAsString() != "true");
2665 }
2666 
2667 // The wave scratch offset register is used as the global base pointer.
2668 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2669                                     SmallVectorImpl<SDValue> &InVals) const {
2670   SelectionDAG &DAG = CLI.DAG;
2671   const SDLoc &DL = CLI.DL;
2672   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2673   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2674   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2675   SDValue Chain = CLI.Chain;
2676   SDValue Callee = CLI.Callee;
2677   bool &IsTailCall = CLI.IsTailCall;
2678   CallingConv::ID CallConv = CLI.CallConv;
2679   bool IsVarArg = CLI.IsVarArg;
2680   bool IsSibCall = false;
2681   bool IsThisReturn = false;
2682   MachineFunction &MF = DAG.getMachineFunction();
2683 
2684   if (Callee.isUndef() || isNullConstant(Callee)) {
2685     if (!CLI.IsTailCall) {
2686       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2687         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2688     }
2689 
2690     return Chain;
2691   }
2692 
2693   if (IsVarArg) {
2694     return lowerUnhandledCall(CLI, InVals,
2695                               "unsupported call to variadic function ");
2696   }
2697 
2698   if (!CLI.CS.getInstruction())
2699     report_fatal_error("unsupported libcall legalization");
2700 
2701   if (!CLI.CS.getCalledFunction()) {
2702     return lowerUnhandledCall(CLI, InVals,
2703                               "unsupported indirect call to function ");
2704   }
2705 
2706   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2707     return lowerUnhandledCall(CLI, InVals,
2708                               "unsupported required tail call to function ");
2709   }
2710 
2711   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2712     // Note the issue is with the CC of the calling function, not of the call
2713     // itself.
2714     return lowerUnhandledCall(CLI, InVals,
2715                           "unsupported call from graphics shader of function ");
2716   }
2717 
2718   if (IsTailCall) {
2719     IsTailCall = isEligibleForTailCallOptimization(
2720       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2721     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2722       report_fatal_error("failed to perform tail call elimination on a call "
2723                          "site marked musttail");
2724     }
2725 
2726     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2727 
2728     // A sibling call is one where we're under the usual C ABI and not planning
2729     // to change that but can still do a tail call:
2730     if (!TailCallOpt && IsTailCall)
2731       IsSibCall = true;
2732 
2733     if (IsTailCall)
2734       ++NumTailCalls;
2735   }
2736 
2737   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2738 
2739   // Analyze operands of the call, assigning locations to each operand.
2740   SmallVector<CCValAssign, 16> ArgLocs;
2741   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2742   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2743 
2744   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2745 
2746   // Get a count of how many bytes are to be pushed on the stack.
2747   unsigned NumBytes = CCInfo.getNextStackOffset();
2748 
2749   if (IsSibCall) {
2750     // Since we're not changing the ABI to make this a tail call, the memory
2751     // operands are already available in the caller's incoming argument space.
2752     NumBytes = 0;
2753   }
2754 
2755   // FPDiff is the byte offset of the call's argument area from the callee's.
2756   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2757   // by this amount for a tail call. In a sibling call it must be 0 because the
2758   // caller will deallocate the entire stack and the callee still expects its
2759   // arguments to begin at SP+0. Completely unused for non-tail calls.
2760   int32_t FPDiff = 0;
2761   MachineFrameInfo &MFI = MF.getFrameInfo();
2762   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2763 
2764   // Adjust the stack pointer for the new arguments...
2765   // These operations are automatically eliminated by the prolog/epilog pass
2766   if (!IsSibCall) {
2767     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2768 
2769     SmallVector<SDValue, 4> CopyFromChains;
2770 
2771     // In the HSA case, this should be an identity copy.
2772     SDValue ScratchRSrcReg
2773       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2774     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2775     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2776     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2777   }
2778 
2779   SmallVector<SDValue, 8> MemOpChains;
2780   MVT PtrVT = MVT::i32;
2781 
2782   // Walk the register/memloc assignments, inserting copies/loads.
2783   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2784        ++i, ++realArgIdx) {
2785     CCValAssign &VA = ArgLocs[i];
2786     SDValue Arg = OutVals[realArgIdx];
2787 
2788     // Promote the value if needed.
2789     switch (VA.getLocInfo()) {
2790     case CCValAssign::Full:
2791       break;
2792     case CCValAssign::BCvt:
2793       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2794       break;
2795     case CCValAssign::ZExt:
2796       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2797       break;
2798     case CCValAssign::SExt:
2799       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2800       break;
2801     case CCValAssign::AExt:
2802       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2803       break;
2804     case CCValAssign::FPExt:
2805       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2806       break;
2807     default:
2808       llvm_unreachable("Unknown loc info!");
2809     }
2810 
2811     if (VA.isRegLoc()) {
2812       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2813     } else {
2814       assert(VA.isMemLoc());
2815 
2816       SDValue DstAddr;
2817       MachinePointerInfo DstInfo;
2818 
2819       unsigned LocMemOffset = VA.getLocMemOffset();
2820       int32_t Offset = LocMemOffset;
2821 
2822       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2823       MaybeAlign Alignment;
2824 
2825       if (IsTailCall) {
2826         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2827         unsigned OpSize = Flags.isByVal() ?
2828           Flags.getByValSize() : VA.getValVT().getStoreSize();
2829 
2830         // FIXME: We can have better than the minimum byval required alignment.
2831         Alignment =
2832             Flags.isByVal()
2833                 ? MaybeAlign(Flags.getByValAlign())
2834                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2835 
2836         Offset = Offset + FPDiff;
2837         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2838 
2839         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2840         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2841 
2842         // Make sure any stack arguments overlapping with where we're storing
2843         // are loaded before this eventual operation. Otherwise they'll be
2844         // clobbered.
2845 
2846         // FIXME: Why is this really necessary? This seems to just result in a
2847         // lot of code to copy the stack and write them back to the same
2848         // locations, which are supposed to be immutable?
2849         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2850       } else {
2851         DstAddr = PtrOff;
2852         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2853         Alignment =
2854             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2855       }
2856 
2857       if (Outs[i].Flags.isByVal()) {
2858         SDValue SizeNode =
2859             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2860         SDValue Cpy = DAG.getMemcpy(
2861             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2862             /*isVol = */ false, /*AlwaysInline = */ true,
2863             /*isTailCall = */ false, DstInfo,
2864             MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2865                 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS))));
2866 
2867         MemOpChains.push_back(Cpy);
2868       } else {
2869         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2870                                      Alignment ? Alignment->value() : 0);
2871         MemOpChains.push_back(Store);
2872       }
2873     }
2874   }
2875 
2876   // Copy special input registers after user input arguments.
2877   passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2878 
2879   if (!MemOpChains.empty())
2880     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2881 
2882   // Build a sequence of copy-to-reg nodes chained together with token chain
2883   // and flag operands which copy the outgoing args into the appropriate regs.
2884   SDValue InFlag;
2885   for (auto &RegToPass : RegsToPass) {
2886     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2887                              RegToPass.second, InFlag);
2888     InFlag = Chain.getValue(1);
2889   }
2890 
2891 
2892   SDValue PhysReturnAddrReg;
2893   if (IsTailCall) {
2894     // Since the return is being combined with the call, we need to pass on the
2895     // return address.
2896 
2897     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2898     SDValue ReturnAddrReg = CreateLiveInRegister(
2899       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2900 
2901     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2902                                         MVT::i64);
2903     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2904     InFlag = Chain.getValue(1);
2905   }
2906 
2907   // We don't usually want to end the call-sequence here because we would tidy
2908   // the frame up *after* the call, however in the ABI-changing tail-call case
2909   // we've carefully laid out the parameters so that when sp is reset they'll be
2910   // in the correct location.
2911   if (IsTailCall && !IsSibCall) {
2912     Chain = DAG.getCALLSEQ_END(Chain,
2913                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2914                                DAG.getTargetConstant(0, DL, MVT::i32),
2915                                InFlag, DL);
2916     InFlag = Chain.getValue(1);
2917   }
2918 
2919   std::vector<SDValue> Ops;
2920   Ops.push_back(Chain);
2921   Ops.push_back(Callee);
2922   // Add a redundant copy of the callee global which will not be legalized, as
2923   // we need direct access to the callee later.
2924   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee);
2925   const GlobalValue *GV = GSD->getGlobal();
2926   Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2927 
2928   if (IsTailCall) {
2929     // Each tail call may have to adjust the stack by a different amount, so
2930     // this information must travel along with the operation for eventual
2931     // consumption by emitEpilogue.
2932     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2933 
2934     Ops.push_back(PhysReturnAddrReg);
2935   }
2936 
2937   // Add argument registers to the end of the list so that they are known live
2938   // into the call.
2939   for (auto &RegToPass : RegsToPass) {
2940     Ops.push_back(DAG.getRegister(RegToPass.first,
2941                                   RegToPass.second.getValueType()));
2942   }
2943 
2944   // Add a register mask operand representing the call-preserved registers.
2945 
2946   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2947   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2948   assert(Mask && "Missing call preserved mask for calling convention");
2949   Ops.push_back(DAG.getRegisterMask(Mask));
2950 
2951   if (InFlag.getNode())
2952     Ops.push_back(InFlag);
2953 
2954   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2955 
2956   // If we're doing a tall call, use a TC_RETURN here rather than an
2957   // actual call instruction.
2958   if (IsTailCall) {
2959     MFI.setHasTailCall();
2960     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2961   }
2962 
2963   // Returns a chain and a flag for retval copy to use.
2964   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2965   Chain = Call.getValue(0);
2966   InFlag = Call.getValue(1);
2967 
2968   uint64_t CalleePopBytes = NumBytes;
2969   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2970                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2971                              InFlag, DL);
2972   if (!Ins.empty())
2973     InFlag = Chain.getValue(1);
2974 
2975   // Handle result values, copying them out of physregs into vregs that we
2976   // return.
2977   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2978                          InVals, IsThisReturn,
2979                          IsThisReturn ? OutVals[0] : SDValue());
2980 }
2981 
2982 Register SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2983                                              const MachineFunction &MF) const {
2984   Register Reg = StringSwitch<Register>(RegName)
2985     .Case("m0", AMDGPU::M0)
2986     .Case("exec", AMDGPU::EXEC)
2987     .Case("exec_lo", AMDGPU::EXEC_LO)
2988     .Case("exec_hi", AMDGPU::EXEC_HI)
2989     .Case("flat_scratch", AMDGPU::FLAT_SCR)
2990     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2991     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2992     .Default(Register());
2993 
2994   if (Reg == AMDGPU::NoRegister) {
2995     report_fatal_error(Twine("invalid register name \""
2996                              + StringRef(RegName)  + "\"."));
2997 
2998   }
2999 
3000   if (!Subtarget->hasFlatScrRegister() &&
3001        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3002     report_fatal_error(Twine("invalid register \""
3003                              + StringRef(RegName)  + "\" for subtarget."));
3004   }
3005 
3006   switch (Reg) {
3007   case AMDGPU::M0:
3008   case AMDGPU::EXEC_LO:
3009   case AMDGPU::EXEC_HI:
3010   case AMDGPU::FLAT_SCR_LO:
3011   case AMDGPU::FLAT_SCR_HI:
3012     if (VT.getSizeInBits() == 32)
3013       return Reg;
3014     break;
3015   case AMDGPU::EXEC:
3016   case AMDGPU::FLAT_SCR:
3017     if (VT.getSizeInBits() == 64)
3018       return Reg;
3019     break;
3020   default:
3021     llvm_unreachable("missing register type checking");
3022   }
3023 
3024   report_fatal_error(Twine("invalid type for register \""
3025                            + StringRef(RegName) + "\"."));
3026 }
3027 
3028 // If kill is not the last instruction, split the block so kill is always a
3029 // proper terminator.
3030 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3031                                                     MachineBasicBlock *BB) const {
3032   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3033 
3034   MachineBasicBlock::iterator SplitPoint(&MI);
3035   ++SplitPoint;
3036 
3037   if (SplitPoint == BB->end()) {
3038     // Don't bother with a new block.
3039     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3040     return BB;
3041   }
3042 
3043   MachineFunction *MF = BB->getParent();
3044   MachineBasicBlock *SplitBB
3045     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3046 
3047   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3048   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3049 
3050   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3051   BB->addSuccessor(SplitBB);
3052 
3053   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3054   return SplitBB;
3055 }
3056 
3057 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3058 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3059 // be the first instruction in the remainder block.
3060 //
3061 /// \returns { LoopBody, Remainder }
3062 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3063 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3064   MachineFunction *MF = MBB.getParent();
3065   MachineBasicBlock::iterator I(&MI);
3066 
3067   // To insert the loop we need to split the block. Move everything after this
3068   // point to a new block, and insert a new empty block between the two.
3069   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3070   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3071   MachineFunction::iterator MBBI(MBB);
3072   ++MBBI;
3073 
3074   MF->insert(MBBI, LoopBB);
3075   MF->insert(MBBI, RemainderBB);
3076 
3077   LoopBB->addSuccessor(LoopBB);
3078   LoopBB->addSuccessor(RemainderBB);
3079 
3080   // Move the rest of the block into a new block.
3081   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3082 
3083   if (InstInLoop) {
3084     auto Next = std::next(I);
3085 
3086     // Move instruction to loop body.
3087     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3088 
3089     // Move the rest of the block.
3090     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3091   } else {
3092     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3093   }
3094 
3095   MBB.addSuccessor(LoopBB);
3096 
3097   return std::make_pair(LoopBB, RemainderBB);
3098 }
3099 
3100 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3101 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3102   MachineBasicBlock *MBB = MI.getParent();
3103   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3104   auto I = MI.getIterator();
3105   auto E = std::next(I);
3106 
3107   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3108     .addImm(0);
3109 
3110   MIBundleBuilder Bundler(*MBB, I, E);
3111   finalizeBundle(*MBB, Bundler.begin());
3112 }
3113 
3114 MachineBasicBlock *
3115 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3116                                          MachineBasicBlock *BB) const {
3117   const DebugLoc &DL = MI.getDebugLoc();
3118 
3119   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3120 
3121   MachineBasicBlock *LoopBB;
3122   MachineBasicBlock *RemainderBB;
3123   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3124 
3125   // Apparently kill flags are only valid if the def is in the same block?
3126   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3127     Src->setIsKill(false);
3128 
3129   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3130 
3131   MachineBasicBlock::iterator I = LoopBB->end();
3132 
3133   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3134     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3135 
3136   // Clear TRAP_STS.MEM_VIOL
3137   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3138     .addImm(0)
3139     .addImm(EncodedReg);
3140 
3141   bundleInstWithWaitcnt(MI);
3142 
3143   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3144 
3145   // Load and check TRAP_STS.MEM_VIOL
3146   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3147     .addImm(EncodedReg);
3148 
3149   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3150   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3151     .addReg(Reg, RegState::Kill)
3152     .addImm(0);
3153   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3154     .addMBB(LoopBB);
3155 
3156   return RemainderBB;
3157 }
3158 
3159 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3160 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3161 // will only do one iteration. In the worst case, this will loop 64 times.
3162 //
3163 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3164 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3165   const SIInstrInfo *TII,
3166   MachineRegisterInfo &MRI,
3167   MachineBasicBlock &OrigBB,
3168   MachineBasicBlock &LoopBB,
3169   const DebugLoc &DL,
3170   const MachineOperand &IdxReg,
3171   unsigned InitReg,
3172   unsigned ResultReg,
3173   unsigned PhiReg,
3174   unsigned InitSaveExecReg,
3175   int Offset,
3176   bool UseGPRIdxMode,
3177   bool IsIndirectSrc) {
3178   MachineFunction *MF = OrigBB.getParent();
3179   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3180   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3181   MachineBasicBlock::iterator I = LoopBB.begin();
3182 
3183   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3184   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3185   Register NewExec = MRI.createVirtualRegister(BoolRC);
3186   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3187   Register CondReg = MRI.createVirtualRegister(BoolRC);
3188 
3189   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3190     .addReg(InitReg)
3191     .addMBB(&OrigBB)
3192     .addReg(ResultReg)
3193     .addMBB(&LoopBB);
3194 
3195   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3196     .addReg(InitSaveExecReg)
3197     .addMBB(&OrigBB)
3198     .addReg(NewExec)
3199     .addMBB(&LoopBB);
3200 
3201   // Read the next variant <- also loop target.
3202   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3203     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3204 
3205   // Compare the just read M0 value to all possible Idx values.
3206   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3207     .addReg(CurrentIdxReg)
3208     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3209 
3210   // Update EXEC, save the original EXEC value to VCC.
3211   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3212                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3213           NewExec)
3214     .addReg(CondReg, RegState::Kill);
3215 
3216   MRI.setSimpleHint(NewExec, CondReg);
3217 
3218   if (UseGPRIdxMode) {
3219     unsigned IdxReg;
3220     if (Offset == 0) {
3221       IdxReg = CurrentIdxReg;
3222     } else {
3223       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3224       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3225         .addReg(CurrentIdxReg, RegState::Kill)
3226         .addImm(Offset);
3227     }
3228     unsigned IdxMode = IsIndirectSrc ?
3229       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3230     MachineInstr *SetOn =
3231       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3232       .addReg(IdxReg, RegState::Kill)
3233       .addImm(IdxMode);
3234     SetOn->getOperand(3).setIsUndef();
3235   } else {
3236     // Move index from VCC into M0
3237     if (Offset == 0) {
3238       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3239         .addReg(CurrentIdxReg, RegState::Kill);
3240     } else {
3241       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3242         .addReg(CurrentIdxReg, RegState::Kill)
3243         .addImm(Offset);
3244     }
3245   }
3246 
3247   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3248   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3249   MachineInstr *InsertPt =
3250     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3251                                                   : AMDGPU::S_XOR_B64_term), Exec)
3252       .addReg(Exec)
3253       .addReg(NewExec);
3254 
3255   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3256   // s_cbranch_scc0?
3257 
3258   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3259   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3260     .addMBB(&LoopBB);
3261 
3262   return InsertPt->getIterator();
3263 }
3264 
3265 // This has slightly sub-optimal regalloc when the source vector is killed by
3266 // the read. The register allocator does not understand that the kill is
3267 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3268 // subregister from it, using 1 more VGPR than necessary. This was saved when
3269 // this was expanded after register allocation.
3270 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3271                                                   MachineBasicBlock &MBB,
3272                                                   MachineInstr &MI,
3273                                                   unsigned InitResultReg,
3274                                                   unsigned PhiReg,
3275                                                   int Offset,
3276                                                   bool UseGPRIdxMode,
3277                                                   bool IsIndirectSrc) {
3278   MachineFunction *MF = MBB.getParent();
3279   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3280   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3281   MachineRegisterInfo &MRI = MF->getRegInfo();
3282   const DebugLoc &DL = MI.getDebugLoc();
3283   MachineBasicBlock::iterator I(&MI);
3284 
3285   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3286   Register DstReg = MI.getOperand(0).getReg();
3287   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3288   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3289   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3290   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3291 
3292   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3293 
3294   // Save the EXEC mask
3295   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3296     .addReg(Exec);
3297 
3298   MachineBasicBlock *LoopBB;
3299   MachineBasicBlock *RemainderBB;
3300   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3301 
3302   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3303 
3304   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3305                                       InitResultReg, DstReg, PhiReg, TmpExec,
3306                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3307 
3308   MachineBasicBlock::iterator First = RemainderBB->begin();
3309   BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec)
3310     .addReg(SaveExec);
3311 
3312   return InsPt;
3313 }
3314 
3315 // Returns subreg index, offset
3316 static std::pair<unsigned, int>
3317 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3318                             const TargetRegisterClass *SuperRC,
3319                             unsigned VecReg,
3320                             int Offset) {
3321   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3322 
3323   // Skip out of bounds offsets, or else we would end up using an undefined
3324   // register.
3325   if (Offset >= NumElts || Offset < 0)
3326     return std::make_pair(AMDGPU::sub0, Offset);
3327 
3328   return std::make_pair(AMDGPU::sub0 + Offset, 0);
3329 }
3330 
3331 // Return true if the index is an SGPR and was set.
3332 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3333                                  MachineRegisterInfo &MRI,
3334                                  MachineInstr &MI,
3335                                  int Offset,
3336                                  bool UseGPRIdxMode,
3337                                  bool IsIndirectSrc) {
3338   MachineBasicBlock *MBB = MI.getParent();
3339   const DebugLoc &DL = MI.getDebugLoc();
3340   MachineBasicBlock::iterator I(&MI);
3341 
3342   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3343   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3344 
3345   assert(Idx->getReg() != AMDGPU::NoRegister);
3346 
3347   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3348     return false;
3349 
3350   if (UseGPRIdxMode) {
3351     unsigned IdxMode = IsIndirectSrc ?
3352       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3353     if (Offset == 0) {
3354       MachineInstr *SetOn =
3355           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3356               .add(*Idx)
3357               .addImm(IdxMode);
3358 
3359       SetOn->getOperand(3).setIsUndef();
3360     } else {
3361       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3362       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3363           .add(*Idx)
3364           .addImm(Offset);
3365       MachineInstr *SetOn =
3366         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3367         .addReg(Tmp, RegState::Kill)
3368         .addImm(IdxMode);
3369 
3370       SetOn->getOperand(3).setIsUndef();
3371     }
3372 
3373     return true;
3374   }
3375 
3376   if (Offset == 0) {
3377     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3378       .add(*Idx);
3379   } else {
3380     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3381       .add(*Idx)
3382       .addImm(Offset);
3383   }
3384 
3385   return true;
3386 }
3387 
3388 // Control flow needs to be inserted if indexing with a VGPR.
3389 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3390                                           MachineBasicBlock &MBB,
3391                                           const GCNSubtarget &ST) {
3392   const SIInstrInfo *TII = ST.getInstrInfo();
3393   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3394   MachineFunction *MF = MBB.getParent();
3395   MachineRegisterInfo &MRI = MF->getRegInfo();
3396 
3397   Register Dst = MI.getOperand(0).getReg();
3398   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3399   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3400 
3401   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3402 
3403   unsigned SubReg;
3404   std::tie(SubReg, Offset)
3405     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3406 
3407   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3408 
3409   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3410     MachineBasicBlock::iterator I(&MI);
3411     const DebugLoc &DL = MI.getDebugLoc();
3412 
3413     if (UseGPRIdxMode) {
3414       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3415       // to avoid interfering with other uses, so probably requires a new
3416       // optimization pass.
3417       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3418         .addReg(SrcReg, RegState::Undef, SubReg)
3419         .addReg(SrcReg, RegState::Implicit)
3420         .addReg(AMDGPU::M0, RegState::Implicit);
3421       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3422     } else {
3423       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3424         .addReg(SrcReg, RegState::Undef, SubReg)
3425         .addReg(SrcReg, RegState::Implicit);
3426     }
3427 
3428     MI.eraseFromParent();
3429 
3430     return &MBB;
3431   }
3432 
3433   const DebugLoc &DL = MI.getDebugLoc();
3434   MachineBasicBlock::iterator I(&MI);
3435 
3436   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3437   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3438 
3439   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3440 
3441   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3442                               Offset, UseGPRIdxMode, true);
3443   MachineBasicBlock *LoopBB = InsPt->getParent();
3444 
3445   if (UseGPRIdxMode) {
3446     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3447       .addReg(SrcReg, RegState::Undef, SubReg)
3448       .addReg(SrcReg, RegState::Implicit)
3449       .addReg(AMDGPU::M0, RegState::Implicit);
3450     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3451   } else {
3452     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3453       .addReg(SrcReg, RegState::Undef, SubReg)
3454       .addReg(SrcReg, RegState::Implicit);
3455   }
3456 
3457   MI.eraseFromParent();
3458 
3459   return LoopBB;
3460 }
3461 
3462 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3463                                  const TargetRegisterClass *VecRC) {
3464   switch (TRI.getRegSizeInBits(*VecRC)) {
3465   case 32: // 4 bytes
3466     return AMDGPU::V_MOVRELD_B32_V1;
3467   case 64: // 8 bytes
3468     return AMDGPU::V_MOVRELD_B32_V2;
3469   case 128: // 16 bytes
3470     return AMDGPU::V_MOVRELD_B32_V4;
3471   case 256: // 32 bytes
3472     return AMDGPU::V_MOVRELD_B32_V8;
3473   case 512: // 64 bytes
3474     return AMDGPU::V_MOVRELD_B32_V16;
3475   default:
3476     llvm_unreachable("unsupported size for MOVRELD pseudos");
3477   }
3478 }
3479 
3480 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3481                                           MachineBasicBlock &MBB,
3482                                           const GCNSubtarget &ST) {
3483   const SIInstrInfo *TII = ST.getInstrInfo();
3484   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3485   MachineFunction *MF = MBB.getParent();
3486   MachineRegisterInfo &MRI = MF->getRegInfo();
3487 
3488   Register Dst = MI.getOperand(0).getReg();
3489   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3490   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3491   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3492   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3493   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3494 
3495   // This can be an immediate, but will be folded later.
3496   assert(Val->getReg());
3497 
3498   unsigned SubReg;
3499   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3500                                                          SrcVec->getReg(),
3501                                                          Offset);
3502   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3503 
3504   if (Idx->getReg() == AMDGPU::NoRegister) {
3505     MachineBasicBlock::iterator I(&MI);
3506     const DebugLoc &DL = MI.getDebugLoc();
3507 
3508     assert(Offset == 0);
3509 
3510     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3511         .add(*SrcVec)
3512         .add(*Val)
3513         .addImm(SubReg);
3514 
3515     MI.eraseFromParent();
3516     return &MBB;
3517   }
3518 
3519   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3520     MachineBasicBlock::iterator I(&MI);
3521     const DebugLoc &DL = MI.getDebugLoc();
3522 
3523     if (UseGPRIdxMode) {
3524       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3525           .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3526           .add(*Val)
3527           .addReg(Dst, RegState::ImplicitDefine)
3528           .addReg(SrcVec->getReg(), RegState::Implicit)
3529           .addReg(AMDGPU::M0, RegState::Implicit);
3530 
3531       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3532     } else {
3533       const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3534 
3535       BuildMI(MBB, I, DL, MovRelDesc)
3536           .addReg(Dst, RegState::Define)
3537           .addReg(SrcVec->getReg())
3538           .add(*Val)
3539           .addImm(SubReg - AMDGPU::sub0);
3540     }
3541 
3542     MI.eraseFromParent();
3543     return &MBB;
3544   }
3545 
3546   if (Val->isReg())
3547     MRI.clearKillFlags(Val->getReg());
3548 
3549   const DebugLoc &DL = MI.getDebugLoc();
3550 
3551   Register PhiReg = MRI.createVirtualRegister(VecRC);
3552 
3553   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3554                               Offset, UseGPRIdxMode, false);
3555   MachineBasicBlock *LoopBB = InsPt->getParent();
3556 
3557   if (UseGPRIdxMode) {
3558     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3559         .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3560         .add(*Val)                               // src0
3561         .addReg(Dst, RegState::ImplicitDefine)
3562         .addReg(PhiReg, RegState::Implicit)
3563         .addReg(AMDGPU::M0, RegState::Implicit);
3564     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3565   } else {
3566     const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3567 
3568     BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3569         .addReg(Dst, RegState::Define)
3570         .addReg(PhiReg)
3571         .add(*Val)
3572         .addImm(SubReg - AMDGPU::sub0);
3573   }
3574 
3575   MI.eraseFromParent();
3576 
3577   return LoopBB;
3578 }
3579 
3580 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3581   MachineInstr &MI, MachineBasicBlock *BB) const {
3582 
3583   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3584   MachineFunction *MF = BB->getParent();
3585   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3586 
3587   if (TII->isMIMG(MI)) {
3588     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3589       report_fatal_error("missing mem operand from MIMG instruction");
3590     }
3591     // Add a memoperand for mimg instructions so that they aren't assumed to
3592     // be ordered memory instuctions.
3593 
3594     return BB;
3595   }
3596 
3597   switch (MI.getOpcode()) {
3598   case AMDGPU::S_ADD_U64_PSEUDO:
3599   case AMDGPU::S_SUB_U64_PSEUDO: {
3600     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3601     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3602     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3603     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3604     const DebugLoc &DL = MI.getDebugLoc();
3605 
3606     MachineOperand &Dest = MI.getOperand(0);
3607     MachineOperand &Src0 = MI.getOperand(1);
3608     MachineOperand &Src1 = MI.getOperand(2);
3609 
3610     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3611     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3612 
3613     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3614      Src0, BoolRC, AMDGPU::sub0,
3615      &AMDGPU::SReg_32RegClass);
3616     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3617       Src0, BoolRC, AMDGPU::sub1,
3618       &AMDGPU::SReg_32RegClass);
3619 
3620     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3621       Src1, BoolRC, AMDGPU::sub0,
3622       &AMDGPU::SReg_32RegClass);
3623     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3624       Src1, BoolRC, AMDGPU::sub1,
3625       &AMDGPU::SReg_32RegClass);
3626 
3627     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3628 
3629     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3630     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3631     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3632       .add(Src0Sub0)
3633       .add(Src1Sub0);
3634     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3635       .add(Src0Sub1)
3636       .add(Src1Sub1);
3637     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3638       .addReg(DestSub0)
3639       .addImm(AMDGPU::sub0)
3640       .addReg(DestSub1)
3641       .addImm(AMDGPU::sub1);
3642     MI.eraseFromParent();
3643     return BB;
3644   }
3645   case AMDGPU::SI_INIT_M0: {
3646     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3647             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3648         .add(MI.getOperand(0));
3649     MI.eraseFromParent();
3650     return BB;
3651   }
3652   case AMDGPU::SI_INIT_EXEC:
3653     // This should be before all vector instructions.
3654     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3655             AMDGPU::EXEC)
3656         .addImm(MI.getOperand(0).getImm());
3657     MI.eraseFromParent();
3658     return BB;
3659 
3660   case AMDGPU::SI_INIT_EXEC_LO:
3661     // This should be before all vector instructions.
3662     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3663             AMDGPU::EXEC_LO)
3664         .addImm(MI.getOperand(0).getImm());
3665     MI.eraseFromParent();
3666     return BB;
3667 
3668   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3669     // Extract the thread count from an SGPR input and set EXEC accordingly.
3670     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3671     //
3672     // S_BFE_U32 count, input, {shift, 7}
3673     // S_BFM_B64 exec, count, 0
3674     // S_CMP_EQ_U32 count, 64
3675     // S_CMOV_B64 exec, -1
3676     MachineInstr *FirstMI = &*BB->begin();
3677     MachineRegisterInfo &MRI = MF->getRegInfo();
3678     Register InputReg = MI.getOperand(0).getReg();
3679     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3680     bool Found = false;
3681 
3682     // Move the COPY of the input reg to the beginning, so that we can use it.
3683     for (auto I = BB->begin(); I != &MI; I++) {
3684       if (I->getOpcode() != TargetOpcode::COPY ||
3685           I->getOperand(0).getReg() != InputReg)
3686         continue;
3687 
3688       if (I == FirstMI) {
3689         FirstMI = &*++BB->begin();
3690       } else {
3691         I->removeFromParent();
3692         BB->insert(FirstMI, &*I);
3693       }
3694       Found = true;
3695       break;
3696     }
3697     assert(Found);
3698     (void)Found;
3699 
3700     // This should be before all vector instructions.
3701     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3702     bool isWave32 = getSubtarget()->isWave32();
3703     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3704     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3705         .addReg(InputReg)
3706         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3707     BuildMI(*BB, FirstMI, DebugLoc(),
3708             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3709             Exec)
3710         .addReg(CountReg)
3711         .addImm(0);
3712     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3713         .addReg(CountReg, RegState::Kill)
3714         .addImm(getSubtarget()->getWavefrontSize());
3715     BuildMI(*BB, FirstMI, DebugLoc(),
3716             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3717             Exec)
3718         .addImm(-1);
3719     MI.eraseFromParent();
3720     return BB;
3721   }
3722 
3723   case AMDGPU::GET_GROUPSTATICSIZE: {
3724     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3725            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3726     DebugLoc DL = MI.getDebugLoc();
3727     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3728         .add(MI.getOperand(0))
3729         .addImm(MFI->getLDSSize());
3730     MI.eraseFromParent();
3731     return BB;
3732   }
3733   case AMDGPU::SI_INDIRECT_SRC_V1:
3734   case AMDGPU::SI_INDIRECT_SRC_V2:
3735   case AMDGPU::SI_INDIRECT_SRC_V4:
3736   case AMDGPU::SI_INDIRECT_SRC_V8:
3737   case AMDGPU::SI_INDIRECT_SRC_V16:
3738     return emitIndirectSrc(MI, *BB, *getSubtarget());
3739   case AMDGPU::SI_INDIRECT_DST_V1:
3740   case AMDGPU::SI_INDIRECT_DST_V2:
3741   case AMDGPU::SI_INDIRECT_DST_V4:
3742   case AMDGPU::SI_INDIRECT_DST_V8:
3743   case AMDGPU::SI_INDIRECT_DST_V16:
3744     return emitIndirectDst(MI, *BB, *getSubtarget());
3745   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3746   case AMDGPU::SI_KILL_I1_PSEUDO:
3747     return splitKillBlock(MI, BB);
3748   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3749     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3750     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3751     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3752 
3753     Register Dst = MI.getOperand(0).getReg();
3754     Register Src0 = MI.getOperand(1).getReg();
3755     Register Src1 = MI.getOperand(2).getReg();
3756     const DebugLoc &DL = MI.getDebugLoc();
3757     Register SrcCond = MI.getOperand(3).getReg();
3758 
3759     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3760     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3761     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3762     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3763 
3764     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3765       .addReg(SrcCond);
3766     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3767       .addImm(0)
3768       .addReg(Src0, 0, AMDGPU::sub0)
3769       .addImm(0)
3770       .addReg(Src1, 0, AMDGPU::sub0)
3771       .addReg(SrcCondCopy);
3772     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3773       .addImm(0)
3774       .addReg(Src0, 0, AMDGPU::sub1)
3775       .addImm(0)
3776       .addReg(Src1, 0, AMDGPU::sub1)
3777       .addReg(SrcCondCopy);
3778 
3779     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3780       .addReg(DstLo)
3781       .addImm(AMDGPU::sub0)
3782       .addReg(DstHi)
3783       .addImm(AMDGPU::sub1);
3784     MI.eraseFromParent();
3785     return BB;
3786   }
3787   case AMDGPU::SI_BR_UNDEF: {
3788     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3789     const DebugLoc &DL = MI.getDebugLoc();
3790     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3791                            .add(MI.getOperand(0));
3792     Br->getOperand(1).setIsUndef(true); // read undef SCC
3793     MI.eraseFromParent();
3794     return BB;
3795   }
3796   case AMDGPU::ADJCALLSTACKUP:
3797   case AMDGPU::ADJCALLSTACKDOWN: {
3798     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3799     MachineInstrBuilder MIB(*MF, &MI);
3800 
3801     // Add an implicit use of the frame offset reg to prevent the restore copy
3802     // inserted after the call from being reorderd after stack operations in the
3803     // the caller's frame.
3804     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3805         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3806         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3807     return BB;
3808   }
3809   case AMDGPU::SI_CALL_ISEL: {
3810     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3811     const DebugLoc &DL = MI.getDebugLoc();
3812 
3813     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3814 
3815     MachineInstrBuilder MIB;
3816     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3817 
3818     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3819       MIB.add(MI.getOperand(I));
3820 
3821     MIB.cloneMemRefs(MI);
3822     MI.eraseFromParent();
3823     return BB;
3824   }
3825   case AMDGPU::V_ADD_I32_e32:
3826   case AMDGPU::V_SUB_I32_e32:
3827   case AMDGPU::V_SUBREV_I32_e32: {
3828     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3829     const DebugLoc &DL = MI.getDebugLoc();
3830     unsigned Opc = MI.getOpcode();
3831 
3832     bool NeedClampOperand = false;
3833     if (TII->pseudoToMCOpcode(Opc) == -1) {
3834       Opc = AMDGPU::getVOPe64(Opc);
3835       NeedClampOperand = true;
3836     }
3837 
3838     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3839     if (TII->isVOP3(*I)) {
3840       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3841       const SIRegisterInfo *TRI = ST.getRegisterInfo();
3842       I.addReg(TRI->getVCC(), RegState::Define);
3843     }
3844     I.add(MI.getOperand(1))
3845      .add(MI.getOperand(2));
3846     if (NeedClampOperand)
3847       I.addImm(0); // clamp bit for e64 encoding
3848 
3849     TII->legalizeOperands(*I);
3850 
3851     MI.eraseFromParent();
3852     return BB;
3853   }
3854   case AMDGPU::DS_GWS_INIT:
3855   case AMDGPU::DS_GWS_SEMA_V:
3856   case AMDGPU::DS_GWS_SEMA_BR:
3857   case AMDGPU::DS_GWS_SEMA_P:
3858   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
3859   case AMDGPU::DS_GWS_BARRIER:
3860     // A s_waitcnt 0 is required to be the instruction immediately following.
3861     if (getSubtarget()->hasGWSAutoReplay()) {
3862       bundleInstWithWaitcnt(MI);
3863       return BB;
3864     }
3865 
3866     return emitGWSMemViolTestLoop(MI, BB);
3867   default:
3868     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3869   }
3870 }
3871 
3872 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3873   return isTypeLegal(VT.getScalarType());
3874 }
3875 
3876 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3877   // This currently forces unfolding various combinations of fsub into fma with
3878   // free fneg'd operands. As long as we have fast FMA (controlled by
3879   // isFMAFasterThanFMulAndFAdd), we should perform these.
3880 
3881   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3882   // most of these combines appear to be cycle neutral but save on instruction
3883   // count / code size.
3884   return true;
3885 }
3886 
3887 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3888                                          EVT VT) const {
3889   if (!VT.isVector()) {
3890     return MVT::i1;
3891   }
3892   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3893 }
3894 
3895 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3896   // TODO: Should i16 be used always if legal? For now it would force VALU
3897   // shifts.
3898   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3899 }
3900 
3901 // Answering this is somewhat tricky and depends on the specific device which
3902 // have different rates for fma or all f64 operations.
3903 //
3904 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3905 // regardless of which device (although the number of cycles differs between
3906 // devices), so it is always profitable for f64.
3907 //
3908 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3909 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3910 // which we can always do even without fused FP ops since it returns the same
3911 // result as the separate operations and since it is always full
3912 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3913 // however does not support denormals, so we do report fma as faster if we have
3914 // a fast fma device and require denormals.
3915 //
3916 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3917   VT = VT.getScalarType();
3918 
3919   switch (VT.getSimpleVT().SimpleTy) {
3920   case MVT::f32: {
3921     // This is as fast on some subtargets. However, we always have full rate f32
3922     // mad available which returns the same result as the separate operations
3923     // which we should prefer over fma. We can't use this if we want to support
3924     // denormals, so only report this in these cases.
3925     if (Subtarget->hasFP32Denormals())
3926       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3927 
3928     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3929     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3930   }
3931   case MVT::f64:
3932     return true;
3933   case MVT::f16:
3934     return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3935   default:
3936     break;
3937   }
3938 
3939   return false;
3940 }
3941 
3942 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG,
3943                                               const SDNode *N) const {
3944   // TODO: Check future ftz flag
3945   // v_mad_f32/v_mac_f32 do not support denormals.
3946   EVT VT = N->getValueType(0);
3947   if (VT == MVT::f32)
3948     return !Subtarget->hasFP32Denormals();
3949   if (VT == MVT::f16)
3950     return !Subtarget->hasFP16Denormals() && Subtarget->hasMadF16();
3951 
3952   return false;
3953 }
3954 
3955 //===----------------------------------------------------------------------===//
3956 // Custom DAG Lowering Operations
3957 //===----------------------------------------------------------------------===//
3958 
3959 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3960 // wider vector type is legal.
3961 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3962                                              SelectionDAG &DAG) const {
3963   unsigned Opc = Op.getOpcode();
3964   EVT VT = Op.getValueType();
3965   assert(VT == MVT::v4f16);
3966 
3967   SDValue Lo, Hi;
3968   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3969 
3970   SDLoc SL(Op);
3971   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3972                              Op->getFlags());
3973   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3974                              Op->getFlags());
3975 
3976   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3977 }
3978 
3979 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3980 // wider vector type is legal.
3981 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3982                                               SelectionDAG &DAG) const {
3983   unsigned Opc = Op.getOpcode();
3984   EVT VT = Op.getValueType();
3985   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3986 
3987   SDValue Lo0, Hi0;
3988   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3989   SDValue Lo1, Hi1;
3990   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3991 
3992   SDLoc SL(Op);
3993 
3994   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3995                              Op->getFlags());
3996   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3997                              Op->getFlags());
3998 
3999   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4000 }
4001 
4002 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4003                                               SelectionDAG &DAG) const {
4004   unsigned Opc = Op.getOpcode();
4005   EVT VT = Op.getValueType();
4006   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4007 
4008   SDValue Lo0, Hi0;
4009   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4010   SDValue Lo1, Hi1;
4011   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4012   SDValue Lo2, Hi2;
4013   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4014 
4015   SDLoc SL(Op);
4016 
4017   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4018                              Op->getFlags());
4019   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4020                              Op->getFlags());
4021 
4022   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4023 }
4024 
4025 
4026 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4027   switch (Op.getOpcode()) {
4028   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4029   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4030   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4031   case ISD::LOAD: {
4032     SDValue Result = LowerLOAD(Op, DAG);
4033     assert((!Result.getNode() ||
4034             Result.getNode()->getNumValues() == 2) &&
4035            "Load should return a value and a chain");
4036     return Result;
4037   }
4038 
4039   case ISD::FSIN:
4040   case ISD::FCOS:
4041     return LowerTrig(Op, DAG);
4042   case ISD::SELECT: return LowerSELECT(Op, DAG);
4043   case ISD::FDIV: return LowerFDIV(Op, DAG);
4044   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4045   case ISD::STORE: return LowerSTORE(Op, DAG);
4046   case ISD::GlobalAddress: {
4047     MachineFunction &MF = DAG.getMachineFunction();
4048     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4049     return LowerGlobalAddress(MFI, Op, DAG);
4050   }
4051   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4052   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4053   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4054   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4055   case ISD::INSERT_SUBVECTOR:
4056     return lowerINSERT_SUBVECTOR(Op, DAG);
4057   case ISD::INSERT_VECTOR_ELT:
4058     return lowerINSERT_VECTOR_ELT(Op, DAG);
4059   case ISD::EXTRACT_VECTOR_ELT:
4060     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4061   case ISD::VECTOR_SHUFFLE:
4062     return lowerVECTOR_SHUFFLE(Op, DAG);
4063   case ISD::BUILD_VECTOR:
4064     return lowerBUILD_VECTOR(Op, DAG);
4065   case ISD::FP_ROUND:
4066     return lowerFP_ROUND(Op, DAG);
4067   case ISD::TRAP:
4068     return lowerTRAP(Op, DAG);
4069   case ISD::DEBUGTRAP:
4070     return lowerDEBUGTRAP(Op, DAG);
4071   case ISD::FABS:
4072   case ISD::FNEG:
4073   case ISD::FCANONICALIZE:
4074     return splitUnaryVectorOp(Op, DAG);
4075   case ISD::FMINNUM:
4076   case ISD::FMAXNUM:
4077     return lowerFMINNUM_FMAXNUM(Op, DAG);
4078   case ISD::FMA:
4079     return splitTernaryVectorOp(Op, DAG);
4080   case ISD::SHL:
4081   case ISD::SRA:
4082   case ISD::SRL:
4083   case ISD::ADD:
4084   case ISD::SUB:
4085   case ISD::MUL:
4086   case ISD::SMIN:
4087   case ISD::SMAX:
4088   case ISD::UMIN:
4089   case ISD::UMAX:
4090   case ISD::FADD:
4091   case ISD::FMUL:
4092   case ISD::FMINNUM_IEEE:
4093   case ISD::FMAXNUM_IEEE:
4094     return splitBinaryVectorOp(Op, DAG);
4095   }
4096   return SDValue();
4097 }
4098 
4099 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4100                                        const SDLoc &DL,
4101                                        SelectionDAG &DAG, bool Unpacked) {
4102   if (!LoadVT.isVector())
4103     return Result;
4104 
4105   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4106     // Truncate to v2i16/v4i16.
4107     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4108 
4109     // Workaround legalizer not scalarizing truncate after vector op
4110     // legalization byt not creating intermediate vector trunc.
4111     SmallVector<SDValue, 4> Elts;
4112     DAG.ExtractVectorElements(Result, Elts);
4113     for (SDValue &Elt : Elts)
4114       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4115 
4116     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4117 
4118     // Bitcast to original type (v2f16/v4f16).
4119     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4120   }
4121 
4122   // Cast back to the original packed type.
4123   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4124 }
4125 
4126 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4127                                               MemSDNode *M,
4128                                               SelectionDAG &DAG,
4129                                               ArrayRef<SDValue> Ops,
4130                                               bool IsIntrinsic) const {
4131   SDLoc DL(M);
4132 
4133   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4134   EVT LoadVT = M->getValueType(0);
4135 
4136   EVT EquivLoadVT = LoadVT;
4137   if (Unpacked && LoadVT.isVector()) {
4138     EquivLoadVT = LoadVT.isVector() ?
4139       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4140                        LoadVT.getVectorNumElements()) : LoadVT;
4141   }
4142 
4143   // Change from v4f16/v2f16 to EquivLoadVT.
4144   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4145 
4146   SDValue Load
4147     = DAG.getMemIntrinsicNode(
4148       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4149       VTList, Ops, M->getMemoryVT(),
4150       M->getMemOperand());
4151   if (!Unpacked) // Just adjusted the opcode.
4152     return Load;
4153 
4154   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4155 
4156   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4157 }
4158 
4159 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4160                                              SelectionDAG &DAG,
4161                                              ArrayRef<SDValue> Ops) const {
4162   SDLoc DL(M);
4163   EVT LoadVT = M->getValueType(0);
4164   EVT EltType = LoadVT.getScalarType();
4165   EVT IntVT = LoadVT.changeTypeToInteger();
4166 
4167   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4168 
4169   unsigned Opc =
4170       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4171 
4172   if (IsD16) {
4173     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4174   }
4175 
4176   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4177   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4178     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4179 
4180   if (isTypeLegal(LoadVT)) {
4181     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4182                                M->getMemOperand(), DAG);
4183   }
4184 
4185   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4186   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4187   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4188                                         M->getMemOperand(), DAG);
4189   return DAG.getMergeValues(
4190       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4191       DL);
4192 }
4193 
4194 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4195                                   SDNode *N, SelectionDAG &DAG) {
4196   EVT VT = N->getValueType(0);
4197   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4198   int CondCode = CD->getSExtValue();
4199   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4200       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4201     return DAG.getUNDEF(VT);
4202 
4203   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4204 
4205   SDValue LHS = N->getOperand(1);
4206   SDValue RHS = N->getOperand(2);
4207 
4208   SDLoc DL(N);
4209 
4210   EVT CmpVT = LHS.getValueType();
4211   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4212     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4213       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4214     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4215     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4216   }
4217 
4218   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4219 
4220   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4221   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4222 
4223   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4224                               DAG.getCondCode(CCOpcode));
4225   if (VT.bitsEq(CCVT))
4226     return SetCC;
4227   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4228 }
4229 
4230 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4231                                   SDNode *N, SelectionDAG &DAG) {
4232   EVT VT = N->getValueType(0);
4233   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4234 
4235   int CondCode = CD->getSExtValue();
4236   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4237       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4238     return DAG.getUNDEF(VT);
4239   }
4240 
4241   SDValue Src0 = N->getOperand(1);
4242   SDValue Src1 = N->getOperand(2);
4243   EVT CmpVT = Src0.getValueType();
4244   SDLoc SL(N);
4245 
4246   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4247     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4248     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4249   }
4250 
4251   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4252   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4253   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4254   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4255   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4256                               Src1, DAG.getCondCode(CCOpcode));
4257   if (VT.bitsEq(CCVT))
4258     return SetCC;
4259   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4260 }
4261 
4262 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4263                                           SmallVectorImpl<SDValue> &Results,
4264                                           SelectionDAG &DAG) const {
4265   switch (N->getOpcode()) {
4266   case ISD::INSERT_VECTOR_ELT: {
4267     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4268       Results.push_back(Res);
4269     return;
4270   }
4271   case ISD::EXTRACT_VECTOR_ELT: {
4272     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4273       Results.push_back(Res);
4274     return;
4275   }
4276   case ISD::INTRINSIC_WO_CHAIN: {
4277     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4278     switch (IID) {
4279     case Intrinsic::amdgcn_cvt_pkrtz: {
4280       SDValue Src0 = N->getOperand(1);
4281       SDValue Src1 = N->getOperand(2);
4282       SDLoc SL(N);
4283       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4284                                 Src0, Src1);
4285       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4286       return;
4287     }
4288     case Intrinsic::amdgcn_cvt_pknorm_i16:
4289     case Intrinsic::amdgcn_cvt_pknorm_u16:
4290     case Intrinsic::amdgcn_cvt_pk_i16:
4291     case Intrinsic::amdgcn_cvt_pk_u16: {
4292       SDValue Src0 = N->getOperand(1);
4293       SDValue Src1 = N->getOperand(2);
4294       SDLoc SL(N);
4295       unsigned Opcode;
4296 
4297       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4298         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4299       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4300         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4301       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4302         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4303       else
4304         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4305 
4306       EVT VT = N->getValueType(0);
4307       if (isTypeLegal(VT))
4308         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4309       else {
4310         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4311         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4312       }
4313       return;
4314     }
4315     }
4316     break;
4317   }
4318   case ISD::INTRINSIC_W_CHAIN: {
4319     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4320       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4321         // FIXME: Hacky
4322         Results.push_back(Res.getOperand(0));
4323         Results.push_back(Res.getOperand(1));
4324       } else {
4325         Results.push_back(Res);
4326         Results.push_back(Res.getValue(1));
4327       }
4328       return;
4329     }
4330 
4331     break;
4332   }
4333   case ISD::SELECT: {
4334     SDLoc SL(N);
4335     EVT VT = N->getValueType(0);
4336     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4337     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4338     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4339 
4340     EVT SelectVT = NewVT;
4341     if (NewVT.bitsLT(MVT::i32)) {
4342       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4343       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4344       SelectVT = MVT::i32;
4345     }
4346 
4347     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4348                                     N->getOperand(0), LHS, RHS);
4349 
4350     if (NewVT != SelectVT)
4351       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4352     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4353     return;
4354   }
4355   case ISD::FNEG: {
4356     if (N->getValueType(0) != MVT::v2f16)
4357       break;
4358 
4359     SDLoc SL(N);
4360     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4361 
4362     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4363                              BC,
4364                              DAG.getConstant(0x80008000, SL, MVT::i32));
4365     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4366     return;
4367   }
4368   case ISD::FABS: {
4369     if (N->getValueType(0) != MVT::v2f16)
4370       break;
4371 
4372     SDLoc SL(N);
4373     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4374 
4375     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4376                              BC,
4377                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4378     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4379     return;
4380   }
4381   default:
4382     break;
4383   }
4384 }
4385 
4386 /// Helper function for LowerBRCOND
4387 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4388 
4389   SDNode *Parent = Value.getNode();
4390   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4391        I != E; ++I) {
4392 
4393     if (I.getUse().get() != Value)
4394       continue;
4395 
4396     if (I->getOpcode() == Opcode)
4397       return *I;
4398   }
4399   return nullptr;
4400 }
4401 
4402 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4403   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4404     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4405     case Intrinsic::amdgcn_if:
4406       return AMDGPUISD::IF;
4407     case Intrinsic::amdgcn_else:
4408       return AMDGPUISD::ELSE;
4409     case Intrinsic::amdgcn_loop:
4410       return AMDGPUISD::LOOP;
4411     case Intrinsic::amdgcn_end_cf:
4412       llvm_unreachable("should not occur");
4413     default:
4414       return 0;
4415     }
4416   }
4417 
4418   // break, if_break, else_break are all only used as inputs to loop, not
4419   // directly as branch conditions.
4420   return 0;
4421 }
4422 
4423 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4424   const Triple &TT = getTargetMachine().getTargetTriple();
4425   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4426           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4427          AMDGPU::shouldEmitConstantsToTextSection(TT);
4428 }
4429 
4430 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4431   // FIXME: Either avoid relying on address space here or change the default
4432   // address space for functions to avoid the explicit check.
4433   return (GV->getValueType()->isFunctionTy() ||
4434           GV->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4435           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4436           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4437          !shouldEmitFixup(GV) &&
4438          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4439 }
4440 
4441 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4442   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4443 }
4444 
4445 /// This transforms the control flow intrinsics to get the branch destination as
4446 /// last parameter, also switches branch target with BR if the need arise
4447 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4448                                       SelectionDAG &DAG) const {
4449   SDLoc DL(BRCOND);
4450 
4451   SDNode *Intr = BRCOND.getOperand(1).getNode();
4452   SDValue Target = BRCOND.getOperand(2);
4453   SDNode *BR = nullptr;
4454   SDNode *SetCC = nullptr;
4455 
4456   if (Intr->getOpcode() == ISD::SETCC) {
4457     // As long as we negate the condition everything is fine
4458     SetCC = Intr;
4459     Intr = SetCC->getOperand(0).getNode();
4460 
4461   } else {
4462     // Get the target from BR if we don't negate the condition
4463     BR = findUser(BRCOND, ISD::BR);
4464     Target = BR->getOperand(1);
4465   }
4466 
4467   // FIXME: This changes the types of the intrinsics instead of introducing new
4468   // nodes with the correct types.
4469   // e.g. llvm.amdgcn.loop
4470 
4471   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4472   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4473 
4474   unsigned CFNode = isCFIntrinsic(Intr);
4475   if (CFNode == 0) {
4476     // This is a uniform branch so we don't need to legalize.
4477     return BRCOND;
4478   }
4479 
4480   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4481                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4482 
4483   assert(!SetCC ||
4484         (SetCC->getConstantOperandVal(1) == 1 &&
4485          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4486                                                              ISD::SETNE));
4487 
4488   // operands of the new intrinsic call
4489   SmallVector<SDValue, 4> Ops;
4490   if (HaveChain)
4491     Ops.push_back(BRCOND.getOperand(0));
4492 
4493   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4494   Ops.push_back(Target);
4495 
4496   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4497 
4498   // build the new intrinsic call
4499   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4500 
4501   if (!HaveChain) {
4502     SDValue Ops[] =  {
4503       SDValue(Result, 0),
4504       BRCOND.getOperand(0)
4505     };
4506 
4507     Result = DAG.getMergeValues(Ops, DL).getNode();
4508   }
4509 
4510   if (BR) {
4511     // Give the branch instruction our target
4512     SDValue Ops[] = {
4513       BR->getOperand(0),
4514       BRCOND.getOperand(2)
4515     };
4516     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4517     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4518     BR = NewBR.getNode();
4519   }
4520 
4521   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4522 
4523   // Copy the intrinsic results to registers
4524   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4525     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4526     if (!CopyToReg)
4527       continue;
4528 
4529     Chain = DAG.getCopyToReg(
4530       Chain, DL,
4531       CopyToReg->getOperand(1),
4532       SDValue(Result, i - 1),
4533       SDValue());
4534 
4535     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4536   }
4537 
4538   // Remove the old intrinsic from the chain
4539   DAG.ReplaceAllUsesOfValueWith(
4540     SDValue(Intr, Intr->getNumValues() - 1),
4541     Intr->getOperand(0));
4542 
4543   return Chain;
4544 }
4545 
4546 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4547                                           SelectionDAG &DAG) const {
4548   MVT VT = Op.getSimpleValueType();
4549   SDLoc DL(Op);
4550   // Checking the depth
4551   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4552     return DAG.getConstant(0, DL, VT);
4553 
4554   MachineFunction &MF = DAG.getMachineFunction();
4555   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4556   // Check for kernel and shader functions
4557   if (Info->isEntryFunction())
4558     return DAG.getConstant(0, DL, VT);
4559 
4560   MachineFrameInfo &MFI = MF.getFrameInfo();
4561   // There is a call to @llvm.returnaddress in this function
4562   MFI.setReturnAddressIsTaken(true);
4563 
4564   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4565   // Get the return address reg and mark it as an implicit live-in
4566   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4567 
4568   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4569 }
4570 
4571 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4572                                             SDValue Op,
4573                                             const SDLoc &DL,
4574                                             EVT VT) const {
4575   return Op.getValueType().bitsLE(VT) ?
4576       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4577       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4578 }
4579 
4580 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4581   assert(Op.getValueType() == MVT::f16 &&
4582          "Do not know how to custom lower FP_ROUND for non-f16 type");
4583 
4584   SDValue Src = Op.getOperand(0);
4585   EVT SrcVT = Src.getValueType();
4586   if (SrcVT != MVT::f64)
4587     return Op;
4588 
4589   SDLoc DL(Op);
4590 
4591   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4592   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4593   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4594 }
4595 
4596 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4597                                                SelectionDAG &DAG) const {
4598   EVT VT = Op.getValueType();
4599   const MachineFunction &MF = DAG.getMachineFunction();
4600   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4601   bool IsIEEEMode = Info->getMode().IEEE;
4602 
4603   // FIXME: Assert during eslection that this is only selected for
4604   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4605   // mode functions, but this happens to be OK since it's only done in cases
4606   // where there is known no sNaN.
4607   if (IsIEEEMode)
4608     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4609 
4610   if (VT == MVT::v4f16)
4611     return splitBinaryVectorOp(Op, DAG);
4612   return Op;
4613 }
4614 
4615 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4616   SDLoc SL(Op);
4617   SDValue Chain = Op.getOperand(0);
4618 
4619   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4620       !Subtarget->isTrapHandlerEnabled())
4621     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4622 
4623   MachineFunction &MF = DAG.getMachineFunction();
4624   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4625   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4626   assert(UserSGPR != AMDGPU::NoRegister);
4627   SDValue QueuePtr = CreateLiveInRegister(
4628     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4629   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4630   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4631                                    QueuePtr, SDValue());
4632   SDValue Ops[] = {
4633     ToReg,
4634     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4635     SGPR01,
4636     ToReg.getValue(1)
4637   };
4638   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4639 }
4640 
4641 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4642   SDLoc SL(Op);
4643   SDValue Chain = Op.getOperand(0);
4644   MachineFunction &MF = DAG.getMachineFunction();
4645 
4646   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4647       !Subtarget->isTrapHandlerEnabled()) {
4648     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4649                                      "debugtrap handler not supported",
4650                                      Op.getDebugLoc(),
4651                                      DS_Warning);
4652     LLVMContext &Ctx = MF.getFunction().getContext();
4653     Ctx.diagnose(NoTrap);
4654     return Chain;
4655   }
4656 
4657   SDValue Ops[] = {
4658     Chain,
4659     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4660   };
4661   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4662 }
4663 
4664 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4665                                              SelectionDAG &DAG) const {
4666   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4667   if (Subtarget->hasApertureRegs()) {
4668     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4669         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4670         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4671     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4672         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4673         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4674     unsigned Encoding =
4675         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4676         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4677         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4678 
4679     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4680     SDValue ApertureReg = SDValue(
4681         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4682     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4683     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4684   }
4685 
4686   MachineFunction &MF = DAG.getMachineFunction();
4687   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4688   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4689   assert(UserSGPR != AMDGPU::NoRegister);
4690 
4691   SDValue QueuePtr = CreateLiveInRegister(
4692     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4693 
4694   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4695   // private_segment_aperture_base_hi.
4696   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4697 
4698   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4699 
4700   // TODO: Use custom target PseudoSourceValue.
4701   // TODO: We should use the value from the IR intrinsic call, but it might not
4702   // be available and how do we get it?
4703   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4704                                               AMDGPUAS::CONSTANT_ADDRESS));
4705 
4706   MachinePointerInfo PtrInfo(V, StructOffset);
4707   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4708                      MinAlign(64, StructOffset),
4709                      MachineMemOperand::MODereferenceable |
4710                          MachineMemOperand::MOInvariant);
4711 }
4712 
4713 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4714                                              SelectionDAG &DAG) const {
4715   SDLoc SL(Op);
4716   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4717 
4718   SDValue Src = ASC->getOperand(0);
4719   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4720 
4721   const AMDGPUTargetMachine &TM =
4722     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4723 
4724   // flat -> local/private
4725   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4726     unsigned DestAS = ASC->getDestAddressSpace();
4727 
4728     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4729         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4730       unsigned NullVal = TM.getNullPointerValue(DestAS);
4731       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4732       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4733       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4734 
4735       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4736                          NonNull, Ptr, SegmentNullPtr);
4737     }
4738   }
4739 
4740   // local/private -> flat
4741   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4742     unsigned SrcAS = ASC->getSrcAddressSpace();
4743 
4744     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4745         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4746       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4747       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4748 
4749       SDValue NonNull
4750         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4751 
4752       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4753       SDValue CvtPtr
4754         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4755 
4756       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4757                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4758                          FlatNullPtr);
4759     }
4760   }
4761 
4762   // global <-> flat are no-ops and never emitted.
4763 
4764   const MachineFunction &MF = DAG.getMachineFunction();
4765   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4766     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4767   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4768 
4769   return DAG.getUNDEF(ASC->getValueType(0));
4770 }
4771 
4772 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4773 // the small vector and inserting them into the big vector. That is better than
4774 // the default expansion of doing it via a stack slot. Even though the use of
4775 // the stack slot would be optimized away afterwards, the stack slot itself
4776 // remains.
4777 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4778                                                 SelectionDAG &DAG) const {
4779   SDValue Vec = Op.getOperand(0);
4780   SDValue Ins = Op.getOperand(1);
4781   SDValue Idx = Op.getOperand(2);
4782   EVT VecVT = Vec.getValueType();
4783   EVT InsVT = Ins.getValueType();
4784   EVT EltVT = VecVT.getVectorElementType();
4785   unsigned InsNumElts = InsVT.getVectorNumElements();
4786   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4787   SDLoc SL(Op);
4788 
4789   for (unsigned I = 0; I != InsNumElts; ++I) {
4790     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4791                               DAG.getConstant(I, SL, MVT::i32));
4792     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4793                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
4794   }
4795   return Vec;
4796 }
4797 
4798 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4799                                                  SelectionDAG &DAG) const {
4800   SDValue Vec = Op.getOperand(0);
4801   SDValue InsVal = Op.getOperand(1);
4802   SDValue Idx = Op.getOperand(2);
4803   EVT VecVT = Vec.getValueType();
4804   EVT EltVT = VecVT.getVectorElementType();
4805   unsigned VecSize = VecVT.getSizeInBits();
4806   unsigned EltSize = EltVT.getSizeInBits();
4807 
4808 
4809   assert(VecSize <= 64);
4810 
4811   unsigned NumElts = VecVT.getVectorNumElements();
4812   SDLoc SL(Op);
4813   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4814 
4815   if (NumElts == 4 && EltSize == 16 && KIdx) {
4816     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4817 
4818     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4819                                  DAG.getConstant(0, SL, MVT::i32));
4820     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4821                                  DAG.getConstant(1, SL, MVT::i32));
4822 
4823     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4824     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4825 
4826     unsigned Idx = KIdx->getZExtValue();
4827     bool InsertLo = Idx < 2;
4828     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4829       InsertLo ? LoVec : HiVec,
4830       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4831       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4832 
4833     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4834 
4835     SDValue Concat = InsertLo ?
4836       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4837       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4838 
4839     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4840   }
4841 
4842   if (isa<ConstantSDNode>(Idx))
4843     return SDValue();
4844 
4845   MVT IntVT = MVT::getIntegerVT(VecSize);
4846 
4847   // Avoid stack access for dynamic indexing.
4848   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4849 
4850   // Create a congruent vector with the target value in each element so that
4851   // the required element can be masked and ORed into the target vector.
4852   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4853                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
4854 
4855   assert(isPowerOf2_32(EltSize));
4856   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4857 
4858   // Convert vector index to bit-index.
4859   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4860 
4861   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4862   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4863                             DAG.getConstant(0xffff, SL, IntVT),
4864                             ScaledIdx);
4865 
4866   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4867   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4868                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4869 
4870   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4871   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4872 }
4873 
4874 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4875                                                   SelectionDAG &DAG) const {
4876   SDLoc SL(Op);
4877 
4878   EVT ResultVT = Op.getValueType();
4879   SDValue Vec = Op.getOperand(0);
4880   SDValue Idx = Op.getOperand(1);
4881   EVT VecVT = Vec.getValueType();
4882   unsigned VecSize = VecVT.getSizeInBits();
4883   EVT EltVT = VecVT.getVectorElementType();
4884   assert(VecSize <= 64);
4885 
4886   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4887 
4888   // Make sure we do any optimizations that will make it easier to fold
4889   // source modifiers before obscuring it with bit operations.
4890 
4891   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4892   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4893     return Combined;
4894 
4895   unsigned EltSize = EltVT.getSizeInBits();
4896   assert(isPowerOf2_32(EltSize));
4897 
4898   MVT IntVT = MVT::getIntegerVT(VecSize);
4899   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4900 
4901   // Convert vector index to bit-index (* EltSize)
4902   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4903 
4904   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4905   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4906 
4907   if (ResultVT == MVT::f16) {
4908     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4909     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4910   }
4911 
4912   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4913 }
4914 
4915 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
4916   assert(Elt % 2 == 0);
4917   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
4918 }
4919 
4920 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4921                                               SelectionDAG &DAG) const {
4922   SDLoc SL(Op);
4923   EVT ResultVT = Op.getValueType();
4924   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
4925 
4926   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
4927   EVT EltVT = PackVT.getVectorElementType();
4928   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
4929 
4930   // vector_shuffle <0,1,6,7> lhs, rhs
4931   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
4932   //
4933   // vector_shuffle <6,7,2,3> lhs, rhs
4934   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
4935   //
4936   // vector_shuffle <6,7,0,1> lhs, rhs
4937   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
4938 
4939   // Avoid scalarizing when both halves are reading from consecutive elements.
4940   SmallVector<SDValue, 4> Pieces;
4941   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
4942     if (elementPairIsContiguous(SVN->getMask(), I)) {
4943       const int Idx = SVN->getMaskElt(I);
4944       int VecIdx = Idx < SrcNumElts ? 0 : 1;
4945       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
4946       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
4947                                     PackVT, SVN->getOperand(VecIdx),
4948                                     DAG.getConstant(EltIdx, SL, MVT::i32));
4949       Pieces.push_back(SubVec);
4950     } else {
4951       const int Idx0 = SVN->getMaskElt(I);
4952       const int Idx1 = SVN->getMaskElt(I + 1);
4953       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
4954       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
4955       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
4956       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
4957 
4958       SDValue Vec0 = SVN->getOperand(VecIdx0);
4959       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4960                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
4961 
4962       SDValue Vec1 = SVN->getOperand(VecIdx1);
4963       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4964                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
4965       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
4966     }
4967   }
4968 
4969   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
4970 }
4971 
4972 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4973                                             SelectionDAG &DAG) const {
4974   SDLoc SL(Op);
4975   EVT VT = Op.getValueType();
4976 
4977   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4978     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4979 
4980     // Turn into pair of packed build_vectors.
4981     // TODO: Special case for constants that can be materialized with s_mov_b64.
4982     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4983                                     { Op.getOperand(0), Op.getOperand(1) });
4984     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4985                                     { Op.getOperand(2), Op.getOperand(3) });
4986 
4987     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4988     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4989 
4990     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4991     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4992   }
4993 
4994   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4995   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
4996 
4997   SDValue Lo = Op.getOperand(0);
4998   SDValue Hi = Op.getOperand(1);
4999 
5000   // Avoid adding defined bits with the zero_extend.
5001   if (Hi.isUndef()) {
5002     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5003     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5004     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5005   }
5006 
5007   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5008   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5009 
5010   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5011                               DAG.getConstant(16, SL, MVT::i32));
5012   if (Lo.isUndef())
5013     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5014 
5015   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5016   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5017 
5018   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5019   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5020 }
5021 
5022 bool
5023 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5024   // We can fold offsets for anything that doesn't require a GOT relocation.
5025   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5026           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5027           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5028          !shouldEmitGOTReloc(GA->getGlobal());
5029 }
5030 
5031 static SDValue
5032 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5033                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5034                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5035   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5036   // lowered to the following code sequence:
5037   //
5038   // For constant address space:
5039   //   s_getpc_b64 s[0:1]
5040   //   s_add_u32 s0, s0, $symbol
5041   //   s_addc_u32 s1, s1, 0
5042   //
5043   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5044   //   a fixup or relocation is emitted to replace $symbol with a literal
5045   //   constant, which is a pc-relative offset from the encoding of the $symbol
5046   //   operand to the global variable.
5047   //
5048   // For global address space:
5049   //   s_getpc_b64 s[0:1]
5050   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5051   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5052   //
5053   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5054   //   fixups or relocations are emitted to replace $symbol@*@lo and
5055   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5056   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5057   //   operand to the global variable.
5058   //
5059   // What we want here is an offset from the value returned by s_getpc
5060   // (which is the address of the s_add_u32 instruction) to the global
5061   // variable, but since the encoding of $symbol starts 4 bytes after the start
5062   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5063   // small. This requires us to add 4 to the global variable offset in order to
5064   // compute the correct address.
5065   SDValue PtrLo =
5066       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5067   SDValue PtrHi;
5068   if (GAFlags == SIInstrInfo::MO_NONE) {
5069     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5070   } else {
5071     PtrHi =
5072         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5073   }
5074   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5075 }
5076 
5077 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5078                                              SDValue Op,
5079                                              SelectionDAG &DAG) const {
5080   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5081   const GlobalValue *GV = GSD->getGlobal();
5082   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5083        (!GV->hasExternalLinkage() ||
5084         getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
5085         getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL)) ||
5086       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5087       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5088     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5089 
5090   SDLoc DL(GSD);
5091   EVT PtrVT = Op.getValueType();
5092 
5093   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5094     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5095                                             SIInstrInfo::MO_ABS32_LO);
5096     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5097   }
5098 
5099   if (shouldEmitFixup(GV))
5100     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5101   else if (shouldEmitPCReloc(GV))
5102     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5103                                    SIInstrInfo::MO_REL32);
5104 
5105   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5106                                             SIInstrInfo::MO_GOTPCREL32);
5107 
5108   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5109   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5110   const DataLayout &DataLayout = DAG.getDataLayout();
5111   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5112   MachinePointerInfo PtrInfo
5113     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5114 
5115   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5116                      MachineMemOperand::MODereferenceable |
5117                          MachineMemOperand::MOInvariant);
5118 }
5119 
5120 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5121                                    const SDLoc &DL, SDValue V) const {
5122   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5123   // the destination register.
5124   //
5125   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5126   // so we will end up with redundant moves to m0.
5127   //
5128   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5129 
5130   // A Null SDValue creates a glue result.
5131   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5132                                   V, Chain);
5133   return SDValue(M0, 0);
5134 }
5135 
5136 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5137                                                  SDValue Op,
5138                                                  MVT VT,
5139                                                  unsigned Offset) const {
5140   SDLoc SL(Op);
5141   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5142                                            DAG.getEntryNode(), Offset, 4, false);
5143   // The local size values will have the hi 16-bits as zero.
5144   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5145                      DAG.getValueType(VT));
5146 }
5147 
5148 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5149                                         EVT VT) {
5150   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5151                                       "non-hsa intrinsic with hsa target",
5152                                       DL.getDebugLoc());
5153   DAG.getContext()->diagnose(BadIntrin);
5154   return DAG.getUNDEF(VT);
5155 }
5156 
5157 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5158                                          EVT VT) {
5159   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5160                                       "intrinsic not supported on subtarget",
5161                                       DL.getDebugLoc());
5162   DAG.getContext()->diagnose(BadIntrin);
5163   return DAG.getUNDEF(VT);
5164 }
5165 
5166 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5167                                     ArrayRef<SDValue> Elts) {
5168   assert(!Elts.empty());
5169   MVT Type;
5170   unsigned NumElts;
5171 
5172   if (Elts.size() == 1) {
5173     Type = MVT::f32;
5174     NumElts = 1;
5175   } else if (Elts.size() == 2) {
5176     Type = MVT::v2f32;
5177     NumElts = 2;
5178   } else if (Elts.size() <= 4) {
5179     Type = MVT::v4f32;
5180     NumElts = 4;
5181   } else if (Elts.size() <= 8) {
5182     Type = MVT::v8f32;
5183     NumElts = 8;
5184   } else {
5185     assert(Elts.size() <= 16);
5186     Type = MVT::v16f32;
5187     NumElts = 16;
5188   }
5189 
5190   SmallVector<SDValue, 16> VecElts(NumElts);
5191   for (unsigned i = 0; i < Elts.size(); ++i) {
5192     SDValue Elt = Elts[i];
5193     if (Elt.getValueType() != MVT::f32)
5194       Elt = DAG.getBitcast(MVT::f32, Elt);
5195     VecElts[i] = Elt;
5196   }
5197   for (unsigned i = Elts.size(); i < NumElts; ++i)
5198     VecElts[i] = DAG.getUNDEF(MVT::f32);
5199 
5200   if (NumElts == 1)
5201     return VecElts[0];
5202   return DAG.getBuildVector(Type, DL, VecElts);
5203 }
5204 
5205 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5206                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5207   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5208 
5209   uint64_t Value = CachePolicyConst->getZExtValue();
5210   SDLoc DL(CachePolicy);
5211   if (GLC) {
5212     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5213     Value &= ~(uint64_t)0x1;
5214   }
5215   if (SLC) {
5216     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5217     Value &= ~(uint64_t)0x2;
5218   }
5219   if (DLC) {
5220     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5221     Value &= ~(uint64_t)0x4;
5222   }
5223 
5224   return Value == 0;
5225 }
5226 
5227 // Re-construct the required return value for a image load intrinsic.
5228 // This is more complicated due to the optional use TexFailCtrl which means the required
5229 // return type is an aggregate
5230 static SDValue constructRetValue(SelectionDAG &DAG,
5231                                  MachineSDNode *Result,
5232                                  ArrayRef<EVT> ResultTypes,
5233                                  bool IsTexFail, bool Unpacked, bool IsD16,
5234                                  int DMaskPop, int NumVDataDwords,
5235                                  const SDLoc &DL, LLVMContext &Context) {
5236   // Determine the required return type. This is the same regardless of IsTexFail flag
5237   EVT ReqRetVT = ResultTypes[0];
5238   EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT;
5239   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5240   EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT;
5241   EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts)
5242                                            : AdjEltVT
5243                        : ReqRetVT;
5244 
5245   // Extract data part of the result
5246   // Bitcast the result to the same type as the required return type
5247   int NumElts;
5248   if (IsD16 && !Unpacked)
5249     NumElts = NumVDataDwords << 1;
5250   else
5251     NumElts = NumVDataDwords;
5252 
5253   EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts)
5254                            : AdjEltVT;
5255 
5256   // Special case for v6f16. Rather than add support for this, use v3i32 to
5257   // extract the data elements
5258   bool V6F16Special = false;
5259   if (NumElts == 6) {
5260     CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2);
5261     DMaskPop >>= 1;
5262     ReqRetNumElts >>= 1;
5263     V6F16Special = true;
5264     AdjVT = MVT::v2i32;
5265   }
5266 
5267   SDValue N = SDValue(Result, 0);
5268   SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N);
5269 
5270   // Iterate over the result
5271   SmallVector<SDValue, 4> BVElts;
5272 
5273   if (CastVT.isVector()) {
5274     DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop);
5275   } else {
5276     BVElts.push_back(CastRes);
5277   }
5278   int ExtraElts = ReqRetNumElts - DMaskPop;
5279   while(ExtraElts--)
5280     BVElts.push_back(DAG.getUNDEF(AdjEltVT));
5281 
5282   SDValue PreTFCRes;
5283   if (ReqRetNumElts > 1) {
5284     SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts);
5285     if (IsD16 && Unpacked)
5286       PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked);
5287     else
5288       PreTFCRes = NewVec;
5289   } else {
5290     PreTFCRes = BVElts[0];
5291   }
5292 
5293   if (V6F16Special)
5294     PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes);
5295 
5296   if (!IsTexFail) {
5297     if (Result->getNumValues() > 1)
5298       return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL);
5299     else
5300       return PreTFCRes;
5301   }
5302 
5303   // Extract the TexFail result and insert into aggregate return
5304   SmallVector<SDValue, 1> TFCElt;
5305   DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1);
5306   SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]);
5307   return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL);
5308 }
5309 
5310 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5311                          SDValue *LWE, bool &IsTexFail) {
5312   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5313 
5314   uint64_t Value = TexFailCtrlConst->getZExtValue();
5315   if (Value) {
5316     IsTexFail = true;
5317   }
5318 
5319   SDLoc DL(TexFailCtrlConst);
5320   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5321   Value &= ~(uint64_t)0x1;
5322   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5323   Value &= ~(uint64_t)0x2;
5324 
5325   return Value == 0;
5326 }
5327 
5328 SDValue SITargetLowering::lowerImage(SDValue Op,
5329                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5330                                      SelectionDAG &DAG) const {
5331   SDLoc DL(Op);
5332   MachineFunction &MF = DAG.getMachineFunction();
5333   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5334   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5335       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5336   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5337   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5338       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5339   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5340       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5341   unsigned IntrOpcode = Intr->BaseOpcode;
5342   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5343 
5344   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5345   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5346   bool IsD16 = false;
5347   bool IsA16 = false;
5348   SDValue VData;
5349   int NumVDataDwords;
5350   bool AdjustRetType = false;
5351 
5352   unsigned AddrIdx; // Index of first address argument
5353   unsigned DMask;
5354   unsigned DMaskLanes = 0;
5355 
5356   if (BaseOpcode->Atomic) {
5357     VData = Op.getOperand(2);
5358 
5359     bool Is64Bit = VData.getValueType() == MVT::i64;
5360     if (BaseOpcode->AtomicX2) {
5361       SDValue VData2 = Op.getOperand(3);
5362       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5363                                  {VData, VData2});
5364       if (Is64Bit)
5365         VData = DAG.getBitcast(MVT::v4i32, VData);
5366 
5367       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5368       DMask = Is64Bit ? 0xf : 0x3;
5369       NumVDataDwords = Is64Bit ? 4 : 2;
5370       AddrIdx = 4;
5371     } else {
5372       DMask = Is64Bit ? 0x3 : 0x1;
5373       NumVDataDwords = Is64Bit ? 2 : 1;
5374       AddrIdx = 3;
5375     }
5376   } else {
5377     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5378     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5379     DMask = DMaskConst->getZExtValue();
5380     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5381 
5382     if (BaseOpcode->Store) {
5383       VData = Op.getOperand(2);
5384 
5385       MVT StoreVT = VData.getSimpleValueType();
5386       if (StoreVT.getScalarType() == MVT::f16) {
5387         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5388           return Op; // D16 is unsupported for this instruction
5389 
5390         IsD16 = true;
5391         VData = handleD16VData(VData, DAG);
5392       }
5393 
5394       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5395     } else {
5396       // Work out the num dwords based on the dmask popcount and underlying type
5397       // and whether packing is supported.
5398       MVT LoadVT = ResultTypes[0].getSimpleVT();
5399       if (LoadVT.getScalarType() == MVT::f16) {
5400         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5401           return Op; // D16 is unsupported for this instruction
5402 
5403         IsD16 = true;
5404       }
5405 
5406       // Confirm that the return type is large enough for the dmask specified
5407       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5408           (!LoadVT.isVector() && DMaskLanes > 1))
5409           return Op;
5410 
5411       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5412         NumVDataDwords = (DMaskLanes + 1) / 2;
5413       else
5414         NumVDataDwords = DMaskLanes;
5415 
5416       AdjustRetType = true;
5417     }
5418 
5419     AddrIdx = DMaskIdx + 1;
5420   }
5421 
5422   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5423   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5424   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5425   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5426                        NumCoords + NumLCM;
5427   unsigned NumMIVAddrs = NumVAddrs;
5428 
5429   SmallVector<SDValue, 4> VAddrs;
5430 
5431   // Optimize _L to _LZ when _L is zero
5432   if (LZMappingInfo) {
5433     if (auto ConstantLod =
5434          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5435       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5436         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5437         NumMIVAddrs--;               // remove 'lod'
5438       }
5439     }
5440   }
5441 
5442   // Optimize _mip away, when 'lod' is zero
5443   if (MIPMappingInfo) {
5444     if (auto ConstantLod =
5445          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5446       if (ConstantLod->isNullValue()) {
5447         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5448         NumMIVAddrs--;               // remove 'lod'
5449       }
5450     }
5451   }
5452 
5453   // Check for 16 bit addresses and pack if true.
5454   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5455   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5456   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5457   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) &&
5458       ST->hasFeature(AMDGPU::FeatureR128A16)) {
5459     IsA16 = true;
5460     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5461     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5462       SDValue AddrLo, AddrHi;
5463       // Push back extra arguments.
5464       if (i < DimIdx) {
5465         AddrLo = Op.getOperand(i);
5466       } else {
5467         AddrLo = Op.getOperand(i);
5468         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5469         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5470         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5471             ((NumGradients / 2) % 2 == 1 &&
5472             (i == DimIdx + (NumGradients / 2) - 1 ||
5473              i == DimIdx + NumGradients - 1))) {
5474           AddrHi = DAG.getUNDEF(MVT::f16);
5475         } else {
5476           AddrHi = Op.getOperand(i + 1);
5477           i++;
5478         }
5479         AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT,
5480                              {AddrLo, AddrHi});
5481         AddrLo = DAG.getBitcast(MVT::i32, AddrLo);
5482       }
5483       VAddrs.push_back(AddrLo);
5484     }
5485   } else {
5486     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5487       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5488   }
5489 
5490   // If the register allocator cannot place the address registers contiguously
5491   // without introducing moves, then using the non-sequential address encoding
5492   // is always preferable, since it saves VALU instructions and is usually a
5493   // wash in terms of code size or even better.
5494   //
5495   // However, we currently have no way of hinting to the register allocator that
5496   // MIMG addresses should be placed contiguously when it is possible to do so,
5497   // so force non-NSA for the common 2-address case as a heuristic.
5498   //
5499   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5500   // allocation when possible.
5501   bool UseNSA =
5502       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5503   SDValue VAddr;
5504   if (!UseNSA)
5505     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5506 
5507   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5508   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5509   unsigned CtrlIdx; // Index of texfailctrl argument
5510   SDValue Unorm;
5511   if (!BaseOpcode->Sampler) {
5512     Unorm = True;
5513     CtrlIdx = AddrIdx + NumVAddrs + 1;
5514   } else {
5515     auto UnormConst =
5516         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5517 
5518     Unorm = UnormConst->getZExtValue() ? True : False;
5519     CtrlIdx = AddrIdx + NumVAddrs + 3;
5520   }
5521 
5522   SDValue TFE;
5523   SDValue LWE;
5524   SDValue TexFail = Op.getOperand(CtrlIdx);
5525   bool IsTexFail = false;
5526   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5527     return Op;
5528 
5529   if (IsTexFail) {
5530     if (!DMaskLanes) {
5531       // Expecting to get an error flag since TFC is on - and dmask is 0
5532       // Force dmask to be at least 1 otherwise the instruction will fail
5533       DMask = 0x1;
5534       DMaskLanes = 1;
5535       NumVDataDwords = 1;
5536     }
5537     NumVDataDwords += 1;
5538     AdjustRetType = true;
5539   }
5540 
5541   // Has something earlier tagged that the return type needs adjusting
5542   // This happens if the instruction is a load or has set TexFailCtrl flags
5543   if (AdjustRetType) {
5544     // NumVDataDwords reflects the true number of dwords required in the return type
5545     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5546       // This is a no-op load. This can be eliminated
5547       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5548       if (isa<MemSDNode>(Op))
5549         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5550       return Undef;
5551     }
5552 
5553     EVT NewVT = NumVDataDwords > 1 ?
5554                   EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords)
5555                 : MVT::f32;
5556 
5557     ResultTypes[0] = NewVT;
5558     if (ResultTypes.size() == 3) {
5559       // Original result was aggregate type used for TexFailCtrl results
5560       // The actual instruction returns as a vector type which has now been
5561       // created. Remove the aggregate result.
5562       ResultTypes.erase(&ResultTypes[1]);
5563     }
5564   }
5565 
5566   SDValue GLC;
5567   SDValue SLC;
5568   SDValue DLC;
5569   if (BaseOpcode->Atomic) {
5570     GLC = True; // TODO no-return optimization
5571     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5572                           IsGFX10 ? &DLC : nullptr))
5573       return Op;
5574   } else {
5575     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5576                           IsGFX10 ? &DLC : nullptr))
5577       return Op;
5578   }
5579 
5580   SmallVector<SDValue, 26> Ops;
5581   if (BaseOpcode->Store || BaseOpcode->Atomic)
5582     Ops.push_back(VData); // vdata
5583   if (UseNSA) {
5584     for (const SDValue &Addr : VAddrs)
5585       Ops.push_back(Addr);
5586   } else {
5587     Ops.push_back(VAddr);
5588   }
5589   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5590   if (BaseOpcode->Sampler)
5591     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5592   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5593   if (IsGFX10)
5594     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5595   Ops.push_back(Unorm);
5596   if (IsGFX10)
5597     Ops.push_back(DLC);
5598   Ops.push_back(GLC);
5599   Ops.push_back(SLC);
5600   Ops.push_back(IsA16 &&  // a16 or r128
5601                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5602   Ops.push_back(TFE); // tfe
5603   Ops.push_back(LWE); // lwe
5604   if (!IsGFX10)
5605     Ops.push_back(DimInfo->DA ? True : False);
5606   if (BaseOpcode->HasD16)
5607     Ops.push_back(IsD16 ? True : False);
5608   if (isa<MemSDNode>(Op))
5609     Ops.push_back(Op.getOperand(0)); // chain
5610 
5611   int NumVAddrDwords =
5612       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5613   int Opcode = -1;
5614 
5615   if (IsGFX10) {
5616     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5617                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5618                                           : AMDGPU::MIMGEncGfx10Default,
5619                                    NumVDataDwords, NumVAddrDwords);
5620   } else {
5621     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5622       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5623                                      NumVDataDwords, NumVAddrDwords);
5624     if (Opcode == -1)
5625       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5626                                      NumVDataDwords, NumVAddrDwords);
5627   }
5628   assert(Opcode != -1);
5629 
5630   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5631   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5632     MachineMemOperand *MemRef = MemOp->getMemOperand();
5633     DAG.setNodeMemRefs(NewNode, {MemRef});
5634   }
5635 
5636   if (BaseOpcode->AtomicX2) {
5637     SmallVector<SDValue, 1> Elt;
5638     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5639     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5640   } else if (!BaseOpcode->Store) {
5641     return constructRetValue(DAG, NewNode,
5642                              OrigResultTypes, IsTexFail,
5643                              Subtarget->hasUnpackedD16VMem(), IsD16,
5644                              DMaskLanes, NumVDataDwords, DL,
5645                              *DAG.getContext());
5646   }
5647 
5648   return SDValue(NewNode, 0);
5649 }
5650 
5651 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5652                                        SDValue Offset, SDValue GLC, SDValue DLC,
5653                                        SelectionDAG &DAG) const {
5654   MachineFunction &MF = DAG.getMachineFunction();
5655   MachineMemOperand *MMO = MF.getMachineMemOperand(
5656       MachinePointerInfo(),
5657       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5658           MachineMemOperand::MOInvariant,
5659       VT.getStoreSize(), VT.getStoreSize());
5660 
5661   if (!Offset->isDivergent()) {
5662     SDValue Ops[] = {
5663         Rsrc,
5664         Offset, // Offset
5665         GLC,
5666         DLC,
5667     };
5668     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5669                                    DAG.getVTList(VT), Ops, VT, MMO);
5670   }
5671 
5672   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5673   // assume that the buffer is unswizzled.
5674   SmallVector<SDValue, 4> Loads;
5675   unsigned NumLoads = 1;
5676   MVT LoadVT = VT.getSimpleVT();
5677   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5678   assert((LoadVT.getScalarType() == MVT::i32 ||
5679           LoadVT.getScalarType() == MVT::f32) &&
5680          isPowerOf2_32(NumElts));
5681 
5682   if (NumElts == 8 || NumElts == 16) {
5683     NumLoads = NumElts == 16 ? 4 : 2;
5684     LoadVT = MVT::v4i32;
5685   }
5686 
5687   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5688   unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue();
5689   SDValue Ops[] = {
5690       DAG.getEntryNode(),                               // Chain
5691       Rsrc,                                             // rsrc
5692       DAG.getConstant(0, DL, MVT::i32),                 // vindex
5693       {},                                               // voffset
5694       {},                                               // soffset
5695       {},                                               // offset
5696       DAG.getTargetConstant(CachePolicy, DL, MVT::i32), // cachepolicy
5697       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
5698   };
5699 
5700   // Use the alignment to ensure that the required offsets will fit into the
5701   // immediate offsets.
5702   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5703 
5704   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5705   for (unsigned i = 0; i < NumLoads; ++i) {
5706     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5707     Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList,
5708                                             Ops, LoadVT, MMO));
5709   }
5710 
5711   if (VT == MVT::v8i32 || VT == MVT::v16i32)
5712     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5713 
5714   return Loads[0];
5715 }
5716 
5717 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5718                                                   SelectionDAG &DAG) const {
5719   MachineFunction &MF = DAG.getMachineFunction();
5720   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5721 
5722   EVT VT = Op.getValueType();
5723   SDLoc DL(Op);
5724   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5725 
5726   // TODO: Should this propagate fast-math-flags?
5727 
5728   switch (IntrinsicID) {
5729   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5730     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5731       return emitNonHSAIntrinsicError(DAG, DL, VT);
5732     return getPreloadedValue(DAG, *MFI, VT,
5733                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5734   }
5735   case Intrinsic::amdgcn_dispatch_ptr:
5736   case Intrinsic::amdgcn_queue_ptr: {
5737     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5738       DiagnosticInfoUnsupported BadIntrin(
5739           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5740           DL.getDebugLoc());
5741       DAG.getContext()->diagnose(BadIntrin);
5742       return DAG.getUNDEF(VT);
5743     }
5744 
5745     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5746       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5747     return getPreloadedValue(DAG, *MFI, VT, RegID);
5748   }
5749   case Intrinsic::amdgcn_implicitarg_ptr: {
5750     if (MFI->isEntryFunction())
5751       return getImplicitArgPtr(DAG, DL);
5752     return getPreloadedValue(DAG, *MFI, VT,
5753                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5754   }
5755   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5756     return getPreloadedValue(DAG, *MFI, VT,
5757                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5758   }
5759   case Intrinsic::amdgcn_dispatch_id: {
5760     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5761   }
5762   case Intrinsic::amdgcn_rcp:
5763     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5764   case Intrinsic::amdgcn_rsq:
5765     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5766   case Intrinsic::amdgcn_rsq_legacy:
5767     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5768       return emitRemovedIntrinsicError(DAG, DL, VT);
5769 
5770     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5771   case Intrinsic::amdgcn_rcp_legacy:
5772     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5773       return emitRemovedIntrinsicError(DAG, DL, VT);
5774     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5775   case Intrinsic::amdgcn_rsq_clamp: {
5776     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5777       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5778 
5779     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5780     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5781     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5782 
5783     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5784     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5785                               DAG.getConstantFP(Max, DL, VT));
5786     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5787                        DAG.getConstantFP(Min, DL, VT));
5788   }
5789   case Intrinsic::r600_read_ngroups_x:
5790     if (Subtarget->isAmdHsaOS())
5791       return emitNonHSAIntrinsicError(DAG, DL, VT);
5792 
5793     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5794                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
5795   case Intrinsic::r600_read_ngroups_y:
5796     if (Subtarget->isAmdHsaOS())
5797       return emitNonHSAIntrinsicError(DAG, DL, VT);
5798 
5799     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5800                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5801   case Intrinsic::r600_read_ngroups_z:
5802     if (Subtarget->isAmdHsaOS())
5803       return emitNonHSAIntrinsicError(DAG, DL, VT);
5804 
5805     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5806                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5807   case Intrinsic::r600_read_global_size_x:
5808     if (Subtarget->isAmdHsaOS())
5809       return emitNonHSAIntrinsicError(DAG, DL, VT);
5810 
5811     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5812                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5813   case Intrinsic::r600_read_global_size_y:
5814     if (Subtarget->isAmdHsaOS())
5815       return emitNonHSAIntrinsicError(DAG, DL, VT);
5816 
5817     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5818                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5819   case Intrinsic::r600_read_global_size_z:
5820     if (Subtarget->isAmdHsaOS())
5821       return emitNonHSAIntrinsicError(DAG, DL, VT);
5822 
5823     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5824                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5825   case Intrinsic::r600_read_local_size_x:
5826     if (Subtarget->isAmdHsaOS())
5827       return emitNonHSAIntrinsicError(DAG, DL, VT);
5828 
5829     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5830                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
5831   case Intrinsic::r600_read_local_size_y:
5832     if (Subtarget->isAmdHsaOS())
5833       return emitNonHSAIntrinsicError(DAG, DL, VT);
5834 
5835     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5836                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
5837   case Intrinsic::r600_read_local_size_z:
5838     if (Subtarget->isAmdHsaOS())
5839       return emitNonHSAIntrinsicError(DAG, DL, VT);
5840 
5841     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5842                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
5843   case Intrinsic::amdgcn_workgroup_id_x:
5844   case Intrinsic::r600_read_tgid_x:
5845     return getPreloadedValue(DAG, *MFI, VT,
5846                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5847   case Intrinsic::amdgcn_workgroup_id_y:
5848   case Intrinsic::r600_read_tgid_y:
5849     return getPreloadedValue(DAG, *MFI, VT,
5850                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5851   case Intrinsic::amdgcn_workgroup_id_z:
5852   case Intrinsic::r600_read_tgid_z:
5853     return getPreloadedValue(DAG, *MFI, VT,
5854                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5855   case Intrinsic::amdgcn_workitem_id_x:
5856   case Intrinsic::r600_read_tidig_x:
5857     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5858                           SDLoc(DAG.getEntryNode()),
5859                           MFI->getArgInfo().WorkItemIDX);
5860   case Intrinsic::amdgcn_workitem_id_y:
5861   case Intrinsic::r600_read_tidig_y:
5862     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5863                           SDLoc(DAG.getEntryNode()),
5864                           MFI->getArgInfo().WorkItemIDY);
5865   case Intrinsic::amdgcn_workitem_id_z:
5866   case Intrinsic::r600_read_tidig_z:
5867     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5868                           SDLoc(DAG.getEntryNode()),
5869                           MFI->getArgInfo().WorkItemIDZ);
5870   case Intrinsic::amdgcn_wavefrontsize:
5871     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
5872                            SDLoc(Op), MVT::i32);
5873   case Intrinsic::amdgcn_s_buffer_load: {
5874     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5875     SDValue GLC;
5876     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5877     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5878                           IsGFX10 ? &DLC : nullptr))
5879       return Op;
5880     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC,
5881                         DAG);
5882   }
5883   case Intrinsic::amdgcn_fdiv_fast:
5884     return lowerFDIV_FAST(Op, DAG);
5885   case Intrinsic::amdgcn_interp_p1_f16: {
5886     SDValue ToM0 = DAG.getCopyToReg(DAG.getEntryNode(), DL, AMDGPU::M0,
5887                                     Op.getOperand(5), SDValue());
5888     if (getSubtarget()->getLDSBankCount() == 16) {
5889       // 16 bank LDS
5890 
5891       // FIXME: This implicitly will insert a second CopyToReg to M0.
5892       SDValue S = DAG.getNode(
5893         ISD::INTRINSIC_WO_CHAIN, DL, MVT::f32,
5894         DAG.getTargetConstant(Intrinsic::amdgcn_interp_mov, DL, MVT::i32),
5895         DAG.getConstant(2, DL, MVT::i32), // P0
5896         Op.getOperand(2),  // Attrchan
5897         Op.getOperand(3),  // Attr
5898         Op.getOperand(5)); // m0
5899 
5900       SDValue Ops[] = {
5901         Op.getOperand(1), // Src0
5902         Op.getOperand(2), // Attrchan
5903         Op.getOperand(3), // Attr
5904         DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
5905         S, // Src2 - holds two f16 values selected by high
5906         DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers
5907         Op.getOperand(4), // high
5908         DAG.getTargetConstant(0, DL, MVT::i1), // $clamp
5909         DAG.getTargetConstant(0, DL, MVT::i32) // $omod
5910       };
5911       return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops);
5912     } else {
5913       // 32 bank LDS
5914       SDValue Ops[] = {
5915         Op.getOperand(1), // Src0
5916         Op.getOperand(2), // Attrchan
5917         Op.getOperand(3), // Attr
5918         DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
5919         Op.getOperand(4), // high
5920         DAG.getTargetConstant(0, DL, MVT::i1), // $clamp
5921         DAG.getTargetConstant(0, DL, MVT::i32), // $omod
5922         ToM0.getValue(1)
5923       };
5924       return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops);
5925     }
5926   }
5927   case Intrinsic::amdgcn_interp_p2_f16: {
5928     SDValue ToM0 = DAG.getCopyToReg(DAG.getEntryNode(), DL, AMDGPU::M0,
5929                                     Op.getOperand(6), SDValue());
5930     SDValue Ops[] = {
5931       Op.getOperand(2), // Src0
5932       Op.getOperand(3), // Attrchan
5933       Op.getOperand(4), // Attr
5934       DAG.getTargetConstant(0, DL, MVT::i32), // $src0_modifiers
5935       Op.getOperand(1), // Src2
5936       DAG.getTargetConstant(0, DL, MVT::i32), // $src2_modifiers
5937       Op.getOperand(5), // high
5938       DAG.getTargetConstant(0, DL, MVT::i1), // $clamp
5939       ToM0.getValue(1)
5940     };
5941     return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops);
5942   }
5943   case Intrinsic::amdgcn_sin:
5944     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5945 
5946   case Intrinsic::amdgcn_cos:
5947     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5948 
5949   case Intrinsic::amdgcn_mul_u24:
5950     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5951   case Intrinsic::amdgcn_mul_i24:
5952     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5953 
5954   case Intrinsic::amdgcn_log_clamp: {
5955     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5956       return SDValue();
5957 
5958     DiagnosticInfoUnsupported BadIntrin(
5959       MF.getFunction(), "intrinsic not supported on subtarget",
5960       DL.getDebugLoc());
5961       DAG.getContext()->diagnose(BadIntrin);
5962       return DAG.getUNDEF(VT);
5963   }
5964   case Intrinsic::amdgcn_ldexp:
5965     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5966                        Op.getOperand(1), Op.getOperand(2));
5967 
5968   case Intrinsic::amdgcn_fract:
5969     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5970 
5971   case Intrinsic::amdgcn_class:
5972     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5973                        Op.getOperand(1), Op.getOperand(2));
5974   case Intrinsic::amdgcn_div_fmas:
5975     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5976                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5977                        Op.getOperand(4));
5978 
5979   case Intrinsic::amdgcn_div_fixup:
5980     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5981                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5982 
5983   case Intrinsic::amdgcn_trig_preop:
5984     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5985                        Op.getOperand(1), Op.getOperand(2));
5986   case Intrinsic::amdgcn_div_scale: {
5987     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5988 
5989     // Translate to the operands expected by the machine instruction. The
5990     // first parameter must be the same as the first instruction.
5991     SDValue Numerator = Op.getOperand(1);
5992     SDValue Denominator = Op.getOperand(2);
5993 
5994     // Note this order is opposite of the machine instruction's operations,
5995     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
5996     // intrinsic has the numerator as the first operand to match a normal
5997     // division operation.
5998 
5999     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6000 
6001     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6002                        Denominator, Numerator);
6003   }
6004   case Intrinsic::amdgcn_icmp: {
6005     // There is a Pat that handles this variant, so return it as-is.
6006     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6007         Op.getConstantOperandVal(2) == 0 &&
6008         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6009       return Op;
6010     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6011   }
6012   case Intrinsic::amdgcn_fcmp: {
6013     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6014   }
6015   case Intrinsic::amdgcn_fmed3:
6016     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6017                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6018   case Intrinsic::amdgcn_fdot2:
6019     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6020                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6021                        Op.getOperand(4));
6022   case Intrinsic::amdgcn_fmul_legacy:
6023     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6024                        Op.getOperand(1), Op.getOperand(2));
6025   case Intrinsic::amdgcn_sffbh:
6026     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6027   case Intrinsic::amdgcn_sbfe:
6028     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6029                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6030   case Intrinsic::amdgcn_ubfe:
6031     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6032                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6033   case Intrinsic::amdgcn_cvt_pkrtz:
6034   case Intrinsic::amdgcn_cvt_pknorm_i16:
6035   case Intrinsic::amdgcn_cvt_pknorm_u16:
6036   case Intrinsic::amdgcn_cvt_pk_i16:
6037   case Intrinsic::amdgcn_cvt_pk_u16: {
6038     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6039     EVT VT = Op.getValueType();
6040     unsigned Opcode;
6041 
6042     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6043       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6044     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6045       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6046     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6047       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6048     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6049       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6050     else
6051       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6052 
6053     if (isTypeLegal(VT))
6054       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6055 
6056     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6057                                Op.getOperand(1), Op.getOperand(2));
6058     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6059   }
6060   case Intrinsic::amdgcn_fmad_ftz:
6061     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6062                        Op.getOperand(2), Op.getOperand(3));
6063 
6064   case Intrinsic::amdgcn_if_break:
6065     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6066                                       Op->getOperand(1), Op->getOperand(2)), 0);
6067 
6068   case Intrinsic::amdgcn_groupstaticsize: {
6069     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6070     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6071       return Op;
6072 
6073     const Module *M = MF.getFunction().getParent();
6074     const GlobalValue *GV =
6075         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6076     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6077                                             SIInstrInfo::MO_ABS32_LO);
6078     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6079   }
6080   case Intrinsic::amdgcn_is_shared:
6081   case Intrinsic::amdgcn_is_private: {
6082     SDLoc SL(Op);
6083     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6084       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6085     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6086     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6087                                  Op.getOperand(1));
6088 
6089     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6090                                 DAG.getConstant(1, SL, MVT::i32));
6091     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6092   }
6093   default:
6094     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6095             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6096       return lowerImage(Op, ImageDimIntr, DAG);
6097 
6098     return Op;
6099   }
6100 }
6101 
6102 // This function computes an appropriate offset to pass to
6103 // MachineMemOperand::setOffset() based on the offset inputs to
6104 // an intrinsic.  If any of the offsets are non-contstant or
6105 // if VIndex is non-zero then this function returns 0.  Otherwise,
6106 // it returns the sum of VOffset, SOffset, and Offset.
6107 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6108                                       SDValue SOffset,
6109                                       SDValue Offset,
6110                                       SDValue VIndex = SDValue()) {
6111 
6112   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6113       !isa<ConstantSDNode>(Offset))
6114     return 0;
6115 
6116   if (VIndex) {
6117     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6118       return 0;
6119   }
6120 
6121   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6122          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6123          cast<ConstantSDNode>(Offset)->getSExtValue();
6124 }
6125 
6126 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6127                                                  SelectionDAG &DAG) const {
6128   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6129   SDLoc DL(Op);
6130 
6131   switch (IntrID) {
6132   case Intrinsic::amdgcn_ds_ordered_add:
6133   case Intrinsic::amdgcn_ds_ordered_swap: {
6134     MemSDNode *M = cast<MemSDNode>(Op);
6135     SDValue Chain = M->getOperand(0);
6136     SDValue M0 = M->getOperand(2);
6137     SDValue Value = M->getOperand(3);
6138     unsigned IndexOperand = M->getConstantOperandVal(7);
6139     unsigned WaveRelease = M->getConstantOperandVal(8);
6140     unsigned WaveDone = M->getConstantOperandVal(9);
6141     unsigned ShaderType;
6142     unsigned Instruction;
6143 
6144     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6145     IndexOperand &= ~0x3f;
6146     unsigned CountDw = 0;
6147 
6148     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6149       CountDw = (IndexOperand >> 24) & 0xf;
6150       IndexOperand &= ~(0xf << 24);
6151 
6152       if (CountDw < 1 || CountDw > 4) {
6153         report_fatal_error(
6154             "ds_ordered_count: dword count must be between 1 and 4");
6155       }
6156     }
6157 
6158     if (IndexOperand)
6159       report_fatal_error("ds_ordered_count: bad index operand");
6160 
6161     switch (IntrID) {
6162     case Intrinsic::amdgcn_ds_ordered_add:
6163       Instruction = 0;
6164       break;
6165     case Intrinsic::amdgcn_ds_ordered_swap:
6166       Instruction = 1;
6167       break;
6168     }
6169 
6170     if (WaveDone && !WaveRelease)
6171       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6172 
6173     switch (DAG.getMachineFunction().getFunction().getCallingConv()) {
6174     case CallingConv::AMDGPU_CS:
6175     case CallingConv::AMDGPU_KERNEL:
6176       ShaderType = 0;
6177       break;
6178     case CallingConv::AMDGPU_PS:
6179       ShaderType = 1;
6180       break;
6181     case CallingConv::AMDGPU_VS:
6182       ShaderType = 2;
6183       break;
6184     case CallingConv::AMDGPU_GS:
6185       ShaderType = 3;
6186       break;
6187     default:
6188       report_fatal_error("ds_ordered_count unsupported for this calling conv");
6189     }
6190 
6191     unsigned Offset0 = OrderedCountIndex << 2;
6192     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6193                        (Instruction << 4);
6194 
6195     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6196       Offset1 |= (CountDw - 1) << 6;
6197 
6198     unsigned Offset = Offset0 | (Offset1 << 8);
6199 
6200     SDValue Ops[] = {
6201       Chain,
6202       Value,
6203       DAG.getTargetConstant(Offset, DL, MVT::i16),
6204       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6205     };
6206     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6207                                    M->getVTList(), Ops, M->getMemoryVT(),
6208                                    M->getMemOperand());
6209   }
6210   case Intrinsic::amdgcn_ds_fadd: {
6211     MemSDNode *M = cast<MemSDNode>(Op);
6212     unsigned Opc;
6213     switch (IntrID) {
6214     case Intrinsic::amdgcn_ds_fadd:
6215       Opc = ISD::ATOMIC_LOAD_FADD;
6216       break;
6217     }
6218 
6219     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6220                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6221                          M->getMemOperand());
6222   }
6223   case Intrinsic::amdgcn_atomic_inc:
6224   case Intrinsic::amdgcn_atomic_dec:
6225   case Intrinsic::amdgcn_ds_fmin:
6226   case Intrinsic::amdgcn_ds_fmax: {
6227     MemSDNode *M = cast<MemSDNode>(Op);
6228     unsigned Opc;
6229     switch (IntrID) {
6230     case Intrinsic::amdgcn_atomic_inc:
6231       Opc = AMDGPUISD::ATOMIC_INC;
6232       break;
6233     case Intrinsic::amdgcn_atomic_dec:
6234       Opc = AMDGPUISD::ATOMIC_DEC;
6235       break;
6236     case Intrinsic::amdgcn_ds_fmin:
6237       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6238       break;
6239     case Intrinsic::amdgcn_ds_fmax:
6240       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6241       break;
6242     default:
6243       llvm_unreachable("Unknown intrinsic!");
6244     }
6245     SDValue Ops[] = {
6246       M->getOperand(0), // Chain
6247       M->getOperand(2), // Ptr
6248       M->getOperand(3)  // Value
6249     };
6250 
6251     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6252                                    M->getMemoryVT(), M->getMemOperand());
6253   }
6254   case Intrinsic::amdgcn_buffer_load:
6255   case Intrinsic::amdgcn_buffer_load_format: {
6256     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6257     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6258     unsigned IdxEn = 1;
6259     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6260       IdxEn = Idx->getZExtValue() != 0;
6261     SDValue Ops[] = {
6262       Op.getOperand(0), // Chain
6263       Op.getOperand(2), // rsrc
6264       Op.getOperand(3), // vindex
6265       SDValue(),        // voffset -- will be set by setBufferOffsets
6266       SDValue(),        // soffset -- will be set by setBufferOffsets
6267       SDValue(),        // offset -- will be set by setBufferOffsets
6268       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6269       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6270     };
6271 
6272     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6273     // We don't know the offset if vindex is non-zero, so clear it.
6274     if (IdxEn)
6275       Offset = 0;
6276 
6277     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6278         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6279 
6280     EVT VT = Op.getValueType();
6281     EVT IntVT = VT.changeTypeToInteger();
6282     auto *M = cast<MemSDNode>(Op);
6283     M->getMemOperand()->setOffset(Offset);
6284     EVT LoadVT = Op.getValueType();
6285 
6286     if (LoadVT.getScalarType() == MVT::f16)
6287       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6288                                  M, DAG, Ops);
6289 
6290     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6291     if (LoadVT.getScalarType() == MVT::i8 ||
6292         LoadVT.getScalarType() == MVT::i16)
6293       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6294 
6295     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6296                                M->getMemOperand(), DAG);
6297   }
6298   case Intrinsic::amdgcn_raw_buffer_load:
6299   case Intrinsic::amdgcn_raw_buffer_load_format: {
6300     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6301 
6302     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6303     SDValue Ops[] = {
6304       Op.getOperand(0), // Chain
6305       Op.getOperand(2), // rsrc
6306       DAG.getConstant(0, DL, MVT::i32), // vindex
6307       Offsets.first,    // voffset
6308       Op.getOperand(4), // soffset
6309       Offsets.second,   // offset
6310       Op.getOperand(5), // cachepolicy, swizzled buffer
6311       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6312     };
6313 
6314     auto *M = cast<MemSDNode>(Op);
6315     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6316     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6317   }
6318   case Intrinsic::amdgcn_struct_buffer_load:
6319   case Intrinsic::amdgcn_struct_buffer_load_format: {
6320     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6321 
6322     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6323     SDValue Ops[] = {
6324       Op.getOperand(0), // Chain
6325       Op.getOperand(2), // rsrc
6326       Op.getOperand(3), // vindex
6327       Offsets.first,    // voffset
6328       Op.getOperand(5), // soffset
6329       Offsets.second,   // offset
6330       Op.getOperand(6), // cachepolicy, swizzled buffer
6331       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6332     };
6333 
6334     auto *M = cast<MemSDNode>(Op);
6335     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6336                                                         Ops[2]));
6337     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6338   }
6339   case Intrinsic::amdgcn_tbuffer_load: {
6340     MemSDNode *M = cast<MemSDNode>(Op);
6341     EVT LoadVT = Op.getValueType();
6342 
6343     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6344     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6345     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6346     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6347     unsigned IdxEn = 1;
6348     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6349       IdxEn = Idx->getZExtValue() != 0;
6350     SDValue Ops[] = {
6351       Op.getOperand(0),  // Chain
6352       Op.getOperand(2),  // rsrc
6353       Op.getOperand(3),  // vindex
6354       Op.getOperand(4),  // voffset
6355       Op.getOperand(5),  // soffset
6356       Op.getOperand(6),  // offset
6357       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6358       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6359       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6360     };
6361 
6362     if (LoadVT.getScalarType() == MVT::f16)
6363       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6364                                  M, DAG, Ops);
6365     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6366                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6367                                DAG);
6368   }
6369   case Intrinsic::amdgcn_raw_tbuffer_load: {
6370     MemSDNode *M = cast<MemSDNode>(Op);
6371     EVT LoadVT = Op.getValueType();
6372     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6373 
6374     SDValue Ops[] = {
6375       Op.getOperand(0),  // Chain
6376       Op.getOperand(2),  // rsrc
6377       DAG.getConstant(0, DL, MVT::i32), // vindex
6378       Offsets.first,     // voffset
6379       Op.getOperand(4),  // soffset
6380       Offsets.second,    // offset
6381       Op.getOperand(5),  // format
6382       Op.getOperand(6),  // cachepolicy, swizzled buffer
6383       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6384     };
6385 
6386     if (LoadVT.getScalarType() == MVT::f16)
6387       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6388                                  M, DAG, Ops);
6389     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6390                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6391                                DAG);
6392   }
6393   case Intrinsic::amdgcn_struct_tbuffer_load: {
6394     MemSDNode *M = cast<MemSDNode>(Op);
6395     EVT LoadVT = Op.getValueType();
6396     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6397 
6398     SDValue Ops[] = {
6399       Op.getOperand(0),  // Chain
6400       Op.getOperand(2),  // rsrc
6401       Op.getOperand(3),  // vindex
6402       Offsets.first,     // voffset
6403       Op.getOperand(5),  // soffset
6404       Offsets.second,    // offset
6405       Op.getOperand(6),  // format
6406       Op.getOperand(7),  // cachepolicy, swizzled buffer
6407       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6408     };
6409 
6410     if (LoadVT.getScalarType() == MVT::f16)
6411       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6412                                  M, DAG, Ops);
6413     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6414                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6415                                DAG);
6416   }
6417   case Intrinsic::amdgcn_buffer_atomic_swap:
6418   case Intrinsic::amdgcn_buffer_atomic_add:
6419   case Intrinsic::amdgcn_buffer_atomic_sub:
6420   case Intrinsic::amdgcn_buffer_atomic_smin:
6421   case Intrinsic::amdgcn_buffer_atomic_umin:
6422   case Intrinsic::amdgcn_buffer_atomic_smax:
6423   case Intrinsic::amdgcn_buffer_atomic_umax:
6424   case Intrinsic::amdgcn_buffer_atomic_and:
6425   case Intrinsic::amdgcn_buffer_atomic_or:
6426   case Intrinsic::amdgcn_buffer_atomic_xor: {
6427     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6428     unsigned IdxEn = 1;
6429     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6430       IdxEn = Idx->getZExtValue() != 0;
6431     SDValue Ops[] = {
6432       Op.getOperand(0), // Chain
6433       Op.getOperand(2), // vdata
6434       Op.getOperand(3), // rsrc
6435       Op.getOperand(4), // vindex
6436       SDValue(),        // voffset -- will be set by setBufferOffsets
6437       SDValue(),        // soffset -- will be set by setBufferOffsets
6438       SDValue(),        // offset -- will be set by setBufferOffsets
6439       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6440       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6441     };
6442     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6443     // We don't know the offset if vindex is non-zero, so clear it.
6444     if (IdxEn)
6445       Offset = 0;
6446     EVT VT = Op.getValueType();
6447 
6448     auto *M = cast<MemSDNode>(Op);
6449     M->getMemOperand()->setOffset(Offset);
6450     unsigned Opcode = 0;
6451 
6452     switch (IntrID) {
6453     case Intrinsic::amdgcn_buffer_atomic_swap:
6454       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6455       break;
6456     case Intrinsic::amdgcn_buffer_atomic_add:
6457       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6458       break;
6459     case Intrinsic::amdgcn_buffer_atomic_sub:
6460       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6461       break;
6462     case Intrinsic::amdgcn_buffer_atomic_smin:
6463       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6464       break;
6465     case Intrinsic::amdgcn_buffer_atomic_umin:
6466       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6467       break;
6468     case Intrinsic::amdgcn_buffer_atomic_smax:
6469       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6470       break;
6471     case Intrinsic::amdgcn_buffer_atomic_umax:
6472       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6473       break;
6474     case Intrinsic::amdgcn_buffer_atomic_and:
6475       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6476       break;
6477     case Intrinsic::amdgcn_buffer_atomic_or:
6478       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6479       break;
6480     case Intrinsic::amdgcn_buffer_atomic_xor:
6481       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6482       break;
6483     default:
6484       llvm_unreachable("unhandled atomic opcode");
6485     }
6486 
6487     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6488                                    M->getMemOperand());
6489   }
6490   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6491   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6492   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6493   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6494   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6495   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6496   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6497   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6498   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6499   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6500   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6501   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6502     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6503     SDValue Ops[] = {
6504       Op.getOperand(0), // Chain
6505       Op.getOperand(2), // vdata
6506       Op.getOperand(3), // rsrc
6507       DAG.getConstant(0, DL, MVT::i32), // vindex
6508       Offsets.first,    // voffset
6509       Op.getOperand(5), // soffset
6510       Offsets.second,   // offset
6511       Op.getOperand(6), // cachepolicy
6512       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6513     };
6514     EVT VT = Op.getValueType();
6515 
6516     auto *M = cast<MemSDNode>(Op);
6517     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6518     unsigned Opcode = 0;
6519 
6520     switch (IntrID) {
6521     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6522       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6523       break;
6524     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6525       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6526       break;
6527     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6528       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6529       break;
6530     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6531       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6532       break;
6533     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6534       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6535       break;
6536     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6537       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6538       break;
6539     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6540       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6541       break;
6542     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6543       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6544       break;
6545     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6546       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6547       break;
6548     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6549       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6550       break;
6551     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6552       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6553       break;
6554     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6555       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6556       break;
6557     default:
6558       llvm_unreachable("unhandled atomic opcode");
6559     }
6560 
6561     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6562                                    M->getMemOperand());
6563   }
6564   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6565   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6566   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6567   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6568   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6569   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6570   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6571   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6572   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6573   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6574   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6575   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6576     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6577     SDValue Ops[] = {
6578       Op.getOperand(0), // Chain
6579       Op.getOperand(2), // vdata
6580       Op.getOperand(3), // rsrc
6581       Op.getOperand(4), // vindex
6582       Offsets.first,    // voffset
6583       Op.getOperand(6), // soffset
6584       Offsets.second,   // offset
6585       Op.getOperand(7), // cachepolicy
6586       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6587     };
6588     EVT VT = Op.getValueType();
6589 
6590     auto *M = cast<MemSDNode>(Op);
6591     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6592                                                         Ops[3]));
6593     unsigned Opcode = 0;
6594 
6595     switch (IntrID) {
6596     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6597       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6598       break;
6599     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6600       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6601       break;
6602     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6603       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6604       break;
6605     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6606       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6607       break;
6608     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6609       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6610       break;
6611     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6612       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6613       break;
6614     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6615       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6616       break;
6617     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6618       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6619       break;
6620     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6621       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6622       break;
6623     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6624       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6625       break;
6626     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6627       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6628       break;
6629     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6630       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6631       break;
6632     default:
6633       llvm_unreachable("unhandled atomic opcode");
6634     }
6635 
6636     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6637                                    M->getMemOperand());
6638   }
6639   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6640     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6641     unsigned IdxEn = 1;
6642     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6643       IdxEn = Idx->getZExtValue() != 0;
6644     SDValue Ops[] = {
6645       Op.getOperand(0), // Chain
6646       Op.getOperand(2), // src
6647       Op.getOperand(3), // cmp
6648       Op.getOperand(4), // rsrc
6649       Op.getOperand(5), // vindex
6650       SDValue(),        // voffset -- will be set by setBufferOffsets
6651       SDValue(),        // soffset -- will be set by setBufferOffsets
6652       SDValue(),        // offset -- will be set by setBufferOffsets
6653       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6654       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6655     };
6656     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6657     // We don't know the offset if vindex is non-zero, so clear it.
6658     if (IdxEn)
6659       Offset = 0;
6660     EVT VT = Op.getValueType();
6661     auto *M = cast<MemSDNode>(Op);
6662     M->getMemOperand()->setOffset(Offset);
6663 
6664     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6665                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6666   }
6667   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6668     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6669     SDValue Ops[] = {
6670       Op.getOperand(0), // Chain
6671       Op.getOperand(2), // src
6672       Op.getOperand(3), // cmp
6673       Op.getOperand(4), // rsrc
6674       DAG.getConstant(0, DL, MVT::i32), // vindex
6675       Offsets.first,    // voffset
6676       Op.getOperand(6), // soffset
6677       Offsets.second,   // offset
6678       Op.getOperand(7), // cachepolicy
6679       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6680     };
6681     EVT VT = Op.getValueType();
6682     auto *M = cast<MemSDNode>(Op);
6683     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
6684 
6685     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6686                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6687   }
6688   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6689     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6690     SDValue Ops[] = {
6691       Op.getOperand(0), // Chain
6692       Op.getOperand(2), // src
6693       Op.getOperand(3), // cmp
6694       Op.getOperand(4), // rsrc
6695       Op.getOperand(5), // vindex
6696       Offsets.first,    // voffset
6697       Op.getOperand(7), // soffset
6698       Offsets.second,   // offset
6699       Op.getOperand(8), // cachepolicy
6700       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6701     };
6702     EVT VT = Op.getValueType();
6703     auto *M = cast<MemSDNode>(Op);
6704     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
6705                                                         Ops[4]));
6706 
6707     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6708                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6709   }
6710 
6711   default:
6712     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6713             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6714       return lowerImage(Op, ImageDimIntr, DAG);
6715 
6716     return SDValue();
6717   }
6718 }
6719 
6720 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6721 // dwordx4 if on SI.
6722 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6723                                               SDVTList VTList,
6724                                               ArrayRef<SDValue> Ops, EVT MemVT,
6725                                               MachineMemOperand *MMO,
6726                                               SelectionDAG &DAG) const {
6727   EVT VT = VTList.VTs[0];
6728   EVT WidenedVT = VT;
6729   EVT WidenedMemVT = MemVT;
6730   if (!Subtarget->hasDwordx3LoadStores() &&
6731       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6732     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6733                                  WidenedVT.getVectorElementType(), 4);
6734     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6735                                     WidenedMemVT.getVectorElementType(), 4);
6736     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6737   }
6738 
6739   assert(VTList.NumVTs == 2);
6740   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6741 
6742   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6743                                        WidenedMemVT, MMO);
6744   if (WidenedVT != VT) {
6745     auto Extract = DAG.getNode(
6746         ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6747         DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout())));
6748     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6749   }
6750   return NewOp;
6751 }
6752 
6753 SDValue SITargetLowering::handleD16VData(SDValue VData,
6754                                          SelectionDAG &DAG) const {
6755   EVT StoreVT = VData.getValueType();
6756 
6757   // No change for f16 and legal vector D16 types.
6758   if (!StoreVT.isVector())
6759     return VData;
6760 
6761   SDLoc DL(VData);
6762   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6763 
6764   if (Subtarget->hasUnpackedD16VMem()) {
6765     // We need to unpack the packed data to store.
6766     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6767     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6768 
6769     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6770                                         StoreVT.getVectorNumElements());
6771     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6772     return DAG.UnrollVectorOp(ZExt.getNode());
6773   }
6774 
6775   assert(isTypeLegal(StoreVT));
6776   return VData;
6777 }
6778 
6779 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6780                                               SelectionDAG &DAG) const {
6781   SDLoc DL(Op);
6782   SDValue Chain = Op.getOperand(0);
6783   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6784   MachineFunction &MF = DAG.getMachineFunction();
6785 
6786   switch (IntrinsicID) {
6787   case Intrinsic::amdgcn_exp: {
6788     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6789     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6790     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
6791     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
6792 
6793     const SDValue Ops[] = {
6794       Chain,
6795       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6796       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
6797       Op.getOperand(4), // src0
6798       Op.getOperand(5), // src1
6799       Op.getOperand(6), // src2
6800       Op.getOperand(7), // src3
6801       DAG.getTargetConstant(0, DL, MVT::i1), // compr
6802       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6803     };
6804 
6805     unsigned Opc = Done->isNullValue() ?
6806       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6807     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6808   }
6809   case Intrinsic::amdgcn_exp_compr: {
6810     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6811     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6812     SDValue Src0 = Op.getOperand(4);
6813     SDValue Src1 = Op.getOperand(5);
6814     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6815     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
6816 
6817     SDValue Undef = DAG.getUNDEF(MVT::f32);
6818     const SDValue Ops[] = {
6819       Chain,
6820       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6821       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
6822       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
6823       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
6824       Undef, // src2
6825       Undef, // src3
6826       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6827       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6828     };
6829 
6830     unsigned Opc = Done->isNullValue() ?
6831       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6832     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6833   }
6834   case Intrinsic::amdgcn_s_barrier: {
6835     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6836       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6837       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6838       if (WGSize <= ST.getWavefrontSize())
6839         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6840                                           Op.getOperand(0)), 0);
6841     }
6842     return SDValue();
6843   };
6844   case Intrinsic::amdgcn_tbuffer_store: {
6845     SDValue VData = Op.getOperand(2);
6846     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6847     if (IsD16)
6848       VData = handleD16VData(VData, DAG);
6849     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6850     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6851     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6852     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6853     unsigned IdxEn = 1;
6854     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6855       IdxEn = Idx->getZExtValue() != 0;
6856     SDValue Ops[] = {
6857       Chain,
6858       VData,             // vdata
6859       Op.getOperand(3),  // rsrc
6860       Op.getOperand(4),  // vindex
6861       Op.getOperand(5),  // voffset
6862       Op.getOperand(6),  // soffset
6863       Op.getOperand(7),  // offset
6864       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6865       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6866       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
6867     };
6868     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6869                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6870     MemSDNode *M = cast<MemSDNode>(Op);
6871     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6872                                    M->getMemoryVT(), M->getMemOperand());
6873   }
6874 
6875   case Intrinsic::amdgcn_struct_tbuffer_store: {
6876     SDValue VData = Op.getOperand(2);
6877     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6878     if (IsD16)
6879       VData = handleD16VData(VData, DAG);
6880     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6881     SDValue Ops[] = {
6882       Chain,
6883       VData,             // vdata
6884       Op.getOperand(3),  // rsrc
6885       Op.getOperand(4),  // vindex
6886       Offsets.first,     // voffset
6887       Op.getOperand(6),  // soffset
6888       Offsets.second,    // offset
6889       Op.getOperand(7),  // format
6890       Op.getOperand(8),  // cachepolicy, swizzled buffer
6891       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
6892     };
6893     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6894                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6895     MemSDNode *M = cast<MemSDNode>(Op);
6896     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6897                                    M->getMemoryVT(), M->getMemOperand());
6898   }
6899 
6900   case Intrinsic::amdgcn_raw_tbuffer_store: {
6901     SDValue VData = Op.getOperand(2);
6902     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6903     if (IsD16)
6904       VData = handleD16VData(VData, DAG);
6905     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6906     SDValue Ops[] = {
6907       Chain,
6908       VData,             // vdata
6909       Op.getOperand(3),  // rsrc
6910       DAG.getConstant(0, DL, MVT::i32), // vindex
6911       Offsets.first,     // voffset
6912       Op.getOperand(5),  // soffset
6913       Offsets.second,    // offset
6914       Op.getOperand(6),  // format
6915       Op.getOperand(7),  // cachepolicy, swizzled buffer
6916       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
6917     };
6918     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6919                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6920     MemSDNode *M = cast<MemSDNode>(Op);
6921     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6922                                    M->getMemoryVT(), M->getMemOperand());
6923   }
6924 
6925   case Intrinsic::amdgcn_buffer_store:
6926   case Intrinsic::amdgcn_buffer_store_format: {
6927     SDValue VData = Op.getOperand(2);
6928     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6929     if (IsD16)
6930       VData = handleD16VData(VData, DAG);
6931     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6932     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6933     unsigned IdxEn = 1;
6934     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6935       IdxEn = Idx->getZExtValue() != 0;
6936     SDValue Ops[] = {
6937       Chain,
6938       VData,
6939       Op.getOperand(3), // rsrc
6940       Op.getOperand(4), // vindex
6941       SDValue(), // voffset -- will be set by setBufferOffsets
6942       SDValue(), // soffset -- will be set by setBufferOffsets
6943       SDValue(), // offset -- will be set by setBufferOffsets
6944       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6945       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6946     };
6947     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6948     // We don't know the offset if vindex is non-zero, so clear it.
6949     if (IdxEn)
6950       Offset = 0;
6951     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6952                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6953     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6954     MemSDNode *M = cast<MemSDNode>(Op);
6955     M->getMemOperand()->setOffset(Offset);
6956 
6957     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6958     EVT VDataType = VData.getValueType().getScalarType();
6959     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6960       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6961 
6962     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6963                                    M->getMemoryVT(), M->getMemOperand());
6964   }
6965 
6966   case Intrinsic::amdgcn_raw_buffer_store:
6967   case Intrinsic::amdgcn_raw_buffer_store_format: {
6968     const bool IsFormat =
6969         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
6970 
6971     SDValue VData = Op.getOperand(2);
6972     EVT VDataVT = VData.getValueType();
6973     EVT EltType = VDataVT.getScalarType();
6974     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6975     if (IsD16)
6976       VData = handleD16VData(VData, DAG);
6977 
6978     if (!isTypeLegal(VDataVT)) {
6979       VData =
6980           DAG.getNode(ISD::BITCAST, DL,
6981                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6982     }
6983 
6984     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6985     SDValue Ops[] = {
6986       Chain,
6987       VData,
6988       Op.getOperand(3), // rsrc
6989       DAG.getConstant(0, DL, MVT::i32), // vindex
6990       Offsets.first,    // voffset
6991       Op.getOperand(5), // soffset
6992       Offsets.second,   // offset
6993       Op.getOperand(6), // cachepolicy, swizzled buffer
6994       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6995     };
6996     unsigned Opc =
6997         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
6998     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6999     MemSDNode *M = cast<MemSDNode>(Op);
7000     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7001 
7002     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7003     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7004       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7005 
7006     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7007                                    M->getMemoryVT(), M->getMemOperand());
7008   }
7009 
7010   case Intrinsic::amdgcn_struct_buffer_store:
7011   case Intrinsic::amdgcn_struct_buffer_store_format: {
7012     const bool IsFormat =
7013         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7014 
7015     SDValue VData = Op.getOperand(2);
7016     EVT VDataVT = VData.getValueType();
7017     EVT EltType = VDataVT.getScalarType();
7018     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7019 
7020     if (IsD16)
7021       VData = handleD16VData(VData, DAG);
7022 
7023     if (!isTypeLegal(VDataVT)) {
7024       VData =
7025           DAG.getNode(ISD::BITCAST, DL,
7026                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7027     }
7028 
7029     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7030     SDValue Ops[] = {
7031       Chain,
7032       VData,
7033       Op.getOperand(3), // rsrc
7034       Op.getOperand(4), // vindex
7035       Offsets.first,    // voffset
7036       Op.getOperand(6), // soffset
7037       Offsets.second,   // offset
7038       Op.getOperand(7), // cachepolicy, swizzled buffer
7039       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7040     };
7041     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7042                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7043     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7044     MemSDNode *M = cast<MemSDNode>(Op);
7045     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7046                                                         Ops[3]));
7047 
7048     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7049     EVT VDataType = VData.getValueType().getScalarType();
7050     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7051       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7052 
7053     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7054                                    M->getMemoryVT(), M->getMemOperand());
7055   }
7056 
7057   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7058     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7059     unsigned IdxEn = 1;
7060     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7061       IdxEn = Idx->getZExtValue() != 0;
7062     SDValue Ops[] = {
7063       Chain,
7064       Op.getOperand(2), // vdata
7065       Op.getOperand(3), // rsrc
7066       Op.getOperand(4), // vindex
7067       SDValue(),        // voffset -- will be set by setBufferOffsets
7068       SDValue(),        // soffset -- will be set by setBufferOffsets
7069       SDValue(),        // offset -- will be set by setBufferOffsets
7070       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7071       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7072     };
7073     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7074     // We don't know the offset if vindex is non-zero, so clear it.
7075     if (IdxEn)
7076       Offset = 0;
7077     EVT VT = Op.getOperand(2).getValueType();
7078 
7079     auto *M = cast<MemSDNode>(Op);
7080     M->getMemOperand()->setOffset(Offset);
7081     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7082                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7083 
7084     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7085                                    M->getMemOperand());
7086   }
7087 
7088   case Intrinsic::amdgcn_global_atomic_fadd: {
7089     SDValue Ops[] = {
7090       Chain,
7091       Op.getOperand(2), // ptr
7092       Op.getOperand(3)  // vdata
7093     };
7094     EVT VT = Op.getOperand(3).getValueType();
7095 
7096     auto *M = cast<MemSDNode>(Op);
7097     unsigned Opcode = VT.isVector() ? AMDGPUISD::ATOMIC_PK_FADD
7098                                     : AMDGPUISD::ATOMIC_FADD;
7099 
7100     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7101                                    M->getMemOperand());
7102   }
7103 
7104   case Intrinsic::amdgcn_end_cf:
7105     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7106                                       Op->getOperand(2), Chain), 0);
7107 
7108   default: {
7109     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7110             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7111       return lowerImage(Op, ImageDimIntr, DAG);
7112 
7113     return Op;
7114   }
7115   }
7116 }
7117 
7118 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7119 // offset (the offset that is included in bounds checking and swizzling, to be
7120 // split between the instruction's voffset and immoffset fields) and soffset
7121 // (the offset that is excluded from bounds checking and swizzling, to go in
7122 // the instruction's soffset field).  This function takes the first kind of
7123 // offset and figures out how to split it between voffset and immoffset.
7124 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7125     SDValue Offset, SelectionDAG &DAG) const {
7126   SDLoc DL(Offset);
7127   const unsigned MaxImm = 4095;
7128   SDValue N0 = Offset;
7129   ConstantSDNode *C1 = nullptr;
7130 
7131   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7132     N0 = SDValue();
7133   else if (DAG.isBaseWithConstantOffset(N0)) {
7134     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7135     N0 = N0.getOperand(0);
7136   }
7137 
7138   if (C1) {
7139     unsigned ImmOffset = C1->getZExtValue();
7140     // If the immediate value is too big for the immoffset field, put the value
7141     // and -4096 into the immoffset field so that the value that is copied/added
7142     // for the voffset field is a multiple of 4096, and it stands more chance
7143     // of being CSEd with the copy/add for another similar load/store.
7144     // However, do not do that rounding down to a multiple of 4096 if that is a
7145     // negative number, as it appears to be illegal to have a negative offset
7146     // in the vgpr, even if adding the immediate offset makes it positive.
7147     unsigned Overflow = ImmOffset & ~MaxImm;
7148     ImmOffset -= Overflow;
7149     if ((int32_t)Overflow < 0) {
7150       Overflow += ImmOffset;
7151       ImmOffset = 0;
7152     }
7153     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7154     if (Overflow) {
7155       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7156       if (!N0)
7157         N0 = OverflowVal;
7158       else {
7159         SDValue Ops[] = { N0, OverflowVal };
7160         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7161       }
7162     }
7163   }
7164   if (!N0)
7165     N0 = DAG.getConstant(0, DL, MVT::i32);
7166   if (!C1)
7167     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7168   return {N0, SDValue(C1, 0)};
7169 }
7170 
7171 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7172 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7173 // pointed to by Offsets.
7174 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7175                                         SelectionDAG &DAG, SDValue *Offsets,
7176                                         unsigned Align) const {
7177   SDLoc DL(CombinedOffset);
7178   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7179     uint32_t Imm = C->getZExtValue();
7180     uint32_t SOffset, ImmOffset;
7181     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7182       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7183       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7184       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7185       return SOffset + ImmOffset;
7186     }
7187   }
7188   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7189     SDValue N0 = CombinedOffset.getOperand(0);
7190     SDValue N1 = CombinedOffset.getOperand(1);
7191     uint32_t SOffset, ImmOffset;
7192     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7193     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7194                                                 Subtarget, Align)) {
7195       Offsets[0] = N0;
7196       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7197       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7198       return 0;
7199     }
7200   }
7201   Offsets[0] = CombinedOffset;
7202   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7203   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7204   return 0;
7205 }
7206 
7207 // Handle 8 bit and 16 bit buffer loads
7208 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7209                                                      EVT LoadVT, SDLoc DL,
7210                                                      ArrayRef<SDValue> Ops,
7211                                                      MemSDNode *M) const {
7212   EVT IntVT = LoadVT.changeTypeToInteger();
7213   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7214          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7215 
7216   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7217   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7218                                                Ops, IntVT,
7219                                                M->getMemOperand());
7220   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7221   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7222 
7223   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7224 }
7225 
7226 // Handle 8 bit and 16 bit buffer stores
7227 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7228                                                       EVT VDataType, SDLoc DL,
7229                                                       SDValue Ops[],
7230                                                       MemSDNode *M) const {
7231   if (VDataType == MVT::f16)
7232     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7233 
7234   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7235   Ops[1] = BufferStoreExt;
7236   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7237                                  AMDGPUISD::BUFFER_STORE_SHORT;
7238   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7239   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7240                                      M->getMemOperand());
7241 }
7242 
7243 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7244                                  ISD::LoadExtType ExtType, SDValue Op,
7245                                  const SDLoc &SL, EVT VT) {
7246   if (VT.bitsLT(Op.getValueType()))
7247     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7248 
7249   switch (ExtType) {
7250   case ISD::SEXTLOAD:
7251     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7252   case ISD::ZEXTLOAD:
7253     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7254   case ISD::EXTLOAD:
7255     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7256   case ISD::NON_EXTLOAD:
7257     return Op;
7258   }
7259 
7260   llvm_unreachable("invalid ext type");
7261 }
7262 
7263 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7264   SelectionDAG &DAG = DCI.DAG;
7265   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7266     return SDValue();
7267 
7268   // FIXME: Constant loads should all be marked invariant.
7269   unsigned AS = Ld->getAddressSpace();
7270   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7271       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7272       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7273     return SDValue();
7274 
7275   // Don't do this early, since it may interfere with adjacent load merging for
7276   // illegal types. We can avoid losing alignment information for exotic types
7277   // pre-legalize.
7278   EVT MemVT = Ld->getMemoryVT();
7279   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7280       MemVT.getSizeInBits() >= 32)
7281     return SDValue();
7282 
7283   SDLoc SL(Ld);
7284 
7285   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7286          "unexpected vector extload");
7287 
7288   // TODO: Drop only high part of range.
7289   SDValue Ptr = Ld->getBasePtr();
7290   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7291                                 MVT::i32, SL, Ld->getChain(), Ptr,
7292                                 Ld->getOffset(),
7293                                 Ld->getPointerInfo(), MVT::i32,
7294                                 Ld->getAlignment(),
7295                                 Ld->getMemOperand()->getFlags(),
7296                                 Ld->getAAInfo(),
7297                                 nullptr); // Drop ranges
7298 
7299   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7300   if (MemVT.isFloatingPoint()) {
7301     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7302            "unexpected fp extload");
7303     TruncVT = MemVT.changeTypeToInteger();
7304   }
7305 
7306   SDValue Cvt = NewLoad;
7307   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7308     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7309                       DAG.getValueType(TruncVT));
7310   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7311              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7312     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7313   } else {
7314     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7315   }
7316 
7317   EVT VT = Ld->getValueType(0);
7318   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7319 
7320   DCI.AddToWorklist(Cvt.getNode());
7321 
7322   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7323   // the appropriate extension from the 32-bit load.
7324   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7325   DCI.AddToWorklist(Cvt.getNode());
7326 
7327   // Handle conversion back to floating point if necessary.
7328   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7329 
7330   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7331 }
7332 
7333 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7334   SDLoc DL(Op);
7335   LoadSDNode *Load = cast<LoadSDNode>(Op);
7336   ISD::LoadExtType ExtType = Load->getExtensionType();
7337   EVT MemVT = Load->getMemoryVT();
7338 
7339   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7340     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7341       return SDValue();
7342 
7343     // FIXME: Copied from PPC
7344     // First, load into 32 bits, then truncate to 1 bit.
7345 
7346     SDValue Chain = Load->getChain();
7347     SDValue BasePtr = Load->getBasePtr();
7348     MachineMemOperand *MMO = Load->getMemOperand();
7349 
7350     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7351 
7352     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7353                                    BasePtr, RealMemVT, MMO);
7354 
7355     if (!MemVT.isVector()) {
7356       SDValue Ops[] = {
7357         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7358         NewLD.getValue(1)
7359       };
7360 
7361       return DAG.getMergeValues(Ops, DL);
7362     }
7363 
7364     SmallVector<SDValue, 3> Elts;
7365     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7366       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7367                                 DAG.getConstant(I, DL, MVT::i32));
7368 
7369       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7370     }
7371 
7372     SDValue Ops[] = {
7373       DAG.getBuildVector(MemVT, DL, Elts),
7374       NewLD.getValue(1)
7375     };
7376 
7377     return DAG.getMergeValues(Ops, DL);
7378   }
7379 
7380   if (!MemVT.isVector())
7381     return SDValue();
7382 
7383   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7384          "Custom lowering for non-i32 vectors hasn't been implemented.");
7385 
7386   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7387                                       MemVT, *Load->getMemOperand())) {
7388     SDValue Ops[2];
7389     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7390     return DAG.getMergeValues(Ops, DL);
7391   }
7392 
7393   unsigned Alignment = Load->getAlignment();
7394   unsigned AS = Load->getAddressSpace();
7395   if (Subtarget->hasLDSMisalignedBug() &&
7396       AS == AMDGPUAS::FLAT_ADDRESS &&
7397       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7398     return SplitVectorLoad(Op, DAG);
7399   }
7400 
7401   MachineFunction &MF = DAG.getMachineFunction();
7402   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7403   // If there is a possibilty that flat instruction access scratch memory
7404   // then we need to use the same legalization rules we use for private.
7405   if (AS == AMDGPUAS::FLAT_ADDRESS)
7406     AS = MFI->hasFlatScratchInit() ?
7407          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7408 
7409   unsigned NumElements = MemVT.getVectorNumElements();
7410 
7411   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7412       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7413     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7414       if (MemVT.isPow2VectorType())
7415         return SDValue();
7416       if (NumElements == 3)
7417         return WidenVectorLoad(Op, DAG);
7418       return SplitVectorLoad(Op, DAG);
7419     }
7420     // Non-uniform loads will be selected to MUBUF instructions, so they
7421     // have the same legalization requirements as global and private
7422     // loads.
7423     //
7424   }
7425 
7426   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7427       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7428       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7429     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7430         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7431         Alignment >= 4 && NumElements < 32) {
7432       if (MemVT.isPow2VectorType())
7433         return SDValue();
7434       if (NumElements == 3)
7435         return WidenVectorLoad(Op, DAG);
7436       return SplitVectorLoad(Op, DAG);
7437     }
7438     // Non-uniform loads will be selected to MUBUF instructions, so they
7439     // have the same legalization requirements as global and private
7440     // loads.
7441     //
7442   }
7443   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7444       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7445       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7446       AS == AMDGPUAS::FLAT_ADDRESS) {
7447     if (NumElements > 4)
7448       return SplitVectorLoad(Op, DAG);
7449     // v3 loads not supported on SI.
7450     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7451       return WidenVectorLoad(Op, DAG);
7452     // v3 and v4 loads are supported for private and global memory.
7453     return SDValue();
7454   }
7455   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7456     // Depending on the setting of the private_element_size field in the
7457     // resource descriptor, we can only make private accesses up to a certain
7458     // size.
7459     switch (Subtarget->getMaxPrivateElementSize()) {
7460     case 4:
7461       return scalarizeVectorLoad(Load, DAG);
7462     case 8:
7463       if (NumElements > 2)
7464         return SplitVectorLoad(Op, DAG);
7465       return SDValue();
7466     case 16:
7467       // Same as global/flat
7468       if (NumElements > 4)
7469         return SplitVectorLoad(Op, DAG);
7470       // v3 loads not supported on SI.
7471       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7472         return WidenVectorLoad(Op, DAG);
7473       return SDValue();
7474     default:
7475       llvm_unreachable("unsupported private_element_size");
7476     }
7477   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7478     // Use ds_read_b128 if possible.
7479     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7480         MemVT.getStoreSize() == 16)
7481       return SDValue();
7482 
7483     if (NumElements > 2)
7484       return SplitVectorLoad(Op, DAG);
7485 
7486     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7487     // address is negative, then the instruction is incorrectly treated as
7488     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7489     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7490     // load later in the SILoadStoreOptimizer.
7491     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7492         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7493         Load->getAlignment() < 8) {
7494       return SplitVectorLoad(Op, DAG);
7495     }
7496   }
7497   return SDValue();
7498 }
7499 
7500 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7501   EVT VT = Op.getValueType();
7502   assert(VT.getSizeInBits() == 64);
7503 
7504   SDLoc DL(Op);
7505   SDValue Cond = Op.getOperand(0);
7506 
7507   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7508   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7509 
7510   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7511   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7512 
7513   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7514   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7515 
7516   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7517 
7518   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7519   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7520 
7521   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7522 
7523   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7524   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7525 }
7526 
7527 // Catch division cases where we can use shortcuts with rcp and rsq
7528 // instructions.
7529 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7530                                               SelectionDAG &DAG) const {
7531   SDLoc SL(Op);
7532   SDValue LHS = Op.getOperand(0);
7533   SDValue RHS = Op.getOperand(1);
7534   EVT VT = Op.getValueType();
7535   const SDNodeFlags Flags = Op->getFlags();
7536   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
7537 
7538   if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
7539     return SDValue();
7540 
7541   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7542     if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
7543       if (CLHS->isExactlyValue(1.0)) {
7544         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7545         // the CI documentation has a worst case error of 1 ulp.
7546         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7547         // use it as long as we aren't trying to use denormals.
7548         //
7549         // v_rcp_f16 and v_rsq_f16 DO support denormals.
7550 
7551         // 1.0 / sqrt(x) -> rsq(x)
7552 
7553         // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7554         // error seems really high at 2^29 ULP.
7555         if (RHS.getOpcode() == ISD::FSQRT)
7556           return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7557 
7558         // 1.0 / x -> rcp(x)
7559         return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7560       }
7561 
7562       // Same as for 1.0, but expand the sign out of the constant.
7563       if (CLHS->isExactlyValue(-1.0)) {
7564         // -1.0 / x -> rcp (fneg x)
7565         SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7566         return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7567       }
7568     }
7569   }
7570 
7571   if (Unsafe) {
7572     // Turn into multiply by the reciprocal.
7573     // x / y -> x * (1.0 / y)
7574     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7575     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7576   }
7577 
7578   return SDValue();
7579 }
7580 
7581 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7582                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7583   if (GlueChain->getNumValues() <= 1) {
7584     return DAG.getNode(Opcode, SL, VT, A, B);
7585   }
7586 
7587   assert(GlueChain->getNumValues() == 3);
7588 
7589   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7590   switch (Opcode) {
7591   default: llvm_unreachable("no chain equivalent for opcode");
7592   case ISD::FMUL:
7593     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7594     break;
7595   }
7596 
7597   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7598                      GlueChain.getValue(2));
7599 }
7600 
7601 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7602                            EVT VT, SDValue A, SDValue B, SDValue C,
7603                            SDValue GlueChain) {
7604   if (GlueChain->getNumValues() <= 1) {
7605     return DAG.getNode(Opcode, SL, VT, A, B, C);
7606   }
7607 
7608   assert(GlueChain->getNumValues() == 3);
7609 
7610   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7611   switch (Opcode) {
7612   default: llvm_unreachable("no chain equivalent for opcode");
7613   case ISD::FMA:
7614     Opcode = AMDGPUISD::FMA_W_CHAIN;
7615     break;
7616   }
7617 
7618   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7619                      GlueChain.getValue(2));
7620 }
7621 
7622 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7623   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7624     return FastLowered;
7625 
7626   SDLoc SL(Op);
7627   SDValue Src0 = Op.getOperand(0);
7628   SDValue Src1 = Op.getOperand(1);
7629 
7630   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7631   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7632 
7633   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7634   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7635 
7636   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7637   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7638 
7639   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7640 }
7641 
7642 // Faster 2.5 ULP division that does not support denormals.
7643 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7644   SDLoc SL(Op);
7645   SDValue LHS = Op.getOperand(1);
7646   SDValue RHS = Op.getOperand(2);
7647 
7648   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7649 
7650   const APFloat K0Val(BitsToFloat(0x6f800000));
7651   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7652 
7653   const APFloat K1Val(BitsToFloat(0x2f800000));
7654   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7655 
7656   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7657 
7658   EVT SetCCVT =
7659     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7660 
7661   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7662 
7663   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7664 
7665   // TODO: Should this propagate fast-math-flags?
7666   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7667 
7668   // rcp does not support denormals.
7669   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7670 
7671   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7672 
7673   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7674 }
7675 
7676 // Returns immediate value for setting the F32 denorm mode when using the
7677 // S_DENORM_MODE instruction.
7678 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7679                                           const SDLoc &SL, const GCNSubtarget *ST) {
7680   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7681   int DPDenormModeDefault = ST->hasFP64Denormals()
7682                                 ? FP_DENORM_FLUSH_NONE
7683                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7684 
7685   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7686   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7687 }
7688 
7689 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7690   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7691     return FastLowered;
7692 
7693   SDLoc SL(Op);
7694   SDValue LHS = Op.getOperand(0);
7695   SDValue RHS = Op.getOperand(1);
7696 
7697   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7698 
7699   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7700 
7701   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7702                                           RHS, RHS, LHS);
7703   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7704                                         LHS, RHS, LHS);
7705 
7706   // Denominator is scaled to not be denormal, so using rcp is ok.
7707   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7708                                   DenominatorScaled);
7709   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7710                                      DenominatorScaled);
7711 
7712   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7713                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7714                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7715   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7716 
7717   if (!Subtarget->hasFP32Denormals()) {
7718     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7719 
7720     SDValue EnableDenorm;
7721     if (Subtarget->hasDenormModeInst()) {
7722       const SDValue EnableDenormValue =
7723           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7724 
7725       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7726                                  DAG.getEntryNode(), EnableDenormValue);
7727     } else {
7728       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7729                                                         SL, MVT::i32);
7730       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7731                                  DAG.getEntryNode(), EnableDenormValue,
7732                                  BitField);
7733     }
7734 
7735     SDValue Ops[3] = {
7736       NegDivScale0,
7737       EnableDenorm.getValue(0),
7738       EnableDenorm.getValue(1)
7739     };
7740 
7741     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7742   }
7743 
7744   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7745                              ApproxRcp, One, NegDivScale0);
7746 
7747   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7748                              ApproxRcp, Fma0);
7749 
7750   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7751                            Fma1, Fma1);
7752 
7753   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7754                              NumeratorScaled, Mul);
7755 
7756   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7757 
7758   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7759                              NumeratorScaled, Fma3);
7760 
7761   if (!Subtarget->hasFP32Denormals()) {
7762 
7763     SDValue DisableDenorm;
7764     if (Subtarget->hasDenormModeInst()) {
7765       const SDValue DisableDenormValue =
7766           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7767 
7768       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7769                                   Fma4.getValue(1), DisableDenormValue,
7770                                   Fma4.getValue(2));
7771     } else {
7772       const SDValue DisableDenormValue =
7773           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7774 
7775       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7776                                   Fma4.getValue(1), DisableDenormValue,
7777                                   BitField, Fma4.getValue(2));
7778     }
7779 
7780     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7781                                       DisableDenorm, DAG.getRoot());
7782     DAG.setRoot(OutputChain);
7783   }
7784 
7785   SDValue Scale = NumeratorScaled.getValue(1);
7786   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7787                              Fma4, Fma1, Fma3, Scale);
7788 
7789   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7790 }
7791 
7792 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7793   if (DAG.getTarget().Options.UnsafeFPMath)
7794     return lowerFastUnsafeFDIV(Op, DAG);
7795 
7796   SDLoc SL(Op);
7797   SDValue X = Op.getOperand(0);
7798   SDValue Y = Op.getOperand(1);
7799 
7800   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7801 
7802   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7803 
7804   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7805 
7806   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7807 
7808   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7809 
7810   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7811 
7812   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7813 
7814   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7815 
7816   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7817 
7818   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7819   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7820 
7821   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7822                              NegDivScale0, Mul, DivScale1);
7823 
7824   SDValue Scale;
7825 
7826   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
7827     // Workaround a hardware bug on SI where the condition output from div_scale
7828     // is not usable.
7829 
7830     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7831 
7832     // Figure out if the scale to use for div_fmas.
7833     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7834     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7835     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7836     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7837 
7838     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7839     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7840 
7841     SDValue Scale0Hi
7842       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7843     SDValue Scale1Hi
7844       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7845 
7846     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7847     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7848     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7849   } else {
7850     Scale = DivScale1.getValue(1);
7851   }
7852 
7853   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7854                              Fma4, Fma3, Mul, Scale);
7855 
7856   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7857 }
7858 
7859 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7860   EVT VT = Op.getValueType();
7861 
7862   if (VT == MVT::f32)
7863     return LowerFDIV32(Op, DAG);
7864 
7865   if (VT == MVT::f64)
7866     return LowerFDIV64(Op, DAG);
7867 
7868   if (VT == MVT::f16)
7869     return LowerFDIV16(Op, DAG);
7870 
7871   llvm_unreachable("Unexpected type for fdiv");
7872 }
7873 
7874 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7875   SDLoc DL(Op);
7876   StoreSDNode *Store = cast<StoreSDNode>(Op);
7877   EVT VT = Store->getMemoryVT();
7878 
7879   if (VT == MVT::i1) {
7880     return DAG.getTruncStore(Store->getChain(), DL,
7881        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7882        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
7883   }
7884 
7885   assert(VT.isVector() &&
7886          Store->getValue().getValueType().getScalarType() == MVT::i32);
7887 
7888   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7889                                       VT, *Store->getMemOperand())) {
7890     return expandUnalignedStore(Store, DAG);
7891   }
7892 
7893   unsigned AS = Store->getAddressSpace();
7894   if (Subtarget->hasLDSMisalignedBug() &&
7895       AS == AMDGPUAS::FLAT_ADDRESS &&
7896       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7897     return SplitVectorStore(Op, DAG);
7898   }
7899 
7900   MachineFunction &MF = DAG.getMachineFunction();
7901   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7902   // If there is a possibilty that flat instruction access scratch memory
7903   // then we need to use the same legalization rules we use for private.
7904   if (AS == AMDGPUAS::FLAT_ADDRESS)
7905     AS = MFI->hasFlatScratchInit() ?
7906          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7907 
7908   unsigned NumElements = VT.getVectorNumElements();
7909   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7910       AS == AMDGPUAS::FLAT_ADDRESS) {
7911     if (NumElements > 4)
7912       return SplitVectorStore(Op, DAG);
7913     // v3 stores not supported on SI.
7914     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7915       return SplitVectorStore(Op, DAG);
7916     return SDValue();
7917   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7918     switch (Subtarget->getMaxPrivateElementSize()) {
7919     case 4:
7920       return scalarizeVectorStore(Store, DAG);
7921     case 8:
7922       if (NumElements > 2)
7923         return SplitVectorStore(Op, DAG);
7924       return SDValue();
7925     case 16:
7926       if (NumElements > 4 || NumElements == 3)
7927         return SplitVectorStore(Op, DAG);
7928       return SDValue();
7929     default:
7930       llvm_unreachable("unsupported private_element_size");
7931     }
7932   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7933     // Use ds_write_b128 if possible.
7934     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
7935         VT.getStoreSize() == 16 && NumElements != 3)
7936       return SDValue();
7937 
7938     if (NumElements > 2)
7939       return SplitVectorStore(Op, DAG);
7940 
7941     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7942     // address is negative, then the instruction is incorrectly treated as
7943     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7944     // stores here to avoid emitting ds_write2_b32. We may re-combine the
7945     // store later in the SILoadStoreOptimizer.
7946     if (!Subtarget->hasUsableDSOffset() &&
7947         NumElements == 2 && VT.getStoreSize() == 8 &&
7948         Store->getAlignment() < 8) {
7949       return SplitVectorStore(Op, DAG);
7950     }
7951 
7952     return SDValue();
7953   } else {
7954     llvm_unreachable("unhandled address space");
7955   }
7956 }
7957 
7958 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
7959   SDLoc DL(Op);
7960   EVT VT = Op.getValueType();
7961   SDValue Arg = Op.getOperand(0);
7962   SDValue TrigVal;
7963 
7964   // TODO: Should this propagate fast-math-flags?
7965 
7966   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7967 
7968   if (Subtarget->hasTrigReducedRange()) {
7969     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7970     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7971   } else {
7972     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7973   }
7974 
7975   switch (Op.getOpcode()) {
7976   case ISD::FCOS:
7977     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7978   case ISD::FSIN:
7979     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7980   default:
7981     llvm_unreachable("Wrong trig opcode");
7982   }
7983 }
7984 
7985 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7986   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7987   assert(AtomicNode->isCompareAndSwap());
7988   unsigned AS = AtomicNode->getAddressSpace();
7989 
7990   // No custom lowering required for local address space
7991   if (!isFlatGlobalAddrSpace(AS))
7992     return Op;
7993 
7994   // Non-local address space requires custom lowering for atomic compare
7995   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
7996   SDLoc DL(Op);
7997   SDValue ChainIn = Op.getOperand(0);
7998   SDValue Addr = Op.getOperand(1);
7999   SDValue Old = Op.getOperand(2);
8000   SDValue New = Op.getOperand(3);
8001   EVT VT = Op.getValueType();
8002   MVT SimpleVT = VT.getSimpleVT();
8003   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8004 
8005   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8006   SDValue Ops[] = { ChainIn, Addr, NewOld };
8007 
8008   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8009                                  Ops, VT, AtomicNode->getMemOperand());
8010 }
8011 
8012 //===----------------------------------------------------------------------===//
8013 // Custom DAG optimizations
8014 //===----------------------------------------------------------------------===//
8015 
8016 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8017                                                      DAGCombinerInfo &DCI) const {
8018   EVT VT = N->getValueType(0);
8019   EVT ScalarVT = VT.getScalarType();
8020   if (ScalarVT != MVT::f32)
8021     return SDValue();
8022 
8023   SelectionDAG &DAG = DCI.DAG;
8024   SDLoc DL(N);
8025 
8026   SDValue Src = N->getOperand(0);
8027   EVT SrcVT = Src.getValueType();
8028 
8029   // TODO: We could try to match extracting the higher bytes, which would be
8030   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8031   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8032   // about in practice.
8033   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8034     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8035       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
8036       DCI.AddToWorklist(Cvt.getNode());
8037       return Cvt;
8038     }
8039   }
8040 
8041   return SDValue();
8042 }
8043 
8044 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8045 
8046 // This is a variant of
8047 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8048 //
8049 // The normal DAG combiner will do this, but only if the add has one use since
8050 // that would increase the number of instructions.
8051 //
8052 // This prevents us from seeing a constant offset that can be folded into a
8053 // memory instruction's addressing mode. If we know the resulting add offset of
8054 // a pointer can be folded into an addressing offset, we can replace the pointer
8055 // operand with the add of new constant offset. This eliminates one of the uses,
8056 // and may allow the remaining use to also be simplified.
8057 //
8058 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8059                                                unsigned AddrSpace,
8060                                                EVT MemVT,
8061                                                DAGCombinerInfo &DCI) const {
8062   SDValue N0 = N->getOperand(0);
8063   SDValue N1 = N->getOperand(1);
8064 
8065   // We only do this to handle cases where it's profitable when there are
8066   // multiple uses of the add, so defer to the standard combine.
8067   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8068       N0->hasOneUse())
8069     return SDValue();
8070 
8071   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8072   if (!CN1)
8073     return SDValue();
8074 
8075   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8076   if (!CAdd)
8077     return SDValue();
8078 
8079   // If the resulting offset is too large, we can't fold it into the addressing
8080   // mode offset.
8081   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8082   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8083 
8084   AddrMode AM;
8085   AM.HasBaseReg = true;
8086   AM.BaseOffs = Offset.getSExtValue();
8087   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8088     return SDValue();
8089 
8090   SelectionDAG &DAG = DCI.DAG;
8091   SDLoc SL(N);
8092   EVT VT = N->getValueType(0);
8093 
8094   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8095   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8096 
8097   SDNodeFlags Flags;
8098   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8099                           (N0.getOpcode() == ISD::OR ||
8100                            N0->getFlags().hasNoUnsignedWrap()));
8101 
8102   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8103 }
8104 
8105 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8106                                                   DAGCombinerInfo &DCI) const {
8107   SDValue Ptr = N->getBasePtr();
8108   SelectionDAG &DAG = DCI.DAG;
8109   SDLoc SL(N);
8110 
8111   // TODO: We could also do this for multiplies.
8112   if (Ptr.getOpcode() == ISD::SHL) {
8113     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8114                                           N->getMemoryVT(), DCI);
8115     if (NewPtr) {
8116       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8117 
8118       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8119       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8120     }
8121   }
8122 
8123   return SDValue();
8124 }
8125 
8126 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8127   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8128          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8129          (Opc == ISD::XOR && Val == 0);
8130 }
8131 
8132 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8133 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8134 // integer combine opportunities since most 64-bit operations are decomposed
8135 // this way.  TODO: We won't want this for SALU especially if it is an inline
8136 // immediate.
8137 SDValue SITargetLowering::splitBinaryBitConstantOp(
8138   DAGCombinerInfo &DCI,
8139   const SDLoc &SL,
8140   unsigned Opc, SDValue LHS,
8141   const ConstantSDNode *CRHS) const {
8142   uint64_t Val = CRHS->getZExtValue();
8143   uint32_t ValLo = Lo_32(Val);
8144   uint32_t ValHi = Hi_32(Val);
8145   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8146 
8147     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8148          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8149         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8150     // If we need to materialize a 64-bit immediate, it will be split up later
8151     // anyway. Avoid creating the harder to understand 64-bit immediate
8152     // materialization.
8153     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8154   }
8155 
8156   return SDValue();
8157 }
8158 
8159 // Returns true if argument is a boolean value which is not serialized into
8160 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8161 static bool isBoolSGPR(SDValue V) {
8162   if (V.getValueType() != MVT::i1)
8163     return false;
8164   switch (V.getOpcode()) {
8165   default: break;
8166   case ISD::SETCC:
8167   case ISD::AND:
8168   case ISD::OR:
8169   case ISD::XOR:
8170   case AMDGPUISD::FP_CLASS:
8171     return true;
8172   }
8173   return false;
8174 }
8175 
8176 // If a constant has all zeroes or all ones within each byte return it.
8177 // Otherwise return 0.
8178 static uint32_t getConstantPermuteMask(uint32_t C) {
8179   // 0xff for any zero byte in the mask
8180   uint32_t ZeroByteMask = 0;
8181   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8182   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8183   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8184   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8185   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8186   if ((NonZeroByteMask & C) != NonZeroByteMask)
8187     return 0; // Partial bytes selected.
8188   return C;
8189 }
8190 
8191 // Check if a node selects whole bytes from its operand 0 starting at a byte
8192 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8193 // or -1 if not succeeded.
8194 // Note byte select encoding:
8195 // value 0-3 selects corresponding source byte;
8196 // value 0xc selects zero;
8197 // value 0xff selects 0xff.
8198 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8199   assert(V.getValueSizeInBits() == 32);
8200 
8201   if (V.getNumOperands() != 2)
8202     return ~0;
8203 
8204   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8205   if (!N1)
8206     return ~0;
8207 
8208   uint32_t C = N1->getZExtValue();
8209 
8210   switch (V.getOpcode()) {
8211   default:
8212     break;
8213   case ISD::AND:
8214     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8215       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8216     }
8217     break;
8218 
8219   case ISD::OR:
8220     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8221       return (0x03020100 & ~ConstMask) | ConstMask;
8222     }
8223     break;
8224 
8225   case ISD::SHL:
8226     if (C % 8)
8227       return ~0;
8228 
8229     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8230 
8231   case ISD::SRL:
8232     if (C % 8)
8233       return ~0;
8234 
8235     return uint32_t(0x0c0c0c0c03020100ull >> C);
8236   }
8237 
8238   return ~0;
8239 }
8240 
8241 SDValue SITargetLowering::performAndCombine(SDNode *N,
8242                                             DAGCombinerInfo &DCI) const {
8243   if (DCI.isBeforeLegalize())
8244     return SDValue();
8245 
8246   SelectionDAG &DAG = DCI.DAG;
8247   EVT VT = N->getValueType(0);
8248   SDValue LHS = N->getOperand(0);
8249   SDValue RHS = N->getOperand(1);
8250 
8251 
8252   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8253   if (VT == MVT::i64 && CRHS) {
8254     if (SDValue Split
8255         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8256       return Split;
8257   }
8258 
8259   if (CRHS && VT == MVT::i32) {
8260     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8261     // nb = number of trailing zeroes in mask
8262     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8263     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8264     uint64_t Mask = CRHS->getZExtValue();
8265     unsigned Bits = countPopulation(Mask);
8266     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8267         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8268       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8269         unsigned Shift = CShift->getZExtValue();
8270         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8271         unsigned Offset = NB + Shift;
8272         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8273           SDLoc SL(N);
8274           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8275                                     LHS->getOperand(0),
8276                                     DAG.getConstant(Offset, SL, MVT::i32),
8277                                     DAG.getConstant(Bits, SL, MVT::i32));
8278           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8279           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8280                                     DAG.getValueType(NarrowVT));
8281           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8282                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8283           return Shl;
8284         }
8285       }
8286     }
8287 
8288     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8289     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8290         isa<ConstantSDNode>(LHS.getOperand(2))) {
8291       uint32_t Sel = getConstantPermuteMask(Mask);
8292       if (!Sel)
8293         return SDValue();
8294 
8295       // Select 0xc for all zero bytes
8296       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8297       SDLoc DL(N);
8298       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8299                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8300     }
8301   }
8302 
8303   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8304   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8305   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8306     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8307     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8308 
8309     SDValue X = LHS.getOperand(0);
8310     SDValue Y = RHS.getOperand(0);
8311     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8312       return SDValue();
8313 
8314     if (LCC == ISD::SETO) {
8315       if (X != LHS.getOperand(1))
8316         return SDValue();
8317 
8318       if (RCC == ISD::SETUNE) {
8319         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8320         if (!C1 || !C1->isInfinity() || C1->isNegative())
8321           return SDValue();
8322 
8323         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8324                               SIInstrFlags::N_SUBNORMAL |
8325                               SIInstrFlags::N_ZERO |
8326                               SIInstrFlags::P_ZERO |
8327                               SIInstrFlags::P_SUBNORMAL |
8328                               SIInstrFlags::P_NORMAL;
8329 
8330         static_assert(((~(SIInstrFlags::S_NAN |
8331                           SIInstrFlags::Q_NAN |
8332                           SIInstrFlags::N_INFINITY |
8333                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8334                       "mask not equal");
8335 
8336         SDLoc DL(N);
8337         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8338                            X, DAG.getConstant(Mask, DL, MVT::i32));
8339       }
8340     }
8341   }
8342 
8343   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8344     std::swap(LHS, RHS);
8345 
8346   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8347       RHS.hasOneUse()) {
8348     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8349     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8350     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8351     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8352     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8353         (RHS.getOperand(0) == LHS.getOperand(0) &&
8354          LHS.getOperand(0) == LHS.getOperand(1))) {
8355       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8356       unsigned NewMask = LCC == ISD::SETO ?
8357         Mask->getZExtValue() & ~OrdMask :
8358         Mask->getZExtValue() & OrdMask;
8359 
8360       SDLoc DL(N);
8361       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8362                          DAG.getConstant(NewMask, DL, MVT::i32));
8363     }
8364   }
8365 
8366   if (VT == MVT::i32 &&
8367       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8368     // and x, (sext cc from i1) => select cc, x, 0
8369     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8370       std::swap(LHS, RHS);
8371     if (isBoolSGPR(RHS.getOperand(0)))
8372       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8373                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8374   }
8375 
8376   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8377   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8378   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8379       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8380     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8381     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8382     if (LHSMask != ~0u && RHSMask != ~0u) {
8383       // Canonicalize the expression in an attempt to have fewer unique masks
8384       // and therefore fewer registers used to hold the masks.
8385       if (LHSMask > RHSMask) {
8386         std::swap(LHSMask, RHSMask);
8387         std::swap(LHS, RHS);
8388       }
8389 
8390       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8391       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8392       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8393       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8394 
8395       // Check of we need to combine values from two sources within a byte.
8396       if (!(LHSUsedLanes & RHSUsedLanes) &&
8397           // If we select high and lower word keep it for SDWA.
8398           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8399           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8400         // Each byte in each mask is either selector mask 0-3, or has higher
8401         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8402         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8403         // mask which is not 0xff wins. By anding both masks we have a correct
8404         // result except that 0x0c shall be corrected to give 0x0c only.
8405         uint32_t Mask = LHSMask & RHSMask;
8406         for (unsigned I = 0; I < 32; I += 8) {
8407           uint32_t ByteSel = 0xff << I;
8408           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8409             Mask &= (0x0c << I) & 0xffffffff;
8410         }
8411 
8412         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8413         // or 0x0c.
8414         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8415         SDLoc DL(N);
8416 
8417         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8418                            LHS.getOperand(0), RHS.getOperand(0),
8419                            DAG.getConstant(Sel, DL, MVT::i32));
8420       }
8421     }
8422   }
8423 
8424   return SDValue();
8425 }
8426 
8427 SDValue SITargetLowering::performOrCombine(SDNode *N,
8428                                            DAGCombinerInfo &DCI) const {
8429   SelectionDAG &DAG = DCI.DAG;
8430   SDValue LHS = N->getOperand(0);
8431   SDValue RHS = N->getOperand(1);
8432 
8433   EVT VT = N->getValueType(0);
8434   if (VT == MVT::i1) {
8435     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8436     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8437         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8438       SDValue Src = LHS.getOperand(0);
8439       if (Src != RHS.getOperand(0))
8440         return SDValue();
8441 
8442       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8443       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8444       if (!CLHS || !CRHS)
8445         return SDValue();
8446 
8447       // Only 10 bits are used.
8448       static const uint32_t MaxMask = 0x3ff;
8449 
8450       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8451       SDLoc DL(N);
8452       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8453                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8454     }
8455 
8456     return SDValue();
8457   }
8458 
8459   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8460   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8461       LHS.getOpcode() == AMDGPUISD::PERM &&
8462       isa<ConstantSDNode>(LHS.getOperand(2))) {
8463     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8464     if (!Sel)
8465       return SDValue();
8466 
8467     Sel |= LHS.getConstantOperandVal(2);
8468     SDLoc DL(N);
8469     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8470                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8471   }
8472 
8473   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8474   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8475   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8476       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8477     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8478     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8479     if (LHSMask != ~0u && RHSMask != ~0u) {
8480       // Canonicalize the expression in an attempt to have fewer unique masks
8481       // and therefore fewer registers used to hold the masks.
8482       if (LHSMask > RHSMask) {
8483         std::swap(LHSMask, RHSMask);
8484         std::swap(LHS, RHS);
8485       }
8486 
8487       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8488       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8489       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8490       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8491 
8492       // Check of we need to combine values from two sources within a byte.
8493       if (!(LHSUsedLanes & RHSUsedLanes) &&
8494           // If we select high and lower word keep it for SDWA.
8495           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8496           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8497         // Kill zero bytes selected by other mask. Zero value is 0xc.
8498         LHSMask &= ~RHSUsedLanes;
8499         RHSMask &= ~LHSUsedLanes;
8500         // Add 4 to each active LHS lane
8501         LHSMask |= LHSUsedLanes & 0x04040404;
8502         // Combine masks
8503         uint32_t Sel = LHSMask | RHSMask;
8504         SDLoc DL(N);
8505 
8506         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8507                            LHS.getOperand(0), RHS.getOperand(0),
8508                            DAG.getConstant(Sel, DL, MVT::i32));
8509       }
8510     }
8511   }
8512 
8513   if (VT != MVT::i64)
8514     return SDValue();
8515 
8516   // TODO: This could be a generic combine with a predicate for extracting the
8517   // high half of an integer being free.
8518 
8519   // (or i64:x, (zero_extend i32:y)) ->
8520   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8521   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8522       RHS.getOpcode() != ISD::ZERO_EXTEND)
8523     std::swap(LHS, RHS);
8524 
8525   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8526     SDValue ExtSrc = RHS.getOperand(0);
8527     EVT SrcVT = ExtSrc.getValueType();
8528     if (SrcVT == MVT::i32) {
8529       SDLoc SL(N);
8530       SDValue LowLHS, HiBits;
8531       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8532       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8533 
8534       DCI.AddToWorklist(LowOr.getNode());
8535       DCI.AddToWorklist(HiBits.getNode());
8536 
8537       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8538                                 LowOr, HiBits);
8539       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8540     }
8541   }
8542 
8543   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8544   if (CRHS) {
8545     if (SDValue Split
8546           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8547       return Split;
8548   }
8549 
8550   return SDValue();
8551 }
8552 
8553 SDValue SITargetLowering::performXorCombine(SDNode *N,
8554                                             DAGCombinerInfo &DCI) const {
8555   EVT VT = N->getValueType(0);
8556   if (VT != MVT::i64)
8557     return SDValue();
8558 
8559   SDValue LHS = N->getOperand(0);
8560   SDValue RHS = N->getOperand(1);
8561 
8562   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8563   if (CRHS) {
8564     if (SDValue Split
8565           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8566       return Split;
8567   }
8568 
8569   return SDValue();
8570 }
8571 
8572 // Instructions that will be lowered with a final instruction that zeros the
8573 // high result bits.
8574 // XXX - probably only need to list legal operations.
8575 static bool fp16SrcZerosHighBits(unsigned Opc) {
8576   switch (Opc) {
8577   case ISD::FADD:
8578   case ISD::FSUB:
8579   case ISD::FMUL:
8580   case ISD::FDIV:
8581   case ISD::FREM:
8582   case ISD::FMA:
8583   case ISD::FMAD:
8584   case ISD::FCANONICALIZE:
8585   case ISD::FP_ROUND:
8586   case ISD::UINT_TO_FP:
8587   case ISD::SINT_TO_FP:
8588   case ISD::FABS:
8589     // Fabs is lowered to a bit operation, but it's an and which will clear the
8590     // high bits anyway.
8591   case ISD::FSQRT:
8592   case ISD::FSIN:
8593   case ISD::FCOS:
8594   case ISD::FPOWI:
8595   case ISD::FPOW:
8596   case ISD::FLOG:
8597   case ISD::FLOG2:
8598   case ISD::FLOG10:
8599   case ISD::FEXP:
8600   case ISD::FEXP2:
8601   case ISD::FCEIL:
8602   case ISD::FTRUNC:
8603   case ISD::FRINT:
8604   case ISD::FNEARBYINT:
8605   case ISD::FROUND:
8606   case ISD::FFLOOR:
8607   case ISD::FMINNUM:
8608   case ISD::FMAXNUM:
8609   case AMDGPUISD::FRACT:
8610   case AMDGPUISD::CLAMP:
8611   case AMDGPUISD::COS_HW:
8612   case AMDGPUISD::SIN_HW:
8613   case AMDGPUISD::FMIN3:
8614   case AMDGPUISD::FMAX3:
8615   case AMDGPUISD::FMED3:
8616   case AMDGPUISD::FMAD_FTZ:
8617   case AMDGPUISD::RCP:
8618   case AMDGPUISD::RSQ:
8619   case AMDGPUISD::RCP_IFLAG:
8620   case AMDGPUISD::LDEXP:
8621     return true;
8622   default:
8623     // fcopysign, select and others may be lowered to 32-bit bit operations
8624     // which don't zero the high bits.
8625     return false;
8626   }
8627 }
8628 
8629 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8630                                                    DAGCombinerInfo &DCI) const {
8631   if (!Subtarget->has16BitInsts() ||
8632       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8633     return SDValue();
8634 
8635   EVT VT = N->getValueType(0);
8636   if (VT != MVT::i32)
8637     return SDValue();
8638 
8639   SDValue Src = N->getOperand(0);
8640   if (Src.getValueType() != MVT::i16)
8641     return SDValue();
8642 
8643   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8644   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8645   if (Src.getOpcode() == ISD::BITCAST) {
8646     SDValue BCSrc = Src.getOperand(0);
8647     if (BCSrc.getValueType() == MVT::f16 &&
8648         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8649       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8650   }
8651 
8652   return SDValue();
8653 }
8654 
8655 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8656                                                         DAGCombinerInfo &DCI)
8657                                                         const {
8658   SDValue Src = N->getOperand(0);
8659   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8660 
8661   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8662       VTSign->getVT() == MVT::i8) ||
8663       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8664       VTSign->getVT() == MVT::i16)) &&
8665       Src.hasOneUse()) {
8666     auto *M = cast<MemSDNode>(Src);
8667     SDValue Ops[] = {
8668       Src.getOperand(0), // Chain
8669       Src.getOperand(1), // rsrc
8670       Src.getOperand(2), // vindex
8671       Src.getOperand(3), // voffset
8672       Src.getOperand(4), // soffset
8673       Src.getOperand(5), // offset
8674       Src.getOperand(6),
8675       Src.getOperand(7)
8676     };
8677     // replace with BUFFER_LOAD_BYTE/SHORT
8678     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8679                                          Src.getOperand(0).getValueType());
8680     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8681                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8682     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8683                                                           ResList,
8684                                                           Ops, M->getMemoryVT(),
8685                                                           M->getMemOperand());
8686     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8687                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8688   }
8689   return SDValue();
8690 }
8691 
8692 SDValue SITargetLowering::performClassCombine(SDNode *N,
8693                                               DAGCombinerInfo &DCI) const {
8694   SelectionDAG &DAG = DCI.DAG;
8695   SDValue Mask = N->getOperand(1);
8696 
8697   // fp_class x, 0 -> false
8698   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8699     if (CMask->isNullValue())
8700       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8701   }
8702 
8703   if (N->getOperand(0).isUndef())
8704     return DAG.getUNDEF(MVT::i1);
8705 
8706   return SDValue();
8707 }
8708 
8709 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8710                                             DAGCombinerInfo &DCI) const {
8711   EVT VT = N->getValueType(0);
8712   SDValue N0 = N->getOperand(0);
8713 
8714   if (N0.isUndef())
8715     return N0;
8716 
8717   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8718                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8719     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8720                            N->getFlags());
8721   }
8722 
8723   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8724 }
8725 
8726 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8727                                        unsigned MaxDepth) const {
8728   unsigned Opcode = Op.getOpcode();
8729   if (Opcode == ISD::FCANONICALIZE)
8730     return true;
8731 
8732   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8733     auto F = CFP->getValueAPF();
8734     if (F.isNaN() && F.isSignaling())
8735       return false;
8736     return !F.isDenormal() || denormalsEnabledForType(Op.getValueType());
8737   }
8738 
8739   // If source is a result of another standard FP operation it is already in
8740   // canonical form.
8741   if (MaxDepth == 0)
8742     return false;
8743 
8744   switch (Opcode) {
8745   // These will flush denorms if required.
8746   case ISD::FADD:
8747   case ISD::FSUB:
8748   case ISD::FMUL:
8749   case ISD::FCEIL:
8750   case ISD::FFLOOR:
8751   case ISD::FMA:
8752   case ISD::FMAD:
8753   case ISD::FSQRT:
8754   case ISD::FDIV:
8755   case ISD::FREM:
8756   case ISD::FP_ROUND:
8757   case ISD::FP_EXTEND:
8758   case AMDGPUISD::FMUL_LEGACY:
8759   case AMDGPUISD::FMAD_FTZ:
8760   case AMDGPUISD::RCP:
8761   case AMDGPUISD::RSQ:
8762   case AMDGPUISD::RSQ_CLAMP:
8763   case AMDGPUISD::RCP_LEGACY:
8764   case AMDGPUISD::RSQ_LEGACY:
8765   case AMDGPUISD::RCP_IFLAG:
8766   case AMDGPUISD::TRIG_PREOP:
8767   case AMDGPUISD::DIV_SCALE:
8768   case AMDGPUISD::DIV_FMAS:
8769   case AMDGPUISD::DIV_FIXUP:
8770   case AMDGPUISD::FRACT:
8771   case AMDGPUISD::LDEXP:
8772   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8773   case AMDGPUISD::CVT_F32_UBYTE0:
8774   case AMDGPUISD::CVT_F32_UBYTE1:
8775   case AMDGPUISD::CVT_F32_UBYTE2:
8776   case AMDGPUISD::CVT_F32_UBYTE3:
8777     return true;
8778 
8779   // It can/will be lowered or combined as a bit operation.
8780   // Need to check their input recursively to handle.
8781   case ISD::FNEG:
8782   case ISD::FABS:
8783   case ISD::FCOPYSIGN:
8784     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8785 
8786   case ISD::FSIN:
8787   case ISD::FCOS:
8788   case ISD::FSINCOS:
8789     return Op.getValueType().getScalarType() != MVT::f16;
8790 
8791   case ISD::FMINNUM:
8792   case ISD::FMAXNUM:
8793   case ISD::FMINNUM_IEEE:
8794   case ISD::FMAXNUM_IEEE:
8795   case AMDGPUISD::CLAMP:
8796   case AMDGPUISD::FMED3:
8797   case AMDGPUISD::FMAX3:
8798   case AMDGPUISD::FMIN3: {
8799     // FIXME: Shouldn't treat the generic operations different based these.
8800     // However, we aren't really required to flush the result from
8801     // minnum/maxnum..
8802 
8803     // snans will be quieted, so we only need to worry about denormals.
8804     if (Subtarget->supportsMinMaxDenormModes() ||
8805         denormalsEnabledForType(Op.getValueType()))
8806       return true;
8807 
8808     // Flushing may be required.
8809     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8810     // targets need to check their input recursively.
8811 
8812     // FIXME: Does this apply with clamp? It's implemented with max.
8813     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8814       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8815         return false;
8816     }
8817 
8818     return true;
8819   }
8820   case ISD::SELECT: {
8821     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8822            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8823   }
8824   case ISD::BUILD_VECTOR: {
8825     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8826       SDValue SrcOp = Op.getOperand(i);
8827       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8828         return false;
8829     }
8830 
8831     return true;
8832   }
8833   case ISD::EXTRACT_VECTOR_ELT:
8834   case ISD::EXTRACT_SUBVECTOR: {
8835     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8836   }
8837   case ISD::INSERT_VECTOR_ELT: {
8838     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8839            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8840   }
8841   case ISD::UNDEF:
8842     // Could be anything.
8843     return false;
8844 
8845   case ISD::BITCAST: {
8846     // Hack round the mess we make when legalizing extract_vector_elt
8847     SDValue Src = Op.getOperand(0);
8848     if (Src.getValueType() == MVT::i16 &&
8849         Src.getOpcode() == ISD::TRUNCATE) {
8850       SDValue TruncSrc = Src.getOperand(0);
8851       if (TruncSrc.getValueType() == MVT::i32 &&
8852           TruncSrc.getOpcode() == ISD::BITCAST &&
8853           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8854         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8855       }
8856     }
8857 
8858     return false;
8859   }
8860   case ISD::INTRINSIC_WO_CHAIN: {
8861     unsigned IntrinsicID
8862       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8863     // TODO: Handle more intrinsics
8864     switch (IntrinsicID) {
8865     case Intrinsic::amdgcn_cvt_pkrtz:
8866     case Intrinsic::amdgcn_cubeid:
8867     case Intrinsic::amdgcn_frexp_mant:
8868     case Intrinsic::amdgcn_fdot2:
8869       return true;
8870     default:
8871       break;
8872     }
8873 
8874     LLVM_FALLTHROUGH;
8875   }
8876   default:
8877     return denormalsEnabledForType(Op.getValueType()) &&
8878            DAG.isKnownNeverSNaN(Op);
8879   }
8880 
8881   llvm_unreachable("invalid operation");
8882 }
8883 
8884 // Constant fold canonicalize.
8885 SDValue SITargetLowering::getCanonicalConstantFP(
8886   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8887   // Flush denormals to 0 if not enabled.
8888   if (C.isDenormal() && !denormalsEnabledForType(VT))
8889     return DAG.getConstantFP(0.0, SL, VT);
8890 
8891   if (C.isNaN()) {
8892     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8893     if (C.isSignaling()) {
8894       // Quiet a signaling NaN.
8895       // FIXME: Is this supposed to preserve payload bits?
8896       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8897     }
8898 
8899     // Make sure it is the canonical NaN bitpattern.
8900     //
8901     // TODO: Can we use -1 as the canonical NaN value since it's an inline
8902     // immediate?
8903     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8904       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8905   }
8906 
8907   // Already canonical.
8908   return DAG.getConstantFP(C, SL, VT);
8909 }
8910 
8911 static bool vectorEltWillFoldAway(SDValue Op) {
8912   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8913 }
8914 
8915 SDValue SITargetLowering::performFCanonicalizeCombine(
8916   SDNode *N,
8917   DAGCombinerInfo &DCI) const {
8918   SelectionDAG &DAG = DCI.DAG;
8919   SDValue N0 = N->getOperand(0);
8920   EVT VT = N->getValueType(0);
8921 
8922   // fcanonicalize undef -> qnan
8923   if (N0.isUndef()) {
8924     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
8925     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8926   }
8927 
8928   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
8929     EVT VT = N->getValueType(0);
8930     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
8931   }
8932 
8933   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8934   //                                                   (fcanonicalize k)
8935   //
8936   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8937 
8938   // TODO: This could be better with wider vectors that will be split to v2f16,
8939   // and to consider uses since there aren't that many packed operations.
8940   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8941       isTypeLegal(MVT::v2f16)) {
8942     SDLoc SL(N);
8943     SDValue NewElts[2];
8944     SDValue Lo = N0.getOperand(0);
8945     SDValue Hi = N0.getOperand(1);
8946     EVT EltVT = Lo.getValueType();
8947 
8948     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
8949       for (unsigned I = 0; I != 2; ++I) {
8950         SDValue Op = N0.getOperand(I);
8951         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8952           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8953                                               CFP->getValueAPF());
8954         } else if (Op.isUndef()) {
8955           // Handled below based on what the other operand is.
8956           NewElts[I] = Op;
8957         } else {
8958           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8959         }
8960       }
8961 
8962       // If one half is undef, and one is constant, perfer a splat vector rather
8963       // than the normal qNaN. If it's a register, prefer 0.0 since that's
8964       // cheaper to use and may be free with a packed operation.
8965       if (NewElts[0].isUndef()) {
8966         if (isa<ConstantFPSDNode>(NewElts[1]))
8967           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8968             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8969       }
8970 
8971       if (NewElts[1].isUndef()) {
8972         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8973           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8974       }
8975 
8976       return DAG.getBuildVector(VT, SL, NewElts);
8977     }
8978   }
8979 
8980   unsigned SrcOpc = N0.getOpcode();
8981 
8982   // If it's free to do so, push canonicalizes further up the source, which may
8983   // find a canonical source.
8984   //
8985   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
8986   // sNaNs.
8987   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
8988     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8989     if (CRHS && N0.hasOneUse()) {
8990       SDLoc SL(N);
8991       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
8992                                    N0.getOperand(0));
8993       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
8994       DCI.AddToWorklist(Canon0.getNode());
8995 
8996       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
8997     }
8998   }
8999 
9000   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9001 }
9002 
9003 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9004   switch (Opc) {
9005   case ISD::FMAXNUM:
9006   case ISD::FMAXNUM_IEEE:
9007     return AMDGPUISD::FMAX3;
9008   case ISD::SMAX:
9009     return AMDGPUISD::SMAX3;
9010   case ISD::UMAX:
9011     return AMDGPUISD::UMAX3;
9012   case ISD::FMINNUM:
9013   case ISD::FMINNUM_IEEE:
9014     return AMDGPUISD::FMIN3;
9015   case ISD::SMIN:
9016     return AMDGPUISD::SMIN3;
9017   case ISD::UMIN:
9018     return AMDGPUISD::UMIN3;
9019   default:
9020     llvm_unreachable("Not a min/max opcode");
9021   }
9022 }
9023 
9024 SDValue SITargetLowering::performIntMed3ImmCombine(
9025   SelectionDAG &DAG, const SDLoc &SL,
9026   SDValue Op0, SDValue Op1, bool Signed) const {
9027   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9028   if (!K1)
9029     return SDValue();
9030 
9031   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9032   if (!K0)
9033     return SDValue();
9034 
9035   if (Signed) {
9036     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9037       return SDValue();
9038   } else {
9039     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9040       return SDValue();
9041   }
9042 
9043   EVT VT = K0->getValueType(0);
9044   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9045   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9046     return DAG.getNode(Med3Opc, SL, VT,
9047                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9048   }
9049 
9050   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9051   MVT NVT = MVT::i32;
9052   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9053 
9054   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9055   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9056   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9057 
9058   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9059   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9060 }
9061 
9062 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9063   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9064     return C;
9065 
9066   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9067     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9068       return C;
9069   }
9070 
9071   return nullptr;
9072 }
9073 
9074 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9075                                                   const SDLoc &SL,
9076                                                   SDValue Op0,
9077                                                   SDValue Op1) const {
9078   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9079   if (!K1)
9080     return SDValue();
9081 
9082   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9083   if (!K0)
9084     return SDValue();
9085 
9086   // Ordered >= (although NaN inputs should have folded away by now).
9087   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
9088   if (Cmp == APFloat::cmpGreaterThan)
9089     return SDValue();
9090 
9091   const MachineFunction &MF = DAG.getMachineFunction();
9092   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9093 
9094   // TODO: Check IEEE bit enabled?
9095   EVT VT = Op0.getValueType();
9096   if (Info->getMode().DX10Clamp) {
9097     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9098     // hardware fmed3 behavior converting to a min.
9099     // FIXME: Should this be allowing -0.0?
9100     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9101       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9102   }
9103 
9104   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9105   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9106     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9107     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9108     // then give the other result, which is different from med3 with a NaN
9109     // input.
9110     SDValue Var = Op0.getOperand(0);
9111     if (!DAG.isKnownNeverSNaN(Var))
9112       return SDValue();
9113 
9114     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9115 
9116     if ((!K0->hasOneUse() ||
9117          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9118         (!K1->hasOneUse() ||
9119          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9120       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9121                          Var, SDValue(K0, 0), SDValue(K1, 0));
9122     }
9123   }
9124 
9125   return SDValue();
9126 }
9127 
9128 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9129                                                DAGCombinerInfo &DCI) const {
9130   SelectionDAG &DAG = DCI.DAG;
9131 
9132   EVT VT = N->getValueType(0);
9133   unsigned Opc = N->getOpcode();
9134   SDValue Op0 = N->getOperand(0);
9135   SDValue Op1 = N->getOperand(1);
9136 
9137   // Only do this if the inner op has one use since this will just increases
9138   // register pressure for no benefit.
9139 
9140   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9141       !VT.isVector() &&
9142       (VT == MVT::i32 || VT == MVT::f32 ||
9143        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9144     // max(max(a, b), c) -> max3(a, b, c)
9145     // min(min(a, b), c) -> min3(a, b, c)
9146     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9147       SDLoc DL(N);
9148       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9149                          DL,
9150                          N->getValueType(0),
9151                          Op0.getOperand(0),
9152                          Op0.getOperand(1),
9153                          Op1);
9154     }
9155 
9156     // Try commuted.
9157     // max(a, max(b, c)) -> max3(a, b, c)
9158     // min(a, min(b, c)) -> min3(a, b, c)
9159     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9160       SDLoc DL(N);
9161       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9162                          DL,
9163                          N->getValueType(0),
9164                          Op0,
9165                          Op1.getOperand(0),
9166                          Op1.getOperand(1));
9167     }
9168   }
9169 
9170   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9171   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9172     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9173       return Med3;
9174   }
9175 
9176   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9177     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9178       return Med3;
9179   }
9180 
9181   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9182   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9183        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9184        (Opc == AMDGPUISD::FMIN_LEGACY &&
9185         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9186       (VT == MVT::f32 || VT == MVT::f64 ||
9187        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9188        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9189       Op0.hasOneUse()) {
9190     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9191       return Res;
9192   }
9193 
9194   return SDValue();
9195 }
9196 
9197 static bool isClampZeroToOne(SDValue A, SDValue B) {
9198   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9199     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9200       // FIXME: Should this be allowing -0.0?
9201       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9202              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9203     }
9204   }
9205 
9206   return false;
9207 }
9208 
9209 // FIXME: Should only worry about snans for version with chain.
9210 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9211                                               DAGCombinerInfo &DCI) const {
9212   EVT VT = N->getValueType(0);
9213   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9214   // NaNs. With a NaN input, the order of the operands may change the result.
9215 
9216   SelectionDAG &DAG = DCI.DAG;
9217   SDLoc SL(N);
9218 
9219   SDValue Src0 = N->getOperand(0);
9220   SDValue Src1 = N->getOperand(1);
9221   SDValue Src2 = N->getOperand(2);
9222 
9223   if (isClampZeroToOne(Src0, Src1)) {
9224     // const_a, const_b, x -> clamp is safe in all cases including signaling
9225     // nans.
9226     // FIXME: Should this be allowing -0.0?
9227     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9228   }
9229 
9230   const MachineFunction &MF = DAG.getMachineFunction();
9231   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9232 
9233   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9234   // handling no dx10-clamp?
9235   if (Info->getMode().DX10Clamp) {
9236     // If NaNs is clamped to 0, we are free to reorder the inputs.
9237 
9238     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9239       std::swap(Src0, Src1);
9240 
9241     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9242       std::swap(Src1, Src2);
9243 
9244     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9245       std::swap(Src0, Src1);
9246 
9247     if (isClampZeroToOne(Src1, Src2))
9248       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9249   }
9250 
9251   return SDValue();
9252 }
9253 
9254 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9255                                                  DAGCombinerInfo &DCI) const {
9256   SDValue Src0 = N->getOperand(0);
9257   SDValue Src1 = N->getOperand(1);
9258   if (Src0.isUndef() && Src1.isUndef())
9259     return DCI.DAG.getUNDEF(N->getValueType(0));
9260   return SDValue();
9261 }
9262 
9263 SDValue SITargetLowering::performExtractVectorEltCombine(
9264   SDNode *N, DAGCombinerInfo &DCI) const {
9265   SDValue Vec = N->getOperand(0);
9266   SelectionDAG &DAG = DCI.DAG;
9267 
9268   EVT VecVT = Vec.getValueType();
9269   EVT EltVT = VecVT.getVectorElementType();
9270 
9271   if ((Vec.getOpcode() == ISD::FNEG ||
9272        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9273     SDLoc SL(N);
9274     EVT EltVT = N->getValueType(0);
9275     SDValue Idx = N->getOperand(1);
9276     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9277                               Vec.getOperand(0), Idx);
9278     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9279   }
9280 
9281   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9282   //    =>
9283   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9284   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9285   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9286   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9287     SDLoc SL(N);
9288     EVT EltVT = N->getValueType(0);
9289     SDValue Idx = N->getOperand(1);
9290     unsigned Opc = Vec.getOpcode();
9291 
9292     switch(Opc) {
9293     default:
9294       break;
9295       // TODO: Support other binary operations.
9296     case ISD::FADD:
9297     case ISD::FSUB:
9298     case ISD::FMUL:
9299     case ISD::ADD:
9300     case ISD::UMIN:
9301     case ISD::UMAX:
9302     case ISD::SMIN:
9303     case ISD::SMAX:
9304     case ISD::FMAXNUM:
9305     case ISD::FMINNUM:
9306     case ISD::FMAXNUM_IEEE:
9307     case ISD::FMINNUM_IEEE: {
9308       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9309                                  Vec.getOperand(0), Idx);
9310       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9311                                  Vec.getOperand(1), Idx);
9312 
9313       DCI.AddToWorklist(Elt0.getNode());
9314       DCI.AddToWorklist(Elt1.getNode());
9315       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9316     }
9317     }
9318   }
9319 
9320   unsigned VecSize = VecVT.getSizeInBits();
9321   unsigned EltSize = EltVT.getSizeInBits();
9322 
9323   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9324   // This elminates non-constant index and subsequent movrel or scratch access.
9325   // Sub-dword vectors of size 2 dword or less have better implementation.
9326   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9327   // instructions.
9328   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9329       !isa<ConstantSDNode>(N->getOperand(1))) {
9330     SDLoc SL(N);
9331     SDValue Idx = N->getOperand(1);
9332     EVT IdxVT = Idx.getValueType();
9333     SDValue V;
9334     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9335       SDValue IC = DAG.getConstant(I, SL, IdxVT);
9336       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9337       if (I == 0)
9338         V = Elt;
9339       else
9340         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9341     }
9342     return V;
9343   }
9344 
9345   if (!DCI.isBeforeLegalize())
9346     return SDValue();
9347 
9348   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9349   // elements. This exposes more load reduction opportunities by replacing
9350   // multiple small extract_vector_elements with a single 32-bit extract.
9351   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9352   if (isa<MemSDNode>(Vec) &&
9353       EltSize <= 16 &&
9354       EltVT.isByteSized() &&
9355       VecSize > 32 &&
9356       VecSize % 32 == 0 &&
9357       Idx) {
9358     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9359 
9360     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9361     unsigned EltIdx = BitIndex / 32;
9362     unsigned LeftoverBitIdx = BitIndex % 32;
9363     SDLoc SL(N);
9364 
9365     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9366     DCI.AddToWorklist(Cast.getNode());
9367 
9368     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9369                               DAG.getConstant(EltIdx, SL, MVT::i32));
9370     DCI.AddToWorklist(Elt.getNode());
9371     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9372                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9373     DCI.AddToWorklist(Srl.getNode());
9374 
9375     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9376     DCI.AddToWorklist(Trunc.getNode());
9377     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9378   }
9379 
9380   return SDValue();
9381 }
9382 
9383 SDValue
9384 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9385                                                 DAGCombinerInfo &DCI) const {
9386   SDValue Vec = N->getOperand(0);
9387   SDValue Idx = N->getOperand(2);
9388   EVT VecVT = Vec.getValueType();
9389   EVT EltVT = VecVT.getVectorElementType();
9390   unsigned VecSize = VecVT.getSizeInBits();
9391   unsigned EltSize = EltVT.getSizeInBits();
9392 
9393   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9394   // => BUILD_VECTOR n x select (e, const-idx)
9395   // This elminates non-constant index and subsequent movrel or scratch access.
9396   // Sub-dword vectors of size 2 dword or less have better implementation.
9397   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9398   // instructions.
9399   if (isa<ConstantSDNode>(Idx) ||
9400       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9401     return SDValue();
9402 
9403   SelectionDAG &DAG = DCI.DAG;
9404   SDLoc SL(N);
9405   SDValue Ins = N->getOperand(1);
9406   EVT IdxVT = Idx.getValueType();
9407 
9408   SmallVector<SDValue, 16> Ops;
9409   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9410     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9411     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9412     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9413     Ops.push_back(V);
9414   }
9415 
9416   return DAG.getBuildVector(VecVT, SL, Ops);
9417 }
9418 
9419 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9420                                           const SDNode *N0,
9421                                           const SDNode *N1) const {
9422   EVT VT = N0->getValueType(0);
9423 
9424   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9425   // support denormals ever.
9426   if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
9427        (VT == MVT::f16 && !Subtarget->hasFP16Denormals() &&
9428         getSubtarget()->hasMadF16())) &&
9429        isOperationLegal(ISD::FMAD, VT))
9430     return ISD::FMAD;
9431 
9432   const TargetOptions &Options = DAG.getTarget().Options;
9433   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9434        (N0->getFlags().hasAllowContract() &&
9435         N1->getFlags().hasAllowContract())) &&
9436       isFMAFasterThanFMulAndFAdd(VT)) {
9437     return ISD::FMA;
9438   }
9439 
9440   return 0;
9441 }
9442 
9443 // For a reassociatable opcode perform:
9444 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9445 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9446                                                SelectionDAG &DAG) const {
9447   EVT VT = N->getValueType(0);
9448   if (VT != MVT::i32 && VT != MVT::i64)
9449     return SDValue();
9450 
9451   unsigned Opc = N->getOpcode();
9452   SDValue Op0 = N->getOperand(0);
9453   SDValue Op1 = N->getOperand(1);
9454 
9455   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9456     return SDValue();
9457 
9458   if (Op0->isDivergent())
9459     std::swap(Op0, Op1);
9460 
9461   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9462     return SDValue();
9463 
9464   SDValue Op2 = Op1.getOperand(1);
9465   Op1 = Op1.getOperand(0);
9466   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9467     return SDValue();
9468 
9469   if (Op1->isDivergent())
9470     std::swap(Op1, Op2);
9471 
9472   // If either operand is constant this will conflict with
9473   // DAGCombiner::ReassociateOps().
9474   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9475       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9476     return SDValue();
9477 
9478   SDLoc SL(N);
9479   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9480   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9481 }
9482 
9483 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9484                            EVT VT,
9485                            SDValue N0, SDValue N1, SDValue N2,
9486                            bool Signed) {
9487   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9488   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9489   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9490   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9491 }
9492 
9493 SDValue SITargetLowering::performAddCombine(SDNode *N,
9494                                             DAGCombinerInfo &DCI) const {
9495   SelectionDAG &DAG = DCI.DAG;
9496   EVT VT = N->getValueType(0);
9497   SDLoc SL(N);
9498   SDValue LHS = N->getOperand(0);
9499   SDValue RHS = N->getOperand(1);
9500 
9501   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9502       && Subtarget->hasMad64_32() &&
9503       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9504       VT.getScalarSizeInBits() <= 64) {
9505     if (LHS.getOpcode() != ISD::MUL)
9506       std::swap(LHS, RHS);
9507 
9508     SDValue MulLHS = LHS.getOperand(0);
9509     SDValue MulRHS = LHS.getOperand(1);
9510     SDValue AddRHS = RHS;
9511 
9512     // TODO: Maybe restrict if SGPR inputs.
9513     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9514         numBitsUnsigned(MulRHS, DAG) <= 32) {
9515       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9516       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9517       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9518       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9519     }
9520 
9521     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9522       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9523       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9524       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9525       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9526     }
9527 
9528     return SDValue();
9529   }
9530 
9531   if (SDValue V = reassociateScalarOps(N, DAG)) {
9532     return V;
9533   }
9534 
9535   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9536     return SDValue();
9537 
9538   // add x, zext (setcc) => addcarry x, 0, setcc
9539   // add x, sext (setcc) => subcarry x, 0, setcc
9540   unsigned Opc = LHS.getOpcode();
9541   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9542       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9543     std::swap(RHS, LHS);
9544 
9545   Opc = RHS.getOpcode();
9546   switch (Opc) {
9547   default: break;
9548   case ISD::ZERO_EXTEND:
9549   case ISD::SIGN_EXTEND:
9550   case ISD::ANY_EXTEND: {
9551     auto Cond = RHS.getOperand(0);
9552     if (!isBoolSGPR(Cond))
9553       break;
9554     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9555     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9556     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9557     return DAG.getNode(Opc, SL, VTList, Args);
9558   }
9559   case ISD::ADDCARRY: {
9560     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9561     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9562     if (!C || C->getZExtValue() != 0) break;
9563     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9564     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9565   }
9566   }
9567   return SDValue();
9568 }
9569 
9570 SDValue SITargetLowering::performSubCombine(SDNode *N,
9571                                             DAGCombinerInfo &DCI) const {
9572   SelectionDAG &DAG = DCI.DAG;
9573   EVT VT = N->getValueType(0);
9574 
9575   if (VT != MVT::i32)
9576     return SDValue();
9577 
9578   SDLoc SL(N);
9579   SDValue LHS = N->getOperand(0);
9580   SDValue RHS = N->getOperand(1);
9581 
9582   if (LHS.getOpcode() == ISD::SUBCARRY) {
9583     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9584     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9585     if (!C || !C->isNullValue())
9586       return SDValue();
9587     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9588     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9589   }
9590   return SDValue();
9591 }
9592 
9593 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9594   DAGCombinerInfo &DCI) const {
9595 
9596   if (N->getValueType(0) != MVT::i32)
9597     return SDValue();
9598 
9599   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9600   if (!C || C->getZExtValue() != 0)
9601     return SDValue();
9602 
9603   SelectionDAG &DAG = DCI.DAG;
9604   SDValue LHS = N->getOperand(0);
9605 
9606   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9607   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9608   unsigned LHSOpc = LHS.getOpcode();
9609   unsigned Opc = N->getOpcode();
9610   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9611       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9612     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9613     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9614   }
9615   return SDValue();
9616 }
9617 
9618 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9619                                              DAGCombinerInfo &DCI) const {
9620   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9621     return SDValue();
9622 
9623   SelectionDAG &DAG = DCI.DAG;
9624   EVT VT = N->getValueType(0);
9625 
9626   SDLoc SL(N);
9627   SDValue LHS = N->getOperand(0);
9628   SDValue RHS = N->getOperand(1);
9629 
9630   // These should really be instruction patterns, but writing patterns with
9631   // source modiifiers is a pain.
9632 
9633   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9634   if (LHS.getOpcode() == ISD::FADD) {
9635     SDValue A = LHS.getOperand(0);
9636     if (A == LHS.getOperand(1)) {
9637       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9638       if (FusedOp != 0) {
9639         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9640         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9641       }
9642     }
9643   }
9644 
9645   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9646   if (RHS.getOpcode() == ISD::FADD) {
9647     SDValue A = RHS.getOperand(0);
9648     if (A == RHS.getOperand(1)) {
9649       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9650       if (FusedOp != 0) {
9651         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9652         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9653       }
9654     }
9655   }
9656 
9657   return SDValue();
9658 }
9659 
9660 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9661                                              DAGCombinerInfo &DCI) const {
9662   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9663     return SDValue();
9664 
9665   SelectionDAG &DAG = DCI.DAG;
9666   SDLoc SL(N);
9667   EVT VT = N->getValueType(0);
9668   assert(!VT.isVector());
9669 
9670   // Try to get the fneg to fold into the source modifier. This undoes generic
9671   // DAG combines and folds them into the mad.
9672   //
9673   // Only do this if we are not trying to support denormals. v_mad_f32 does
9674   // not support denormals ever.
9675   SDValue LHS = N->getOperand(0);
9676   SDValue RHS = N->getOperand(1);
9677   if (LHS.getOpcode() == ISD::FADD) {
9678     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9679     SDValue A = LHS.getOperand(0);
9680     if (A == LHS.getOperand(1)) {
9681       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9682       if (FusedOp != 0){
9683         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9684         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9685 
9686         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9687       }
9688     }
9689   }
9690 
9691   if (RHS.getOpcode() == ISD::FADD) {
9692     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9693 
9694     SDValue A = RHS.getOperand(0);
9695     if (A == RHS.getOperand(1)) {
9696       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9697       if (FusedOp != 0){
9698         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9699         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9700       }
9701     }
9702   }
9703 
9704   return SDValue();
9705 }
9706 
9707 SDValue SITargetLowering::performFMACombine(SDNode *N,
9708                                             DAGCombinerInfo &DCI) const {
9709   SelectionDAG &DAG = DCI.DAG;
9710   EVT VT = N->getValueType(0);
9711   SDLoc SL(N);
9712 
9713   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9714     return SDValue();
9715 
9716   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9717   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9718   SDValue Op1 = N->getOperand(0);
9719   SDValue Op2 = N->getOperand(1);
9720   SDValue FMA = N->getOperand(2);
9721 
9722   if (FMA.getOpcode() != ISD::FMA ||
9723       Op1.getOpcode() != ISD::FP_EXTEND ||
9724       Op2.getOpcode() != ISD::FP_EXTEND)
9725     return SDValue();
9726 
9727   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9728   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9729   // is sufficient to allow generaing fdot2.
9730   const TargetOptions &Options = DAG.getTarget().Options;
9731   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9732       (N->getFlags().hasAllowContract() &&
9733        FMA->getFlags().hasAllowContract())) {
9734     Op1 = Op1.getOperand(0);
9735     Op2 = Op2.getOperand(0);
9736     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9737         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9738       return SDValue();
9739 
9740     SDValue Vec1 = Op1.getOperand(0);
9741     SDValue Idx1 = Op1.getOperand(1);
9742     SDValue Vec2 = Op2.getOperand(0);
9743 
9744     SDValue FMAOp1 = FMA.getOperand(0);
9745     SDValue FMAOp2 = FMA.getOperand(1);
9746     SDValue FMAAcc = FMA.getOperand(2);
9747 
9748     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9749         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9750       return SDValue();
9751 
9752     FMAOp1 = FMAOp1.getOperand(0);
9753     FMAOp2 = FMAOp2.getOperand(0);
9754     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9755         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9756       return SDValue();
9757 
9758     SDValue Vec3 = FMAOp1.getOperand(0);
9759     SDValue Vec4 = FMAOp2.getOperand(0);
9760     SDValue Idx2 = FMAOp1.getOperand(1);
9761 
9762     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9763         // Idx1 and Idx2 cannot be the same.
9764         Idx1 == Idx2)
9765       return SDValue();
9766 
9767     if (Vec1 == Vec2 || Vec3 == Vec4)
9768       return SDValue();
9769 
9770     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9771       return SDValue();
9772 
9773     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9774         (Vec1 == Vec4 && Vec2 == Vec3)) {
9775       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9776                          DAG.getTargetConstant(0, SL, MVT::i1));
9777     }
9778   }
9779   return SDValue();
9780 }
9781 
9782 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9783                                               DAGCombinerInfo &DCI) const {
9784   SelectionDAG &DAG = DCI.DAG;
9785   SDLoc SL(N);
9786 
9787   SDValue LHS = N->getOperand(0);
9788   SDValue RHS = N->getOperand(1);
9789   EVT VT = LHS.getValueType();
9790   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9791 
9792   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9793   if (!CRHS) {
9794     CRHS = dyn_cast<ConstantSDNode>(LHS);
9795     if (CRHS) {
9796       std::swap(LHS, RHS);
9797       CC = getSetCCSwappedOperands(CC);
9798     }
9799   }
9800 
9801   if (CRHS) {
9802     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9803         isBoolSGPR(LHS.getOperand(0))) {
9804       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9805       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9806       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9807       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9808       if ((CRHS->isAllOnesValue() &&
9809            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9810           (CRHS->isNullValue() &&
9811            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9812         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9813                            DAG.getConstant(-1, SL, MVT::i1));
9814       if ((CRHS->isAllOnesValue() &&
9815            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9816           (CRHS->isNullValue() &&
9817            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9818         return LHS.getOperand(0);
9819     }
9820 
9821     uint64_t CRHSVal = CRHS->getZExtValue();
9822     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9823         LHS.getOpcode() == ISD::SELECT &&
9824         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9825         isa<ConstantSDNode>(LHS.getOperand(2)) &&
9826         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9827         isBoolSGPR(LHS.getOperand(0))) {
9828       // Given CT != FT:
9829       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9830       // setcc (select cc, CT, CF), CF, ne => cc
9831       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9832       // setcc (select cc, CT, CF), CT, eq => cc
9833       uint64_t CT = LHS.getConstantOperandVal(1);
9834       uint64_t CF = LHS.getConstantOperandVal(2);
9835 
9836       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9837           (CT == CRHSVal && CC == ISD::SETNE))
9838         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9839                            DAG.getConstant(-1, SL, MVT::i1));
9840       if ((CF == CRHSVal && CC == ISD::SETNE) ||
9841           (CT == CRHSVal && CC == ISD::SETEQ))
9842         return LHS.getOperand(0);
9843     }
9844   }
9845 
9846   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9847                                            VT != MVT::f16))
9848     return SDValue();
9849 
9850   // Match isinf/isfinite pattern
9851   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
9852   // (fcmp one (fabs x), inf) -> (fp_class x,
9853   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9854   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
9855     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9856     if (!CRHS)
9857       return SDValue();
9858 
9859     const APFloat &APF = CRHS->getValueAPF();
9860     if (APF.isInfinity() && !APF.isNegative()) {
9861       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9862                                  SIInstrFlags::N_INFINITY;
9863       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9864                                     SIInstrFlags::P_ZERO |
9865                                     SIInstrFlags::N_NORMAL |
9866                                     SIInstrFlags::P_NORMAL |
9867                                     SIInstrFlags::N_SUBNORMAL |
9868                                     SIInstrFlags::P_SUBNORMAL;
9869       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
9870       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9871                          DAG.getConstant(Mask, SL, MVT::i32));
9872     }
9873   }
9874 
9875   return SDValue();
9876 }
9877 
9878 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9879                                                      DAGCombinerInfo &DCI) const {
9880   SelectionDAG &DAG = DCI.DAG;
9881   SDLoc SL(N);
9882   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9883 
9884   SDValue Src = N->getOperand(0);
9885   SDValue Srl = N->getOperand(0);
9886   if (Srl.getOpcode() == ISD::ZERO_EXTEND)
9887     Srl = Srl.getOperand(0);
9888 
9889   // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
9890   if (Srl.getOpcode() == ISD::SRL) {
9891     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9892     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9893     // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
9894 
9895     if (const ConstantSDNode *C =
9896         dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
9897       Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
9898                                EVT(MVT::i32));
9899 
9900       unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
9901       if (SrcOffset < 32 && SrcOffset % 8 == 0) {
9902         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
9903                            MVT::f32, Srl);
9904       }
9905     }
9906   }
9907 
9908   APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9909 
9910   KnownBits Known;
9911   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9912                                         !DCI.isBeforeLegalizeOps());
9913   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9914   if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
9915     DCI.CommitTargetLoweringOpt(TLO);
9916   }
9917 
9918   return SDValue();
9919 }
9920 
9921 SDValue SITargetLowering::performClampCombine(SDNode *N,
9922                                               DAGCombinerInfo &DCI) const {
9923   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
9924   if (!CSrc)
9925     return SDValue();
9926 
9927   const MachineFunction &MF = DCI.DAG.getMachineFunction();
9928   const APFloat &F = CSrc->getValueAPF();
9929   APFloat Zero = APFloat::getZero(F.getSemantics());
9930   APFloat::cmpResult Cmp0 = F.compare(Zero);
9931   if (Cmp0 == APFloat::cmpLessThan ||
9932       (Cmp0 == APFloat::cmpUnordered &&
9933        MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
9934     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9935   }
9936 
9937   APFloat One(F.getSemantics(), "1.0");
9938   APFloat::cmpResult Cmp1 = F.compare(One);
9939   if (Cmp1 == APFloat::cmpGreaterThan)
9940     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9941 
9942   return SDValue(CSrc, 0);
9943 }
9944 
9945 
9946 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
9947                                             DAGCombinerInfo &DCI) const {
9948   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9949     return SDValue();
9950   switch (N->getOpcode()) {
9951   default:
9952     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9953   case ISD::ADD:
9954     return performAddCombine(N, DCI);
9955   case ISD::SUB:
9956     return performSubCombine(N, DCI);
9957   case ISD::ADDCARRY:
9958   case ISD::SUBCARRY:
9959     return performAddCarrySubCarryCombine(N, DCI);
9960   case ISD::FADD:
9961     return performFAddCombine(N, DCI);
9962   case ISD::FSUB:
9963     return performFSubCombine(N, DCI);
9964   case ISD::SETCC:
9965     return performSetCCCombine(N, DCI);
9966   case ISD::FMAXNUM:
9967   case ISD::FMINNUM:
9968   case ISD::FMAXNUM_IEEE:
9969   case ISD::FMINNUM_IEEE:
9970   case ISD::SMAX:
9971   case ISD::SMIN:
9972   case ISD::UMAX:
9973   case ISD::UMIN:
9974   case AMDGPUISD::FMIN_LEGACY:
9975   case AMDGPUISD::FMAX_LEGACY:
9976     return performMinMaxCombine(N, DCI);
9977   case ISD::FMA:
9978     return performFMACombine(N, DCI);
9979   case ISD::LOAD: {
9980     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
9981       return Widended;
9982     LLVM_FALLTHROUGH;
9983   }
9984   case ISD::STORE:
9985   case ISD::ATOMIC_LOAD:
9986   case ISD::ATOMIC_STORE:
9987   case ISD::ATOMIC_CMP_SWAP:
9988   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
9989   case ISD::ATOMIC_SWAP:
9990   case ISD::ATOMIC_LOAD_ADD:
9991   case ISD::ATOMIC_LOAD_SUB:
9992   case ISD::ATOMIC_LOAD_AND:
9993   case ISD::ATOMIC_LOAD_OR:
9994   case ISD::ATOMIC_LOAD_XOR:
9995   case ISD::ATOMIC_LOAD_NAND:
9996   case ISD::ATOMIC_LOAD_MIN:
9997   case ISD::ATOMIC_LOAD_MAX:
9998   case ISD::ATOMIC_LOAD_UMIN:
9999   case ISD::ATOMIC_LOAD_UMAX:
10000   case ISD::ATOMIC_LOAD_FADD:
10001   case AMDGPUISD::ATOMIC_INC:
10002   case AMDGPUISD::ATOMIC_DEC:
10003   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10004   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10005     if (DCI.isBeforeLegalize())
10006       break;
10007     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10008   case ISD::AND:
10009     return performAndCombine(N, DCI);
10010   case ISD::OR:
10011     return performOrCombine(N, DCI);
10012   case ISD::XOR:
10013     return performXorCombine(N, DCI);
10014   case ISD::ZERO_EXTEND:
10015     return performZeroExtendCombine(N, DCI);
10016   case ISD::SIGN_EXTEND_INREG:
10017     return performSignExtendInRegCombine(N , DCI);
10018   case AMDGPUISD::FP_CLASS:
10019     return performClassCombine(N, DCI);
10020   case ISD::FCANONICALIZE:
10021     return performFCanonicalizeCombine(N, DCI);
10022   case AMDGPUISD::RCP:
10023     return performRcpCombine(N, DCI);
10024   case AMDGPUISD::FRACT:
10025   case AMDGPUISD::RSQ:
10026   case AMDGPUISD::RCP_LEGACY:
10027   case AMDGPUISD::RSQ_LEGACY:
10028   case AMDGPUISD::RCP_IFLAG:
10029   case AMDGPUISD::RSQ_CLAMP:
10030   case AMDGPUISD::LDEXP: {
10031     SDValue Src = N->getOperand(0);
10032     if (Src.isUndef())
10033       return Src;
10034     break;
10035   }
10036   case ISD::SINT_TO_FP:
10037   case ISD::UINT_TO_FP:
10038     return performUCharToFloatCombine(N, DCI);
10039   case AMDGPUISD::CVT_F32_UBYTE0:
10040   case AMDGPUISD::CVT_F32_UBYTE1:
10041   case AMDGPUISD::CVT_F32_UBYTE2:
10042   case AMDGPUISD::CVT_F32_UBYTE3:
10043     return performCvtF32UByteNCombine(N, DCI);
10044   case AMDGPUISD::FMED3:
10045     return performFMed3Combine(N, DCI);
10046   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10047     return performCvtPkRTZCombine(N, DCI);
10048   case AMDGPUISD::CLAMP:
10049     return performClampCombine(N, DCI);
10050   case ISD::SCALAR_TO_VECTOR: {
10051     SelectionDAG &DAG = DCI.DAG;
10052     EVT VT = N->getValueType(0);
10053 
10054     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10055     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10056       SDLoc SL(N);
10057       SDValue Src = N->getOperand(0);
10058       EVT EltVT = Src.getValueType();
10059       if (EltVT == MVT::f16)
10060         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10061 
10062       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10063       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10064     }
10065 
10066     break;
10067   }
10068   case ISD::EXTRACT_VECTOR_ELT:
10069     return performExtractVectorEltCombine(N, DCI);
10070   case ISD::INSERT_VECTOR_ELT:
10071     return performInsertVectorEltCombine(N, DCI);
10072   }
10073   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10074 }
10075 
10076 /// Helper function for adjustWritemask
10077 static unsigned SubIdx2Lane(unsigned Idx) {
10078   switch (Idx) {
10079   default: return 0;
10080   case AMDGPU::sub0: return 0;
10081   case AMDGPU::sub1: return 1;
10082   case AMDGPU::sub2: return 2;
10083   case AMDGPU::sub3: return 3;
10084   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10085   }
10086 }
10087 
10088 /// Adjust the writemask of MIMG instructions
10089 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10090                                           SelectionDAG &DAG) const {
10091   unsigned Opcode = Node->getMachineOpcode();
10092 
10093   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10094   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10095   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10096     return Node; // not implemented for D16
10097 
10098   SDNode *Users[5] = { nullptr };
10099   unsigned Lane = 0;
10100   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10101   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10102   unsigned NewDmask = 0;
10103   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10104   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10105   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10106                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10107   unsigned TFCLane = 0;
10108   bool HasChain = Node->getNumValues() > 1;
10109 
10110   if (OldDmask == 0) {
10111     // These are folded out, but on the chance it happens don't assert.
10112     return Node;
10113   }
10114 
10115   unsigned OldBitsSet = countPopulation(OldDmask);
10116   // Work out which is the TFE/LWE lane if that is enabled.
10117   if (UsesTFC) {
10118     TFCLane = OldBitsSet;
10119   }
10120 
10121   // Try to figure out the used register components
10122   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10123        I != E; ++I) {
10124 
10125     // Don't look at users of the chain.
10126     if (I.getUse().getResNo() != 0)
10127       continue;
10128 
10129     // Abort if we can't understand the usage
10130     if (!I->isMachineOpcode() ||
10131         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10132       return Node;
10133 
10134     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10135     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10136     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10137     // set, etc.
10138     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10139 
10140     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10141     if (UsesTFC && Lane == TFCLane) {
10142       Users[Lane] = *I;
10143     } else {
10144       // Set which texture component corresponds to the lane.
10145       unsigned Comp;
10146       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10147         Comp = countTrailingZeros(Dmask);
10148         Dmask &= ~(1 << Comp);
10149       }
10150 
10151       // Abort if we have more than one user per component.
10152       if (Users[Lane])
10153         return Node;
10154 
10155       Users[Lane] = *I;
10156       NewDmask |= 1 << Comp;
10157     }
10158   }
10159 
10160   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10161   bool NoChannels = !NewDmask;
10162   if (NoChannels) {
10163     if (!UsesTFC) {
10164       // No uses of the result and not using TFC. Then do nothing.
10165       return Node;
10166     }
10167     // If the original dmask has one channel - then nothing to do
10168     if (OldBitsSet == 1)
10169       return Node;
10170     // Use an arbitrary dmask - required for the instruction to work
10171     NewDmask = 1;
10172   }
10173   // Abort if there's no change
10174   if (NewDmask == OldDmask)
10175     return Node;
10176 
10177   unsigned BitsSet = countPopulation(NewDmask);
10178 
10179   // Check for TFE or LWE - increase the number of channels by one to account
10180   // for the extra return value
10181   // This will need adjustment for D16 if this is also included in
10182   // adjustWriteMask (this function) but at present D16 are excluded.
10183   unsigned NewChannels = BitsSet + UsesTFC;
10184 
10185   int NewOpcode =
10186       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10187   assert(NewOpcode != -1 &&
10188          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10189          "failed to find equivalent MIMG op");
10190 
10191   // Adjust the writemask in the node
10192   SmallVector<SDValue, 12> Ops;
10193   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10194   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10195   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10196 
10197   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10198 
10199   MVT ResultVT = NewChannels == 1 ?
10200     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10201                            NewChannels == 5 ? 8 : NewChannels);
10202   SDVTList NewVTList = HasChain ?
10203     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10204 
10205 
10206   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10207                                               NewVTList, Ops);
10208 
10209   if (HasChain) {
10210     // Update chain.
10211     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10212     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10213   }
10214 
10215   if (NewChannels == 1) {
10216     assert(Node->hasNUsesOfValue(1, 0));
10217     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10218                                       SDLoc(Node), Users[Lane]->getValueType(0),
10219                                       SDValue(NewNode, 0));
10220     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10221     return nullptr;
10222   }
10223 
10224   // Update the users of the node with the new indices
10225   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10226     SDNode *User = Users[i];
10227     if (!User) {
10228       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10229       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10230       if (i || !NoChannels)
10231         continue;
10232     } else {
10233       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10234       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10235     }
10236 
10237     switch (Idx) {
10238     default: break;
10239     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10240     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10241     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10242     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10243     }
10244   }
10245 
10246   DAG.RemoveDeadNode(Node);
10247   return nullptr;
10248 }
10249 
10250 static bool isFrameIndexOp(SDValue Op) {
10251   if (Op.getOpcode() == ISD::AssertZext)
10252     Op = Op.getOperand(0);
10253 
10254   return isa<FrameIndexSDNode>(Op);
10255 }
10256 
10257 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10258 /// with frame index operands.
10259 /// LLVM assumes that inputs are to these instructions are registers.
10260 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10261                                                         SelectionDAG &DAG) const {
10262   if (Node->getOpcode() == ISD::CopyToReg) {
10263     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10264     SDValue SrcVal = Node->getOperand(2);
10265 
10266     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10267     // to try understanding copies to physical registers.
10268     if (SrcVal.getValueType() == MVT::i1 &&
10269         Register::isPhysicalRegister(DestReg->getReg())) {
10270       SDLoc SL(Node);
10271       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10272       SDValue VReg = DAG.getRegister(
10273         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10274 
10275       SDNode *Glued = Node->getGluedNode();
10276       SDValue ToVReg
10277         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10278                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10279       SDValue ToResultReg
10280         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10281                            VReg, ToVReg.getValue(1));
10282       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10283       DAG.RemoveDeadNode(Node);
10284       return ToResultReg.getNode();
10285     }
10286   }
10287 
10288   SmallVector<SDValue, 8> Ops;
10289   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10290     if (!isFrameIndexOp(Node->getOperand(i))) {
10291       Ops.push_back(Node->getOperand(i));
10292       continue;
10293     }
10294 
10295     SDLoc DL(Node);
10296     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10297                                      Node->getOperand(i).getValueType(),
10298                                      Node->getOperand(i)), 0));
10299   }
10300 
10301   return DAG.UpdateNodeOperands(Node, Ops);
10302 }
10303 
10304 /// Fold the instructions after selecting them.
10305 /// Returns null if users were already updated.
10306 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10307                                           SelectionDAG &DAG) const {
10308   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10309   unsigned Opcode = Node->getMachineOpcode();
10310 
10311   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10312       !TII->isGather4(Opcode)) {
10313     return adjustWritemask(Node, DAG);
10314   }
10315 
10316   if (Opcode == AMDGPU::INSERT_SUBREG ||
10317       Opcode == AMDGPU::REG_SEQUENCE) {
10318     legalizeTargetIndependentNode(Node, DAG);
10319     return Node;
10320   }
10321 
10322   switch (Opcode) {
10323   case AMDGPU::V_DIV_SCALE_F32:
10324   case AMDGPU::V_DIV_SCALE_F64: {
10325     // Satisfy the operand register constraint when one of the inputs is
10326     // undefined. Ordinarily each undef value will have its own implicit_def of
10327     // a vreg, so force these to use a single register.
10328     SDValue Src0 = Node->getOperand(0);
10329     SDValue Src1 = Node->getOperand(1);
10330     SDValue Src2 = Node->getOperand(2);
10331 
10332     if ((Src0.isMachineOpcode() &&
10333          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10334         (Src0 == Src1 || Src0 == Src2))
10335       break;
10336 
10337     MVT VT = Src0.getValueType().getSimpleVT();
10338     const TargetRegisterClass *RC =
10339         getRegClassFor(VT, Src0.getNode()->isDivergent());
10340 
10341     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10342     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10343 
10344     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10345                                       UndefReg, Src0, SDValue());
10346 
10347     // src0 must be the same register as src1 or src2, even if the value is
10348     // undefined, so make sure we don't violate this constraint.
10349     if (Src0.isMachineOpcode() &&
10350         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10351       if (Src1.isMachineOpcode() &&
10352           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10353         Src0 = Src1;
10354       else if (Src2.isMachineOpcode() &&
10355                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10356         Src0 = Src2;
10357       else {
10358         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10359         Src0 = UndefReg;
10360         Src1 = UndefReg;
10361       }
10362     } else
10363       break;
10364 
10365     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10366     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10367       Ops.push_back(Node->getOperand(I));
10368 
10369     Ops.push_back(ImpDef.getValue(1));
10370     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10371   }
10372   case AMDGPU::V_PERMLANE16_B32:
10373   case AMDGPU::V_PERMLANEX16_B32: {
10374     ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0));
10375     ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2));
10376     if (!FI->getZExtValue() && !BC->getZExtValue())
10377       break;
10378     SDValue VDstIn = Node->getOperand(6);
10379     if (VDstIn.isMachineOpcode()
10380         && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF)
10381       break;
10382     MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
10383                                                SDLoc(Node), MVT::i32);
10384     SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1),
10385                                     SDValue(BC, 0), Node->getOperand(3),
10386                                     Node->getOperand(4), Node->getOperand(5),
10387                                     SDValue(ImpDef, 0), Node->getOperand(7) };
10388     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10389   }
10390   default:
10391     break;
10392   }
10393 
10394   return Node;
10395 }
10396 
10397 /// Assign the register class depending on the number of
10398 /// bits set in the writemask
10399 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10400                                                      SDNode *Node) const {
10401   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10402 
10403   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10404 
10405   if (TII->isVOP3(MI.getOpcode())) {
10406     // Make sure constant bus requirements are respected.
10407     TII->legalizeOperandsVOP3(MRI, MI);
10408 
10409     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10410     // This saves a chain-copy of registers and better ballance register
10411     // use between vgpr and agpr as agpr tuples tend to be big.
10412     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10413       unsigned Opc = MI.getOpcode();
10414       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10415       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10416                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10417         if (I == -1)
10418           break;
10419         MachineOperand &Op = MI.getOperand(I);
10420         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10421              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10422             !Register::isVirtualRegister(Op.getReg()) ||
10423             !TRI->isAGPR(MRI, Op.getReg()))
10424           continue;
10425         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10426         if (!Src || !Src->isCopy() ||
10427             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10428           continue;
10429         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10430         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10431         // All uses of agpr64 and agpr32 can also accept vgpr except for
10432         // v_accvgpr_read, but we do not produce agpr reads during selection,
10433         // so no use checks are needed.
10434         MRI.setRegClass(Op.getReg(), NewRC);
10435       }
10436     }
10437 
10438     return;
10439   }
10440 
10441   // Replace unused atomics with the no return version.
10442   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10443   if (NoRetAtomicOp != -1) {
10444     if (!Node->hasAnyUseOfValue(0)) {
10445       MI.setDesc(TII->get(NoRetAtomicOp));
10446       MI.RemoveOperand(0);
10447       return;
10448     }
10449 
10450     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10451     // instruction, because the return type of these instructions is a vec2 of
10452     // the memory type, so it can be tied to the input operand.
10453     // This means these instructions always have a use, so we need to add a
10454     // special case to check if the atomic has only one extract_subreg use,
10455     // which itself has no uses.
10456     if ((Node->hasNUsesOfValue(1, 0) &&
10457          Node->use_begin()->isMachineOpcode() &&
10458          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10459          !Node->use_begin()->hasAnyUseOfValue(0))) {
10460       Register Def = MI.getOperand(0).getReg();
10461 
10462       // Change this into a noret atomic.
10463       MI.setDesc(TII->get(NoRetAtomicOp));
10464       MI.RemoveOperand(0);
10465 
10466       // If we only remove the def operand from the atomic instruction, the
10467       // extract_subreg will be left with a use of a vreg without a def.
10468       // So we need to insert an implicit_def to avoid machine verifier
10469       // errors.
10470       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10471               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10472     }
10473     return;
10474   }
10475 }
10476 
10477 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10478                               uint64_t Val) {
10479   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10480   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10481 }
10482 
10483 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10484                                                 const SDLoc &DL,
10485                                                 SDValue Ptr) const {
10486   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10487 
10488   // Build the half of the subregister with the constants before building the
10489   // full 128-bit register. If we are building multiple resource descriptors,
10490   // this will allow CSEing of the 2-component register.
10491   const SDValue Ops0[] = {
10492     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10493     buildSMovImm32(DAG, DL, 0),
10494     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10495     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10496     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10497   };
10498 
10499   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10500                                                 MVT::v2i32, Ops0), 0);
10501 
10502   // Combine the constants and the pointer.
10503   const SDValue Ops1[] = {
10504     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10505     Ptr,
10506     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10507     SubRegHi,
10508     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10509   };
10510 
10511   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10512 }
10513 
10514 /// Return a resource descriptor with the 'Add TID' bit enabled
10515 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10516 ///        of the resource descriptor) to create an offset, which is added to
10517 ///        the resource pointer.
10518 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10519                                            SDValue Ptr, uint32_t RsrcDword1,
10520                                            uint64_t RsrcDword2And3) const {
10521   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10522   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10523   if (RsrcDword1) {
10524     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10525                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10526                     0);
10527   }
10528 
10529   SDValue DataLo = buildSMovImm32(DAG, DL,
10530                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10531   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10532 
10533   const SDValue Ops[] = {
10534     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10535     PtrLo,
10536     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10537     PtrHi,
10538     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10539     DataLo,
10540     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10541     DataHi,
10542     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10543   };
10544 
10545   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10546 }
10547 
10548 //===----------------------------------------------------------------------===//
10549 //                         SI Inline Assembly Support
10550 //===----------------------------------------------------------------------===//
10551 
10552 std::pair<unsigned, const TargetRegisterClass *>
10553 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10554                                                StringRef Constraint,
10555                                                MVT VT) const {
10556   const TargetRegisterClass *RC = nullptr;
10557   if (Constraint.size() == 1) {
10558     switch (Constraint[0]) {
10559     default:
10560       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10561     case 's':
10562     case 'r':
10563       switch (VT.getSizeInBits()) {
10564       default:
10565         return std::make_pair(0U, nullptr);
10566       case 32:
10567       case 16:
10568         RC = &AMDGPU::SReg_32RegClass;
10569         break;
10570       case 64:
10571         RC = &AMDGPU::SGPR_64RegClass;
10572         break;
10573       case 96:
10574         RC = &AMDGPU::SReg_96RegClass;
10575         break;
10576       case 128:
10577         RC = &AMDGPU::SGPR_128RegClass;
10578         break;
10579       case 160:
10580         RC = &AMDGPU::SReg_160RegClass;
10581         break;
10582       case 256:
10583         RC = &AMDGPU::SReg_256RegClass;
10584         break;
10585       case 512:
10586         RC = &AMDGPU::SReg_512RegClass;
10587         break;
10588       }
10589       break;
10590     case 'v':
10591       switch (VT.getSizeInBits()) {
10592       default:
10593         return std::make_pair(0U, nullptr);
10594       case 32:
10595       case 16:
10596         RC = &AMDGPU::VGPR_32RegClass;
10597         break;
10598       case 64:
10599         RC = &AMDGPU::VReg_64RegClass;
10600         break;
10601       case 96:
10602         RC = &AMDGPU::VReg_96RegClass;
10603         break;
10604       case 128:
10605         RC = &AMDGPU::VReg_128RegClass;
10606         break;
10607       case 160:
10608         RC = &AMDGPU::VReg_160RegClass;
10609         break;
10610       case 256:
10611         RC = &AMDGPU::VReg_256RegClass;
10612         break;
10613       case 512:
10614         RC = &AMDGPU::VReg_512RegClass;
10615         break;
10616       }
10617       break;
10618     case 'a':
10619       if (!Subtarget->hasMAIInsts())
10620         break;
10621       switch (VT.getSizeInBits()) {
10622       default:
10623         return std::make_pair(0U, nullptr);
10624       case 32:
10625       case 16:
10626         RC = &AMDGPU::AGPR_32RegClass;
10627         break;
10628       case 64:
10629         RC = &AMDGPU::AReg_64RegClass;
10630         break;
10631       case 128:
10632         RC = &AMDGPU::AReg_128RegClass;
10633         break;
10634       case 512:
10635         RC = &AMDGPU::AReg_512RegClass;
10636         break;
10637       case 1024:
10638         RC = &AMDGPU::AReg_1024RegClass;
10639         // v32 types are not legal but we support them here.
10640         return std::make_pair(0U, RC);
10641       }
10642       break;
10643     }
10644     // We actually support i128, i16 and f16 as inline parameters
10645     // even if they are not reported as legal
10646     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10647                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10648       return std::make_pair(0U, RC);
10649   }
10650 
10651   if (Constraint.size() > 1) {
10652     if (Constraint[1] == 'v') {
10653       RC = &AMDGPU::VGPR_32RegClass;
10654     } else if (Constraint[1] == 's') {
10655       RC = &AMDGPU::SGPR_32RegClass;
10656     } else if (Constraint[1] == 'a') {
10657       RC = &AMDGPU::AGPR_32RegClass;
10658     }
10659 
10660     if (RC) {
10661       uint32_t Idx;
10662       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10663       if (!Failed && Idx < RC->getNumRegs())
10664         return std::make_pair(RC->getRegister(Idx), RC);
10665     }
10666   }
10667   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10668 }
10669 
10670 SITargetLowering::ConstraintType
10671 SITargetLowering::getConstraintType(StringRef Constraint) const {
10672   if (Constraint.size() == 1) {
10673     switch (Constraint[0]) {
10674     default: break;
10675     case 's':
10676     case 'v':
10677     case 'a':
10678       return C_RegisterClass;
10679     }
10680   }
10681   return TargetLowering::getConstraintType(Constraint);
10682 }
10683 
10684 // Figure out which registers should be reserved for stack access. Only after
10685 // the function is legalized do we know all of the non-spill stack objects or if
10686 // calls are present.
10687 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10688   MachineRegisterInfo &MRI = MF.getRegInfo();
10689   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10690   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10691   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10692 
10693   if (Info->isEntryFunction()) {
10694     // Callable functions have fixed registers used for stack access.
10695     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10696   }
10697 
10698   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10699                              Info->getStackPtrOffsetReg()));
10700   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10701     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10702 
10703   // We need to worry about replacing the default register with itself in case
10704   // of MIR testcases missing the MFI.
10705   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10706     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10707 
10708   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10709     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10710 
10711   if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) {
10712     MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
10713                        Info->getScratchWaveOffsetReg());
10714   }
10715 
10716   Info->limitOccupancy(MF);
10717 
10718   if (ST.isWave32() && !MF.empty()) {
10719     // Add VCC_HI def because many instructions marked as imp-use VCC where
10720     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10721     // having a use of undef.
10722 
10723     const SIInstrInfo *TII = ST.getInstrInfo();
10724     DebugLoc DL;
10725 
10726     MachineBasicBlock &MBB = MF.front();
10727     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10728     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10729 
10730     for (auto &MBB : MF) {
10731       for (auto &MI : MBB) {
10732         TII->fixImplicitOperands(MI);
10733       }
10734     }
10735   }
10736 
10737   TargetLoweringBase::finalizeLowering(MF);
10738 }
10739 
10740 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10741                                                      KnownBits &Known,
10742                                                      const APInt &DemandedElts,
10743                                                      const SelectionDAG &DAG,
10744                                                      unsigned Depth) const {
10745   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10746                                                 DAG, Depth);
10747 
10748   // Set the high bits to zero based on the maximum allowed scratch size per
10749   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10750   // calculation won't overflow, so assume the sign bit is never set.
10751   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10752 }
10753 
10754 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10755   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10756   const Align CacheLineAlign = Align(64);
10757 
10758   // Pre-GFX10 target did not benefit from loop alignment
10759   if (!ML || DisableLoopAlignment ||
10760       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10761       getSubtarget()->hasInstFwdPrefetchBug())
10762     return PrefAlign;
10763 
10764   // On GFX10 I$ is 4 x 64 bytes cache lines.
10765   // By default prefetcher keeps one cache line behind and reads two ahead.
10766   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10767   // behind and one ahead.
10768   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10769   // If loop fits 64 bytes it always spans no more than two cache lines and
10770   // does not need an alignment.
10771   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10772   // Else if loop is less or equal 192 bytes we need two lines behind.
10773 
10774   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10775   const MachineBasicBlock *Header = ML->getHeader();
10776   if (Header->getAlignment() != PrefAlign)
10777     return Header->getAlignment(); // Already processed.
10778 
10779   unsigned LoopSize = 0;
10780   for (const MachineBasicBlock *MBB : ML->blocks()) {
10781     // If inner loop block is aligned assume in average half of the alignment
10782     // size to be added as nops.
10783     if (MBB != Header)
10784       LoopSize += MBB->getAlignment().value() / 2;
10785 
10786     for (const MachineInstr &MI : *MBB) {
10787       LoopSize += TII->getInstSizeInBytes(MI);
10788       if (LoopSize > 192)
10789         return PrefAlign;
10790     }
10791   }
10792 
10793   if (LoopSize <= 64)
10794     return PrefAlign;
10795 
10796   if (LoopSize <= 128)
10797     return CacheLineAlign;
10798 
10799   // If any of parent loops is surrounded by prefetch instructions do not
10800   // insert new for inner loop, which would reset parent's settings.
10801   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10802     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10803       auto I = Exit->getFirstNonDebugInstr();
10804       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10805         return CacheLineAlign;
10806     }
10807   }
10808 
10809   MachineBasicBlock *Pre = ML->getLoopPreheader();
10810   MachineBasicBlock *Exit = ML->getExitBlock();
10811 
10812   if (Pre && Exit) {
10813     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10814             TII->get(AMDGPU::S_INST_PREFETCH))
10815       .addImm(1); // prefetch 2 lines behind PC
10816 
10817     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10818             TII->get(AMDGPU::S_INST_PREFETCH))
10819       .addImm(2); // prefetch 1 line behind PC
10820   }
10821 
10822   return CacheLineAlign;
10823 }
10824 
10825 LLVM_ATTRIBUTE_UNUSED
10826 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10827   assert(N->getOpcode() == ISD::CopyFromReg);
10828   do {
10829     // Follow the chain until we find an INLINEASM node.
10830     N = N->getOperand(0).getNode();
10831     if (N->getOpcode() == ISD::INLINEASM ||
10832         N->getOpcode() == ISD::INLINEASM_BR)
10833       return true;
10834   } while (N->getOpcode() == ISD::CopyFromReg);
10835   return false;
10836 }
10837 
10838 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10839   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10840 {
10841   switch (N->getOpcode()) {
10842     case ISD::CopyFromReg:
10843     {
10844       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10845       const MachineFunction * MF = FLI->MF;
10846       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10847       const MachineRegisterInfo &MRI = MF->getRegInfo();
10848       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10849       unsigned Reg = R->getReg();
10850       if (Register::isPhysicalRegister(Reg))
10851         return !TRI.isSGPRReg(MRI, Reg);
10852 
10853       if (MRI.isLiveIn(Reg)) {
10854         // workitem.id.x workitem.id.y workitem.id.z
10855         // Any VGPR formal argument is also considered divergent
10856         if (!TRI.isSGPRReg(MRI, Reg))
10857           return true;
10858         // Formal arguments of non-entry functions
10859         // are conservatively considered divergent
10860         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10861           return true;
10862         return false;
10863       }
10864       const Value *V = FLI->getValueFromVirtualReg(Reg);
10865       if (V)
10866         return KDA->isDivergent(V);
10867       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10868       return !TRI.isSGPRReg(MRI, Reg);
10869     }
10870     break;
10871     case ISD::LOAD: {
10872       const LoadSDNode *L = cast<LoadSDNode>(N);
10873       unsigned AS = L->getAddressSpace();
10874       // A flat load may access private memory.
10875       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10876     } break;
10877     case ISD::CALLSEQ_END:
10878     return true;
10879     break;
10880     case ISD::INTRINSIC_WO_CHAIN:
10881     {
10882 
10883     }
10884       return AMDGPU::isIntrinsicSourceOfDivergence(
10885       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10886     case ISD::INTRINSIC_W_CHAIN:
10887       return AMDGPU::isIntrinsicSourceOfDivergence(
10888       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10889   }
10890   return false;
10891 }
10892 
10893 bool SITargetLowering::denormalsEnabledForType(EVT VT) const {
10894   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10895   case MVT::f32:
10896     return Subtarget->hasFP32Denormals();
10897   case MVT::f64:
10898     return Subtarget->hasFP64Denormals();
10899   case MVT::f16:
10900     return Subtarget->hasFP16Denormals();
10901   default:
10902     return false;
10903   }
10904 }
10905 
10906 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
10907                                                     const SelectionDAG &DAG,
10908                                                     bool SNaN,
10909                                                     unsigned Depth) const {
10910   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
10911     const MachineFunction &MF = DAG.getMachineFunction();
10912     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10913 
10914     if (Info->getMode().DX10Clamp)
10915       return true; // Clamped to 0.
10916     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10917   }
10918 
10919   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
10920                                                             SNaN, Depth);
10921 }
10922 
10923 TargetLowering::AtomicExpansionKind
10924 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
10925   switch (RMW->getOperation()) {
10926   case AtomicRMWInst::FAdd: {
10927     Type *Ty = RMW->getType();
10928 
10929     // We don't have a way to support 16-bit atomics now, so just leave them
10930     // as-is.
10931     if (Ty->isHalfTy())
10932       return AtomicExpansionKind::None;
10933 
10934     if (!Ty->isFloatTy())
10935       return AtomicExpansionKind::CmpXChg;
10936 
10937     // TODO: Do have these for flat. Older targets also had them for buffers.
10938     unsigned AS = RMW->getPointerAddressSpace();
10939     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10940       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
10941   }
10942   default:
10943     break;
10944   }
10945 
10946   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
10947 }
10948 
10949 const TargetRegisterClass *
10950 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
10951   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
10952   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10953   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
10954     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
10955                                                : &AMDGPU::SReg_32RegClass;
10956   if (!TRI->isSGPRClass(RC) && !isDivergent)
10957     return TRI->getEquivalentSGPRClass(RC);
10958   else if (TRI->isSGPRClass(RC) && isDivergent)
10959     return TRI->getEquivalentVGPRClass(RC);
10960 
10961   return RC;
10962 }
10963 
10964 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited) {
10965   if (!Visited.insert(V).second)
10966     return false;
10967   bool Result = false;
10968   for (auto U : V->users()) {
10969     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
10970       if (V == U->getOperand(1)) {
10971         switch (Intrinsic->getIntrinsicID()) {
10972         default:
10973           Result = false;
10974           break;
10975         case Intrinsic::amdgcn_if_break:
10976         case Intrinsic::amdgcn_if:
10977         case Intrinsic::amdgcn_else:
10978           Result = true;
10979           break;
10980         }
10981       }
10982       if (V == U->getOperand(0)) {
10983         switch (Intrinsic->getIntrinsicID()) {
10984         default:
10985           Result = false;
10986           break;
10987         case Intrinsic::amdgcn_end_cf:
10988         case Intrinsic::amdgcn_loop:
10989           Result = true;
10990           break;
10991         }
10992       }
10993     } else {
10994       Result = hasCFUser(U, Visited);
10995     }
10996     if (Result)
10997       break;
10998   }
10999   return Result;
11000 }
11001 
11002 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11003                                                const Value *V) const {
11004   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) {
11005     switch (Intrinsic->getIntrinsicID()) {
11006     default:
11007       return false;
11008     case Intrinsic::amdgcn_if_break:
11009       return true;
11010     }
11011   }
11012   if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) {
11013     if (const IntrinsicInst *Intrinsic =
11014             dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) {
11015       switch (Intrinsic->getIntrinsicID()) {
11016       default:
11017         return false;
11018       case Intrinsic::amdgcn_if:
11019       case Intrinsic::amdgcn_else: {
11020         ArrayRef<unsigned> Indices = ExtValue->getIndices();
11021         if (Indices.size() == 1 && Indices[0] == 1) {
11022           return true;
11023         }
11024       }
11025       }
11026     }
11027   }
11028   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11029     if (isa<InlineAsm>(CI->getCalledValue())) {
11030       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11031       ImmutableCallSite CS(CI);
11032       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11033           MF.getDataLayout(), Subtarget->getRegisterInfo(), CS);
11034       for (auto &TC : TargetConstraints) {
11035         if (TC.Type == InlineAsm::isOutput) {
11036           ComputeConstraintToUse(TC, SDValue());
11037           unsigned AssignedReg;
11038           const TargetRegisterClass *RC;
11039           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11040               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11041           if (RC) {
11042             MachineRegisterInfo &MRI = MF.getRegInfo();
11043             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11044               return true;
11045             else if (SIRI->isSGPRClass(RC))
11046               return true;
11047           }
11048         }
11049       }
11050     }
11051   }
11052   SmallPtrSet<const Value *, 16> Visited;
11053   return hasCFUser(V, Visited);
11054 }
11055