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> DisableLoopAlignment(
94   "amdgpu-disable-loop-alignment",
95   cl::desc("Do not align and prefetch loops"),
96   cl::init(false));
97 
98 static bool hasFP32Denormals(const MachineFunction &MF) {
99   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
100   return Info->getMode().allFP32Denormals();
101 }
102 
103 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
104   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
105   return Info->getMode().allFP64FP16Denormals();
106 }
107 
108 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
109   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
110   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
111     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
112       return AMDGPU::SGPR0 + Reg;
113     }
114   }
115   llvm_unreachable("Cannot allocate sgpr");
116 }
117 
118 SITargetLowering::SITargetLowering(const TargetMachine &TM,
119                                    const GCNSubtarget &STI)
120     : AMDGPUTargetLowering(TM, STI),
121       Subtarget(&STI) {
122   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
123   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
124 
125   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
126   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
127 
128   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
129   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
130   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
131 
132   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
133   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
134 
135   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
136   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
137 
138   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
139   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
140 
141   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
142   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
143 
144   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
145   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
146 
147   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
148   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
149 
150   if (Subtarget->has16BitInsts()) {
151     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
152     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
153 
154     // Unless there are also VOP3P operations, not operations are really legal.
155     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
156     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
157     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
158     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
159   }
160 
161   if (Subtarget->hasMAIInsts()) {
162     addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
163     addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
164   }
165 
166   computeRegisterProperties(Subtarget->getRegisterInfo());
167 
168   // The boolean content concept here is too inflexible. Compares only ever
169   // really produce a 1-bit result. Any copy/extend from these will turn into a
170   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
171   // it's what most targets use.
172   setBooleanContents(ZeroOrOneBooleanContent);
173   setBooleanVectorContents(ZeroOrOneBooleanContent);
174 
175   // We need to custom lower vector stores from local memory
176   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
177   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
178   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
179   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
180   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
181   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
182   setOperationAction(ISD::LOAD, MVT::i1, Custom);
183   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
184 
185   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
186   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
187   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
188   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
189   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
190   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
191   setOperationAction(ISD::STORE, MVT::i1, Custom);
192   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
193 
194   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
195   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
196   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
197   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
198   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
199   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
200   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
201   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
202   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
203   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
204   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
205   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
206   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
207   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
208   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
209   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
210 
211   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
212   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
213 
214   setOperationAction(ISD::SELECT, MVT::i1, Promote);
215   setOperationAction(ISD::SELECT, MVT::i64, Custom);
216   setOperationAction(ISD::SELECT, MVT::f64, Promote);
217   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
218 
219   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
220   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
221   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
222   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
223   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
224 
225   setOperationAction(ISD::SETCC, MVT::i1, Promote);
226   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
227   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
228   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
229 
230   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
231   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
232 
233   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
234   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
235   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
236   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
237   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
238   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
239   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
240   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
241 
242   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
243   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
244   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
245   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
246   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
247   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
248 
249   setOperationAction(ISD::UADDO, MVT::i32, Legal);
250   setOperationAction(ISD::USUBO, MVT::i32, Legal);
251 
252   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
253   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
254 
255   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
256   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
257   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
258 
259 #if 0
260   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
261   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
262 #endif
263 
264   // We only support LOAD/STORE and vector manipulation ops for vectors
265   // with > 4 elements.
266   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
267                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
268                   MVT::v32i32, MVT::v32f32 }) {
269     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
270       switch (Op) {
271       case ISD::LOAD:
272       case ISD::STORE:
273       case ISD::BUILD_VECTOR:
274       case ISD::BITCAST:
275       case ISD::EXTRACT_VECTOR_ELT:
276       case ISD::INSERT_VECTOR_ELT:
277       case ISD::INSERT_SUBVECTOR:
278       case ISD::EXTRACT_SUBVECTOR:
279       case ISD::SCALAR_TO_VECTOR:
280         break;
281       case ISD::CONCAT_VECTORS:
282         setOperationAction(Op, VT, Custom);
283         break;
284       default:
285         setOperationAction(Op, VT, Expand);
286         break;
287       }
288     }
289   }
290 
291   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
292 
293   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
294   // is expanded to avoid having two separate loops in case the index is a VGPR.
295 
296   // Most operations are naturally 32-bit vector operations. We only support
297   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
298   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
299     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
300     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
301 
302     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
303     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
304 
305     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
306     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
307 
308     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
309     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
310   }
311 
312   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
313   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
314   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
315   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
316 
317   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
318   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
319 
320   // Avoid stack access for these.
321   // TODO: Generalize to more vector types.
322   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
323   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
324   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
325   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
326 
327   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
328   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
329   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
330   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
331   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
332 
333   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
334   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
335   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
336 
337   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
338   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
339   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
340   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
341 
342   // Deal with vec3 vector operations when widened to vec4.
343   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
344   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
345   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
346   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
347 
348   // Deal with vec5 vector operations when widened to vec8.
349   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
350   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
351   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
352   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
353 
354   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
355   // and output demarshalling
356   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
357   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
358 
359   // We can't return success/failure, only the old value,
360   // let LLVM add the comparison
361   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
362   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
363 
364   if (Subtarget->hasFlatAddressSpace()) {
365     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
366     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
367   }
368 
369   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
370 
371   // FIXME: This should be narrowed to i32, but that only happens if i64 is
372   // illegal.
373   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
374   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
375   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
376 
377   // On SI this is s_memtime and s_memrealtime on VI.
378   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
379   setOperationAction(ISD::TRAP, MVT::Other, Custom);
380   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
381 
382   if (Subtarget->has16BitInsts()) {
383     setOperationAction(ISD::FPOW, MVT::f16, Promote);
384     setOperationAction(ISD::FLOG, MVT::f16, Custom);
385     setOperationAction(ISD::FEXP, MVT::f16, Custom);
386     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
387   }
388 
389   // v_mad_f32 does not support denormals. We report it as unconditionally
390   // legal, and the context where it is formed will disallow it when fp32
391   // denormals are enabled.
392   setOperationAction(ISD::FMAD, MVT::f32, Legal);
393 
394   if (!Subtarget->hasBFI()) {
395     // fcopysign can be done in a single instruction with BFI.
396     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
397     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
398   }
399 
400   if (!Subtarget->hasBCNT(32))
401     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
402 
403   if (!Subtarget->hasBCNT(64))
404     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
405 
406   if (Subtarget->hasFFBH())
407     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
408 
409   if (Subtarget->hasFFBL())
410     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
411 
412   // We only really have 32-bit BFE instructions (and 16-bit on VI).
413   //
414   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
415   // effort to match them now. We want this to be false for i64 cases when the
416   // extraction isn't restricted to the upper or lower half. Ideally we would
417   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
418   // span the midpoint are probably relatively rare, so don't worry about them
419   // for now.
420   if (Subtarget->hasBFE())
421     setHasExtractBitsInsn(true);
422 
423   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
424   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
425   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
426   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
427 
428 
429   // These are really only legal for ieee_mode functions. We should be avoiding
430   // them for functions that don't have ieee_mode enabled, so just say they are
431   // legal.
432   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
433   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
434   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
435   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
436 
437 
438   if (Subtarget->haveRoundOpsF64()) {
439     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
440     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
441     setOperationAction(ISD::FRINT, MVT::f64, Legal);
442   } else {
443     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
444     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
445     setOperationAction(ISD::FRINT, MVT::f64, Custom);
446     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
447   }
448 
449   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
450 
451   setOperationAction(ISD::FSIN, MVT::f32, Custom);
452   setOperationAction(ISD::FCOS, MVT::f32, Custom);
453   setOperationAction(ISD::FDIV, MVT::f32, Custom);
454   setOperationAction(ISD::FDIV, MVT::f64, Custom);
455 
456   if (Subtarget->has16BitInsts()) {
457     setOperationAction(ISD::Constant, MVT::i16, Legal);
458 
459     setOperationAction(ISD::SMIN, MVT::i16, Legal);
460     setOperationAction(ISD::SMAX, MVT::i16, Legal);
461 
462     setOperationAction(ISD::UMIN, MVT::i16, Legal);
463     setOperationAction(ISD::UMAX, MVT::i16, Legal);
464 
465     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
466     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
467 
468     setOperationAction(ISD::ROTR, MVT::i16, Promote);
469     setOperationAction(ISD::ROTL, MVT::i16, Promote);
470 
471     setOperationAction(ISD::SDIV, MVT::i16, Promote);
472     setOperationAction(ISD::UDIV, MVT::i16, Promote);
473     setOperationAction(ISD::SREM, MVT::i16, Promote);
474     setOperationAction(ISD::UREM, MVT::i16, Promote);
475 
476     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
477 
478     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
479     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
480     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
481     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
482     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
483 
484     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
485 
486     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
487 
488     setOperationAction(ISD::LOAD, MVT::i16, Custom);
489 
490     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
491 
492     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
493     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
494     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
495     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
496 
497     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
498     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
499 
500     // F16 - Constant Actions.
501     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
502 
503     // F16 - Load/Store Actions.
504     setOperationAction(ISD::LOAD, MVT::f16, Promote);
505     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
506     setOperationAction(ISD::STORE, MVT::f16, Promote);
507     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
508 
509     // F16 - VOP1 Actions.
510     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
511     setOperationAction(ISD::FCOS, MVT::f16, Custom);
512     setOperationAction(ISD::FSIN, MVT::f16, Custom);
513 
514     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
515     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
516 
517     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
518     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
519     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
520     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
521     setOperationAction(ISD::FROUND, MVT::f16, Custom);
522 
523     // F16 - VOP2 Actions.
524     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
525     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
526 
527     setOperationAction(ISD::FDIV, MVT::f16, Custom);
528 
529     // F16 - VOP3 Actions.
530     setOperationAction(ISD::FMA, MVT::f16, Legal);
531     if (STI.hasMadF16())
532       setOperationAction(ISD::FMAD, MVT::f16, Legal);
533 
534     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
535       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
536         switch (Op) {
537         case ISD::LOAD:
538         case ISD::STORE:
539         case ISD::BUILD_VECTOR:
540         case ISD::BITCAST:
541         case ISD::EXTRACT_VECTOR_ELT:
542         case ISD::INSERT_VECTOR_ELT:
543         case ISD::INSERT_SUBVECTOR:
544         case ISD::EXTRACT_SUBVECTOR:
545         case ISD::SCALAR_TO_VECTOR:
546           break;
547         case ISD::CONCAT_VECTORS:
548           setOperationAction(Op, VT, Custom);
549           break;
550         default:
551           setOperationAction(Op, VT, Expand);
552           break;
553         }
554       }
555     }
556 
557     // v_perm_b32 can handle either of these.
558     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
559     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
560     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
561 
562     // XXX - Do these do anything? Vector constants turn into build_vector.
563     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
564     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
565 
566     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
567     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
568 
569     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
570     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
571     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
572     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
573 
574     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
575     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
576     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
577     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
578 
579     setOperationAction(ISD::AND, MVT::v2i16, Promote);
580     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
581     setOperationAction(ISD::OR, MVT::v2i16, Promote);
582     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
583     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
584     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
585 
586     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
587     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
588     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
589     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
590 
591     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
592     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
593     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
594     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
595 
596     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
597     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
598     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
599     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
600 
601     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
602     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
603     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
604 
605     if (!Subtarget->hasVOP3PInsts()) {
606       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
607       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
608     }
609 
610     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
611     // This isn't really legal, but this avoids the legalizer unrolling it (and
612     // allows matching fneg (fabs x) patterns)
613     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
614 
615     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
616     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
617     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
618     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
619 
620     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
621     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
622 
623     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
624     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
625   }
626 
627   if (Subtarget->hasVOP3PInsts()) {
628     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
629     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
630     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
631     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
632     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
633     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
634     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
635     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
636     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
637     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
638 
639     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
640     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
641     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
642 
643     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
644     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
645 
646     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
647 
648     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
649     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
650 
651     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
652     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
653 
654     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
655     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
656     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
657     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
658     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
659     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
660 
661     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
662     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
663     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
664     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
665 
666     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
667     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
668     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
669 
670     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
671     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
672 
673     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
674     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
675     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
676 
677     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
678     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
679     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
680   }
681 
682   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
683   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
684 
685   if (Subtarget->has16BitInsts()) {
686     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
687     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
688     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
689     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
690   } else {
691     // Legalization hack.
692     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
693     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
694 
695     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
696     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
697   }
698 
699   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
700     setOperationAction(ISD::SELECT, VT, Custom);
701   }
702 
703   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
704   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
705   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
706   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
707   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
708   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
709   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
710 
711   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
712   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
713   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
714   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
715   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
716   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
717   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
718   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
719   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
720 
721   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
722   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
723   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
724   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
725   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
726   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
727   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
728   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
729 
730   setTargetDAGCombine(ISD::ADD);
731   setTargetDAGCombine(ISD::ADDCARRY);
732   setTargetDAGCombine(ISD::SUB);
733   setTargetDAGCombine(ISD::SUBCARRY);
734   setTargetDAGCombine(ISD::FADD);
735   setTargetDAGCombine(ISD::FSUB);
736   setTargetDAGCombine(ISD::FMINNUM);
737   setTargetDAGCombine(ISD::FMAXNUM);
738   setTargetDAGCombine(ISD::FMINNUM_IEEE);
739   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
740   setTargetDAGCombine(ISD::FMA);
741   setTargetDAGCombine(ISD::SMIN);
742   setTargetDAGCombine(ISD::SMAX);
743   setTargetDAGCombine(ISD::UMIN);
744   setTargetDAGCombine(ISD::UMAX);
745   setTargetDAGCombine(ISD::SETCC);
746   setTargetDAGCombine(ISD::AND);
747   setTargetDAGCombine(ISD::OR);
748   setTargetDAGCombine(ISD::XOR);
749   setTargetDAGCombine(ISD::SINT_TO_FP);
750   setTargetDAGCombine(ISD::UINT_TO_FP);
751   setTargetDAGCombine(ISD::FCANONICALIZE);
752   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
753   setTargetDAGCombine(ISD::ZERO_EXTEND);
754   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
755   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
756   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
757 
758   // All memory operations. Some folding on the pointer operand is done to help
759   // matching the constant offsets in the addressing modes.
760   setTargetDAGCombine(ISD::LOAD);
761   setTargetDAGCombine(ISD::STORE);
762   setTargetDAGCombine(ISD::ATOMIC_LOAD);
763   setTargetDAGCombine(ISD::ATOMIC_STORE);
764   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
765   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
766   setTargetDAGCombine(ISD::ATOMIC_SWAP);
767   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
768   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
769   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
770   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
771   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
772   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
773   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
774   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
775   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
776   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
777   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
778 
779   setSchedulingPreference(Sched::RegPressure);
780 }
781 
782 const GCNSubtarget *SITargetLowering::getSubtarget() const {
783   return Subtarget;
784 }
785 
786 //===----------------------------------------------------------------------===//
787 // TargetLowering queries
788 //===----------------------------------------------------------------------===//
789 
790 // v_mad_mix* support a conversion from f16 to f32.
791 //
792 // There is only one special case when denormals are enabled we don't currently,
793 // where this is OK to use.
794 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
795                                        EVT DestVT, EVT SrcVT) const {
796   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
797           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
798     DestVT.getScalarType() == MVT::f32 &&
799     SrcVT.getScalarType() == MVT::f16 &&
800     // TODO: This probably only requires no input flushing?
801     !hasFP32Denormals(DAG.getMachineFunction());
802 }
803 
804 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
805   // SI has some legal vector types, but no legal vector operations. Say no
806   // shuffles are legal in order to prefer scalarizing some vector operations.
807   return false;
808 }
809 
810 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
811                                                     CallingConv::ID CC,
812                                                     EVT VT) const {
813   if (CC == CallingConv::AMDGPU_KERNEL)
814     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
815 
816   if (VT.isVector()) {
817     EVT ScalarVT = VT.getScalarType();
818     unsigned Size = ScalarVT.getSizeInBits();
819     if (Size == 32)
820       return ScalarVT.getSimpleVT();
821 
822     if (Size > 32)
823       return MVT::i32;
824 
825     if (Size == 16 && Subtarget->has16BitInsts())
826       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
827   } else if (VT.getSizeInBits() > 32)
828     return MVT::i32;
829 
830   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
831 }
832 
833 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
834                                                          CallingConv::ID CC,
835                                                          EVT VT) const {
836   if (CC == CallingConv::AMDGPU_KERNEL)
837     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
838 
839   if (VT.isVector()) {
840     unsigned NumElts = VT.getVectorNumElements();
841     EVT ScalarVT = VT.getScalarType();
842     unsigned Size = ScalarVT.getSizeInBits();
843 
844     if (Size == 32)
845       return NumElts;
846 
847     if (Size > 32)
848       return NumElts * ((Size + 31) / 32);
849 
850     if (Size == 16 && Subtarget->has16BitInsts())
851       return (NumElts + 1) / 2;
852   } else if (VT.getSizeInBits() > 32)
853     return (VT.getSizeInBits() + 31) / 32;
854 
855   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
856 }
857 
858 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
859   LLVMContext &Context, CallingConv::ID CC,
860   EVT VT, EVT &IntermediateVT,
861   unsigned &NumIntermediates, MVT &RegisterVT) const {
862   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
863     unsigned NumElts = VT.getVectorNumElements();
864     EVT ScalarVT = VT.getScalarType();
865     unsigned Size = ScalarVT.getSizeInBits();
866     if (Size == 32) {
867       RegisterVT = ScalarVT.getSimpleVT();
868       IntermediateVT = RegisterVT;
869       NumIntermediates = NumElts;
870       return NumIntermediates;
871     }
872 
873     if (Size > 32) {
874       RegisterVT = MVT::i32;
875       IntermediateVT = RegisterVT;
876       NumIntermediates = NumElts * ((Size + 31) / 32);
877       return NumIntermediates;
878     }
879 
880     // FIXME: We should fix the ABI to be the same on targets without 16-bit
881     // support, but unless we can properly handle 3-vectors, it will be still be
882     // inconsistent.
883     if (Size == 16 && Subtarget->has16BitInsts()) {
884       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
885       IntermediateVT = RegisterVT;
886       NumIntermediates = (NumElts + 1) / 2;
887       return NumIntermediates;
888     }
889   }
890 
891   return TargetLowering::getVectorTypeBreakdownForCallingConv(
892     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
893 }
894 
895 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
896   assert(DMaskLanes != 0);
897 
898   if (auto *VT = dyn_cast<VectorType>(Ty)) {
899     unsigned NumElts = std::min(DMaskLanes,
900                                 static_cast<unsigned>(VT->getNumElements()));
901     return EVT::getVectorVT(Ty->getContext(),
902                             EVT::getEVT(VT->getElementType()),
903                             NumElts);
904   }
905 
906   return EVT::getEVT(Ty);
907 }
908 
909 // Peek through TFE struct returns to only use the data size.
910 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
911   auto *ST = dyn_cast<StructType>(Ty);
912   if (!ST)
913     return memVTFromImageData(Ty, DMaskLanes);
914 
915   // Some intrinsics return an aggregate type - special case to work out the
916   // correct memVT.
917   //
918   // Only limited forms of aggregate type currently expected.
919   if (ST->getNumContainedTypes() != 2 ||
920       !ST->getContainedType(1)->isIntegerTy(32))
921     return EVT();
922   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
923 }
924 
925 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
926                                           const CallInst &CI,
927                                           MachineFunction &MF,
928                                           unsigned IntrID) const {
929   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
930           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
931     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
932                                                   (Intrinsic::ID)IntrID);
933     if (Attr.hasFnAttribute(Attribute::ReadNone))
934       return false;
935 
936     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
937 
938     if (RsrcIntr->IsImage) {
939       Info.ptrVal = MFI->getImagePSV(
940         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
941         CI.getArgOperand(RsrcIntr->RsrcArg));
942       Info.align.reset();
943     } else {
944       Info.ptrVal = MFI->getBufferPSV(
945         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
946         CI.getArgOperand(RsrcIntr->RsrcArg));
947     }
948 
949     Info.flags = MachineMemOperand::MODereferenceable;
950     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
951       unsigned DMaskLanes = 4;
952 
953       if (RsrcIntr->IsImage) {
954         const AMDGPU::ImageDimIntrinsicInfo *Intr
955           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
956         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
957           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
958 
959         if (!BaseOpcode->Gather4) {
960           // If this isn't a gather, we may have excess loaded elements in the
961           // IR type. Check the dmask for the real number of elements loaded.
962           unsigned DMask
963             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
964           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
965         }
966 
967         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
968       } else
969         Info.memVT = EVT::getEVT(CI.getType());
970 
971       // FIXME: What does alignment mean for an image?
972       Info.opc = ISD::INTRINSIC_W_CHAIN;
973       Info.flags |= MachineMemOperand::MOLoad;
974     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
975       Info.opc = ISD::INTRINSIC_VOID;
976 
977       Type *DataTy = CI.getArgOperand(0)->getType();
978       if (RsrcIntr->IsImage) {
979         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
980         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
981         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
982       } else
983         Info.memVT = EVT::getEVT(DataTy);
984 
985       Info.flags |= MachineMemOperand::MOStore;
986     } else {
987       // Atomic
988       Info.opc = ISD::INTRINSIC_W_CHAIN;
989       Info.memVT = MVT::getVT(CI.getType());
990       Info.flags = MachineMemOperand::MOLoad |
991                    MachineMemOperand::MOStore |
992                    MachineMemOperand::MODereferenceable;
993 
994       // XXX - Should this be volatile without known ordering?
995       Info.flags |= MachineMemOperand::MOVolatile;
996     }
997     return true;
998   }
999 
1000   switch (IntrID) {
1001   case Intrinsic::amdgcn_atomic_inc:
1002   case Intrinsic::amdgcn_atomic_dec:
1003   case Intrinsic::amdgcn_ds_ordered_add:
1004   case Intrinsic::amdgcn_ds_ordered_swap:
1005   case Intrinsic::amdgcn_ds_fadd:
1006   case Intrinsic::amdgcn_ds_fmin:
1007   case Intrinsic::amdgcn_ds_fmax: {
1008     Info.opc = ISD::INTRINSIC_W_CHAIN;
1009     Info.memVT = MVT::getVT(CI.getType());
1010     Info.ptrVal = CI.getOperand(0);
1011     Info.align.reset();
1012     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1013 
1014     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1015     if (!Vol->isZero())
1016       Info.flags |= MachineMemOperand::MOVolatile;
1017 
1018     return true;
1019   }
1020   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1021     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1022 
1023     Info.opc = ISD::INTRINSIC_VOID;
1024     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1025     Info.ptrVal = MFI->getBufferPSV(
1026       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1027       CI.getArgOperand(1));
1028     Info.align.reset();
1029     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1030 
1031     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1032     if (!Vol || !Vol->isZero())
1033       Info.flags |= MachineMemOperand::MOVolatile;
1034 
1035     return true;
1036   }
1037   case Intrinsic::amdgcn_global_atomic_fadd: {
1038     Info.opc = ISD::INTRINSIC_VOID;
1039     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1040                             ->getPointerElementType());
1041     Info.ptrVal = CI.getOperand(0);
1042     Info.align.reset();
1043     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1044 
1045     return true;
1046   }
1047   case Intrinsic::amdgcn_ds_append:
1048   case Intrinsic::amdgcn_ds_consume: {
1049     Info.opc = ISD::INTRINSIC_W_CHAIN;
1050     Info.memVT = MVT::getVT(CI.getType());
1051     Info.ptrVal = CI.getOperand(0);
1052     Info.align.reset();
1053     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1054 
1055     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1056     if (!Vol->isZero())
1057       Info.flags |= MachineMemOperand::MOVolatile;
1058 
1059     return true;
1060   }
1061   case Intrinsic::amdgcn_ds_gws_init:
1062   case Intrinsic::amdgcn_ds_gws_barrier:
1063   case Intrinsic::amdgcn_ds_gws_sema_v:
1064   case Intrinsic::amdgcn_ds_gws_sema_br:
1065   case Intrinsic::amdgcn_ds_gws_sema_p:
1066   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1067     Info.opc = ISD::INTRINSIC_VOID;
1068 
1069     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1070     Info.ptrVal =
1071         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1072 
1073     // This is an abstract access, but we need to specify a type and size.
1074     Info.memVT = MVT::i32;
1075     Info.size = 4;
1076     Info.align = Align(4);
1077 
1078     Info.flags = MachineMemOperand::MOStore;
1079     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1080       Info.flags = MachineMemOperand::MOLoad;
1081     return true;
1082   }
1083   default:
1084     return false;
1085   }
1086 }
1087 
1088 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1089                                             SmallVectorImpl<Value*> &Ops,
1090                                             Type *&AccessTy) const {
1091   switch (II->getIntrinsicID()) {
1092   case Intrinsic::amdgcn_atomic_inc:
1093   case Intrinsic::amdgcn_atomic_dec:
1094   case Intrinsic::amdgcn_ds_ordered_add:
1095   case Intrinsic::amdgcn_ds_ordered_swap:
1096   case Intrinsic::amdgcn_ds_fadd:
1097   case Intrinsic::amdgcn_ds_fmin:
1098   case Intrinsic::amdgcn_ds_fmax: {
1099     Value *Ptr = II->getArgOperand(0);
1100     AccessTy = II->getType();
1101     Ops.push_back(Ptr);
1102     return true;
1103   }
1104   default:
1105     return false;
1106   }
1107 }
1108 
1109 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1110   if (!Subtarget->hasFlatInstOffsets()) {
1111     // Flat instructions do not have offsets, and only have the register
1112     // address.
1113     return AM.BaseOffs == 0 && AM.Scale == 0;
1114   }
1115 
1116   return AM.Scale == 0 &&
1117          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1118                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1119                                   /*Signed=*/false));
1120 }
1121 
1122 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1123   if (Subtarget->hasFlatGlobalInsts())
1124     return AM.Scale == 0 &&
1125            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1126                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1127                                     /*Signed=*/true));
1128 
1129   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1130       // Assume the we will use FLAT for all global memory accesses
1131       // on VI.
1132       // FIXME: This assumption is currently wrong.  On VI we still use
1133       // MUBUF instructions for the r + i addressing mode.  As currently
1134       // implemented, the MUBUF instructions only work on buffer < 4GB.
1135       // It may be possible to support > 4GB buffers with MUBUF instructions,
1136       // by setting the stride value in the resource descriptor which would
1137       // increase the size limit to (stride * 4GB).  However, this is risky,
1138       // because it has never been validated.
1139     return isLegalFlatAddressingMode(AM);
1140   }
1141 
1142   return isLegalMUBUFAddressingMode(AM);
1143 }
1144 
1145 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1146   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1147   // additionally can do r + r + i with addr64. 32-bit has more addressing
1148   // mode options. Depending on the resource constant, it can also do
1149   // (i64 r0) + (i32 r1) * (i14 i).
1150   //
1151   // Private arrays end up using a scratch buffer most of the time, so also
1152   // assume those use MUBUF instructions. Scratch loads / stores are currently
1153   // implemented as mubuf instructions with offen bit set, so slightly
1154   // different than the normal addr64.
1155   if (!isUInt<12>(AM.BaseOffs))
1156     return false;
1157 
1158   // FIXME: Since we can split immediate into soffset and immediate offset,
1159   // would it make sense to allow any immediate?
1160 
1161   switch (AM.Scale) {
1162   case 0: // r + i or just i, depending on HasBaseReg.
1163     return true;
1164   case 1:
1165     return true; // We have r + r or r + i.
1166   case 2:
1167     if (AM.HasBaseReg) {
1168       // Reject 2 * r + r.
1169       return false;
1170     }
1171 
1172     // Allow 2 * r as r + r
1173     // Or  2 * r + i is allowed as r + r + i.
1174     return true;
1175   default: // Don't allow n * r
1176     return false;
1177   }
1178 }
1179 
1180 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1181                                              const AddrMode &AM, Type *Ty,
1182                                              unsigned AS, Instruction *I) const {
1183   // No global is ever allowed as a base.
1184   if (AM.BaseGV)
1185     return false;
1186 
1187   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1188     return isLegalGlobalAddressingMode(AM);
1189 
1190   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1191       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1192       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1193     // If the offset isn't a multiple of 4, it probably isn't going to be
1194     // correctly aligned.
1195     // FIXME: Can we get the real alignment here?
1196     if (AM.BaseOffs % 4 != 0)
1197       return isLegalMUBUFAddressingMode(AM);
1198 
1199     // There are no SMRD extloads, so if we have to do a small type access we
1200     // will use a MUBUF load.
1201     // FIXME?: We also need to do this if unaligned, but we don't know the
1202     // alignment here.
1203     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1204       return isLegalGlobalAddressingMode(AM);
1205 
1206     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1207       // SMRD instructions have an 8-bit, dword offset on SI.
1208       if (!isUInt<8>(AM.BaseOffs / 4))
1209         return false;
1210     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1211       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1212       // in 8-bits, it can use a smaller encoding.
1213       if (!isUInt<32>(AM.BaseOffs / 4))
1214         return false;
1215     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1216       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1217       if (!isUInt<20>(AM.BaseOffs))
1218         return false;
1219     } else
1220       llvm_unreachable("unhandled generation");
1221 
1222     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1223       return true;
1224 
1225     if (AM.Scale == 1 && AM.HasBaseReg)
1226       return true;
1227 
1228     return false;
1229 
1230   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1231     return isLegalMUBUFAddressingMode(AM);
1232   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1233              AS == AMDGPUAS::REGION_ADDRESS) {
1234     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1235     // field.
1236     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1237     // an 8-bit dword offset but we don't know the alignment here.
1238     if (!isUInt<16>(AM.BaseOffs))
1239       return false;
1240 
1241     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1242       return true;
1243 
1244     if (AM.Scale == 1 && AM.HasBaseReg)
1245       return true;
1246 
1247     return false;
1248   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1249              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1250     // For an unknown address space, this usually means that this is for some
1251     // reason being used for pure arithmetic, and not based on some addressing
1252     // computation. We don't have instructions that compute pointers with any
1253     // addressing modes, so treat them as having no offset like flat
1254     // instructions.
1255     return isLegalFlatAddressingMode(AM);
1256   }
1257 
1258   // Assume a user alias of global for unknown address spaces.
1259   return isLegalGlobalAddressingMode(AM);
1260 }
1261 
1262 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1263                                         const SelectionDAG &DAG) const {
1264   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1265     return (MemVT.getSizeInBits() <= 4 * 32);
1266   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1267     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1268     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1269   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1270     return (MemVT.getSizeInBits() <= 2 * 32);
1271   }
1272   return true;
1273 }
1274 
1275 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1276     unsigned Size, unsigned AddrSpace, unsigned Align,
1277     MachineMemOperand::Flags Flags, bool *IsFast) const {
1278   if (IsFast)
1279     *IsFast = false;
1280 
1281   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1282       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1283     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1284     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1285     // with adjacent offsets.
1286     bool AlignedBy4 = (Align % 4 == 0);
1287     if (IsFast)
1288       *IsFast = AlignedBy4;
1289 
1290     return AlignedBy4;
1291   }
1292 
1293   // FIXME: We have to be conservative here and assume that flat operations
1294   // will access scratch.  If we had access to the IR function, then we
1295   // could determine if any private memory was used in the function.
1296   if (!Subtarget->hasUnalignedScratchAccess() &&
1297       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1298        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1299     bool AlignedBy4 = Align >= 4;
1300     if (IsFast)
1301       *IsFast = AlignedBy4;
1302 
1303     return AlignedBy4;
1304   }
1305 
1306   if (Subtarget->hasUnalignedBufferAccess()) {
1307     // If we have an uniform constant load, it still requires using a slow
1308     // buffer instruction if unaligned.
1309     if (IsFast) {
1310       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1311       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1312       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1313                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1314         Align >= 4 : Align != 2;
1315     }
1316 
1317     return true;
1318   }
1319 
1320   // Smaller than dword value must be aligned.
1321   if (Size < 32)
1322     return false;
1323 
1324   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1325   // byte-address are ignored, thus forcing Dword alignment.
1326   // This applies to private, global, and constant memory.
1327   if (IsFast)
1328     *IsFast = true;
1329 
1330   return Size >= 32 && Align >= 4;
1331 }
1332 
1333 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1334     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1335     bool *IsFast) const {
1336   if (IsFast)
1337     *IsFast = false;
1338 
1339   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1340   // which isn't a simple VT.
1341   // Until MVT is extended to handle this, simply check for the size and
1342   // rely on the condition below: allow accesses if the size is a multiple of 4.
1343   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1344                            VT.getStoreSize() > 16)) {
1345     return false;
1346   }
1347 
1348   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1349                                             Align, Flags, IsFast);
1350 }
1351 
1352 EVT SITargetLowering::getOptimalMemOpType(
1353     const MemOp &Op, const AttributeList &FuncAttributes) const {
1354   // FIXME: Should account for address space here.
1355 
1356   // The default fallback uses the private pointer size as a guess for a type to
1357   // use. Make sure we switch these to 64-bit accesses.
1358 
1359   if (Op.size() >= 16 &&
1360       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1361     return MVT::v4i32;
1362 
1363   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1364     return MVT::v2i32;
1365 
1366   // Use the default.
1367   return MVT::Other;
1368 }
1369 
1370 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1371                                            unsigned DestAS) const {
1372   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1373 }
1374 
1375 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1376   const MemSDNode *MemNode = cast<MemSDNode>(N);
1377   const Value *Ptr = MemNode->getMemOperand()->getValue();
1378   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1379   return I && I->getMetadata("amdgpu.noclobber");
1380 }
1381 
1382 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1383                                            unsigned DestAS) const {
1384   // Flat -> private/local is a simple truncate.
1385   // Flat -> global is no-op
1386   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1387     return true;
1388 
1389   return isNoopAddrSpaceCast(SrcAS, DestAS);
1390 }
1391 
1392 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1393   const MemSDNode *MemNode = cast<MemSDNode>(N);
1394 
1395   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1396 }
1397 
1398 TargetLoweringBase::LegalizeTypeAction
1399 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1400   int NumElts = VT.getVectorNumElements();
1401   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1402     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1403   return TargetLoweringBase::getPreferredVectorAction(VT);
1404 }
1405 
1406 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1407                                                          Type *Ty) const {
1408   // FIXME: Could be smarter if called for vector constants.
1409   return true;
1410 }
1411 
1412 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1413   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1414     switch (Op) {
1415     case ISD::LOAD:
1416     case ISD::STORE:
1417 
1418     // These operations are done with 32-bit instructions anyway.
1419     case ISD::AND:
1420     case ISD::OR:
1421     case ISD::XOR:
1422     case ISD::SELECT:
1423       // TODO: Extensions?
1424       return true;
1425     default:
1426       return false;
1427     }
1428   }
1429 
1430   // SimplifySetCC uses this function to determine whether or not it should
1431   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1432   if (VT == MVT::i1 && Op == ISD::SETCC)
1433     return false;
1434 
1435   return TargetLowering::isTypeDesirableForOp(Op, VT);
1436 }
1437 
1438 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1439                                                    const SDLoc &SL,
1440                                                    SDValue Chain,
1441                                                    uint64_t Offset) const {
1442   const DataLayout &DL = DAG.getDataLayout();
1443   MachineFunction &MF = DAG.getMachineFunction();
1444   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1445 
1446   const ArgDescriptor *InputPtrReg;
1447   const TargetRegisterClass *RC;
1448 
1449   std::tie(InputPtrReg, RC)
1450     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1451 
1452   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1453   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1454   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1455     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1456 
1457   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1458 }
1459 
1460 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1461                                             const SDLoc &SL) const {
1462   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1463                                                FIRST_IMPLICIT);
1464   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1465 }
1466 
1467 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1468                                          const SDLoc &SL, SDValue Val,
1469                                          bool Signed,
1470                                          const ISD::InputArg *Arg) const {
1471   // First, if it is a widened vector, narrow it.
1472   if (VT.isVector() &&
1473       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1474     EVT NarrowedVT =
1475         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1476                          VT.getVectorNumElements());
1477     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1478                       DAG.getConstant(0, SL, MVT::i32));
1479   }
1480 
1481   // Then convert the vector elements or scalar value.
1482   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1483       VT.bitsLT(MemVT)) {
1484     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1485     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1486   }
1487 
1488   if (MemVT.isFloatingPoint())
1489     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1490   else if (Signed)
1491     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1492   else
1493     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1494 
1495   return Val;
1496 }
1497 
1498 SDValue SITargetLowering::lowerKernargMemParameter(
1499   SelectionDAG &DAG, EVT VT, EVT MemVT,
1500   const SDLoc &SL, SDValue Chain,
1501   uint64_t Offset, unsigned Align, bool Signed,
1502   const ISD::InputArg *Arg) const {
1503   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1504 
1505   // Try to avoid using an extload by loading earlier than the argument address,
1506   // and extracting the relevant bits. The load should hopefully be merged with
1507   // the previous argument.
1508   if (MemVT.getStoreSize() < 4 && Align < 4) {
1509     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1510     int64_t AlignDownOffset = alignDown(Offset, 4);
1511     int64_t OffsetDiff = Offset - AlignDownOffset;
1512 
1513     EVT IntVT = MemVT.changeTypeToInteger();
1514 
1515     // TODO: If we passed in the base kernel offset we could have a better
1516     // alignment than 4, but we don't really need it.
1517     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1518     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1519                                MachineMemOperand::MODereferenceable |
1520                                MachineMemOperand::MOInvariant);
1521 
1522     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1523     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1524 
1525     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1526     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1527     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1528 
1529 
1530     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1531   }
1532 
1533   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1534   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1535                              MachineMemOperand::MODereferenceable |
1536                              MachineMemOperand::MOInvariant);
1537 
1538   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1539   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1540 }
1541 
1542 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1543                                               const SDLoc &SL, SDValue Chain,
1544                                               const ISD::InputArg &Arg) const {
1545   MachineFunction &MF = DAG.getMachineFunction();
1546   MachineFrameInfo &MFI = MF.getFrameInfo();
1547 
1548   if (Arg.Flags.isByVal()) {
1549     unsigned Size = Arg.Flags.getByValSize();
1550     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1551     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1552   }
1553 
1554   unsigned ArgOffset = VA.getLocMemOffset();
1555   unsigned ArgSize = VA.getValVT().getStoreSize();
1556 
1557   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1558 
1559   // Create load nodes to retrieve arguments from the stack.
1560   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1561   SDValue ArgValue;
1562 
1563   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1564   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1565   MVT MemVT = VA.getValVT();
1566 
1567   switch (VA.getLocInfo()) {
1568   default:
1569     break;
1570   case CCValAssign::BCvt:
1571     MemVT = VA.getLocVT();
1572     break;
1573   case CCValAssign::SExt:
1574     ExtType = ISD::SEXTLOAD;
1575     break;
1576   case CCValAssign::ZExt:
1577     ExtType = ISD::ZEXTLOAD;
1578     break;
1579   case CCValAssign::AExt:
1580     ExtType = ISD::EXTLOAD;
1581     break;
1582   }
1583 
1584   ArgValue = DAG.getExtLoad(
1585     ExtType, SL, VA.getLocVT(), Chain, FIN,
1586     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1587     MemVT);
1588   return ArgValue;
1589 }
1590 
1591 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1592   const SIMachineFunctionInfo &MFI,
1593   EVT VT,
1594   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1595   const ArgDescriptor *Reg;
1596   const TargetRegisterClass *RC;
1597 
1598   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1599   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1600 }
1601 
1602 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1603                                    CallingConv::ID CallConv,
1604                                    ArrayRef<ISD::InputArg> Ins,
1605                                    BitVector &Skipped,
1606                                    FunctionType *FType,
1607                                    SIMachineFunctionInfo *Info) {
1608   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1609     const ISD::InputArg *Arg = &Ins[I];
1610 
1611     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1612            "vector type argument should have been split");
1613 
1614     // First check if it's a PS input addr.
1615     if (CallConv == CallingConv::AMDGPU_PS &&
1616         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1617       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1618 
1619       // Inconveniently only the first part of the split is marked as isSplit,
1620       // so skip to the end. We only want to increment PSInputNum once for the
1621       // entire split argument.
1622       if (Arg->Flags.isSplit()) {
1623         while (!Arg->Flags.isSplitEnd()) {
1624           assert((!Arg->VT.isVector() ||
1625                   Arg->VT.getScalarSizeInBits() == 16) &&
1626                  "unexpected vector split in ps argument type");
1627           if (!SkipArg)
1628             Splits.push_back(*Arg);
1629           Arg = &Ins[++I];
1630         }
1631       }
1632 
1633       if (SkipArg) {
1634         // We can safely skip PS inputs.
1635         Skipped.set(Arg->getOrigArgIndex());
1636         ++PSInputNum;
1637         continue;
1638       }
1639 
1640       Info->markPSInputAllocated(PSInputNum);
1641       if (Arg->Used)
1642         Info->markPSInputEnabled(PSInputNum);
1643 
1644       ++PSInputNum;
1645     }
1646 
1647     Splits.push_back(*Arg);
1648   }
1649 }
1650 
1651 // Allocate special inputs passed in VGPRs.
1652 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1653                                                       MachineFunction &MF,
1654                                                       const SIRegisterInfo &TRI,
1655                                                       SIMachineFunctionInfo &Info) const {
1656   const LLT S32 = LLT::scalar(32);
1657   MachineRegisterInfo &MRI = MF.getRegInfo();
1658 
1659   if (Info.hasWorkItemIDX()) {
1660     Register Reg = AMDGPU::VGPR0;
1661     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1662 
1663     CCInfo.AllocateReg(Reg);
1664     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1665   }
1666 
1667   if (Info.hasWorkItemIDY()) {
1668     Register Reg = AMDGPU::VGPR1;
1669     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1670 
1671     CCInfo.AllocateReg(Reg);
1672     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1673   }
1674 
1675   if (Info.hasWorkItemIDZ()) {
1676     Register Reg = AMDGPU::VGPR2;
1677     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1678 
1679     CCInfo.AllocateReg(Reg);
1680     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1681   }
1682 }
1683 
1684 // Try to allocate a VGPR at the end of the argument list, or if no argument
1685 // VGPRs are left allocating a stack slot.
1686 // If \p Mask is is given it indicates bitfield position in the register.
1687 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1688 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1689                                          ArgDescriptor Arg = ArgDescriptor()) {
1690   if (Arg.isSet())
1691     return ArgDescriptor::createArg(Arg, Mask);
1692 
1693   ArrayRef<MCPhysReg> ArgVGPRs
1694     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1695   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1696   if (RegIdx == ArgVGPRs.size()) {
1697     // Spill to stack required.
1698     int64_t Offset = CCInfo.AllocateStack(4, 4);
1699 
1700     return ArgDescriptor::createStack(Offset, Mask);
1701   }
1702 
1703   unsigned Reg = ArgVGPRs[RegIdx];
1704   Reg = CCInfo.AllocateReg(Reg);
1705   assert(Reg != AMDGPU::NoRegister);
1706 
1707   MachineFunction &MF = CCInfo.getMachineFunction();
1708   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1709   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1710   return ArgDescriptor::createRegister(Reg, Mask);
1711 }
1712 
1713 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1714                                              const TargetRegisterClass *RC,
1715                                              unsigned NumArgRegs) {
1716   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1717   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1718   if (RegIdx == ArgSGPRs.size())
1719     report_fatal_error("ran out of SGPRs for arguments");
1720 
1721   unsigned Reg = ArgSGPRs[RegIdx];
1722   Reg = CCInfo.AllocateReg(Reg);
1723   assert(Reg != AMDGPU::NoRegister);
1724 
1725   MachineFunction &MF = CCInfo.getMachineFunction();
1726   MF.addLiveIn(Reg, RC);
1727   return ArgDescriptor::createRegister(Reg);
1728 }
1729 
1730 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1731   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1732 }
1733 
1734 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1735   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1736 }
1737 
1738 /// Allocate implicit function VGPR arguments at the end of allocated user
1739 /// arguments.
1740 void SITargetLowering::allocateSpecialInputVGPRs(
1741   CCState &CCInfo, MachineFunction &MF,
1742   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1743   const unsigned Mask = 0x3ff;
1744   ArgDescriptor Arg;
1745 
1746   if (Info.hasWorkItemIDX()) {
1747     Arg = allocateVGPR32Input(CCInfo, Mask);
1748     Info.setWorkItemIDX(Arg);
1749   }
1750 
1751   if (Info.hasWorkItemIDY()) {
1752     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1753     Info.setWorkItemIDY(Arg);
1754   }
1755 
1756   if (Info.hasWorkItemIDZ())
1757     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1758 }
1759 
1760 /// Allocate implicit function VGPR arguments in fixed registers.
1761 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1762   CCState &CCInfo, MachineFunction &MF,
1763   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1764   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1765   if (!Reg)
1766     report_fatal_error("failed to allocated VGPR for implicit arguments");
1767 
1768   const unsigned Mask = 0x3ff;
1769   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1770   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1771   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1772 }
1773 
1774 void SITargetLowering::allocateSpecialInputSGPRs(
1775   CCState &CCInfo,
1776   MachineFunction &MF,
1777   const SIRegisterInfo &TRI,
1778   SIMachineFunctionInfo &Info) const {
1779   auto &ArgInfo = Info.getArgInfo();
1780 
1781   // TODO: Unify handling with private memory pointers.
1782 
1783   if (Info.hasDispatchPtr())
1784     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1785 
1786   if (Info.hasQueuePtr())
1787     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1788 
1789   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1790   // constant offset from the kernarg segment.
1791   if (Info.hasImplicitArgPtr())
1792     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1793 
1794   if (Info.hasDispatchID())
1795     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1796 
1797   // flat_scratch_init is not applicable for non-kernel functions.
1798 
1799   if (Info.hasWorkGroupIDX())
1800     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1801 
1802   if (Info.hasWorkGroupIDY())
1803     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1804 
1805   if (Info.hasWorkGroupIDZ())
1806     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1807 }
1808 
1809 // Allocate special inputs passed in user SGPRs.
1810 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1811                                             MachineFunction &MF,
1812                                             const SIRegisterInfo &TRI,
1813                                             SIMachineFunctionInfo &Info) const {
1814   if (Info.hasImplicitBufferPtr()) {
1815     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1816     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1817     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1818   }
1819 
1820   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1821   if (Info.hasPrivateSegmentBuffer()) {
1822     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1823     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1824     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1825   }
1826 
1827   if (Info.hasDispatchPtr()) {
1828     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1829     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1830     CCInfo.AllocateReg(DispatchPtrReg);
1831   }
1832 
1833   if (Info.hasQueuePtr()) {
1834     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1835     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1836     CCInfo.AllocateReg(QueuePtrReg);
1837   }
1838 
1839   if (Info.hasKernargSegmentPtr()) {
1840     MachineRegisterInfo &MRI = MF.getRegInfo();
1841     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1842     CCInfo.AllocateReg(InputPtrReg);
1843 
1844     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1845     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1846   }
1847 
1848   if (Info.hasDispatchID()) {
1849     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1850     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1851     CCInfo.AllocateReg(DispatchIDReg);
1852   }
1853 
1854   if (Info.hasFlatScratchInit()) {
1855     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1856     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1857     CCInfo.AllocateReg(FlatScratchInitReg);
1858   }
1859 
1860   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1861   // these from the dispatch pointer.
1862 }
1863 
1864 // Allocate special input registers that are initialized per-wave.
1865 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1866                                            MachineFunction &MF,
1867                                            SIMachineFunctionInfo &Info,
1868                                            CallingConv::ID CallConv,
1869                                            bool IsShader) const {
1870   if (Info.hasWorkGroupIDX()) {
1871     unsigned Reg = Info.addWorkGroupIDX();
1872     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1873     CCInfo.AllocateReg(Reg);
1874   }
1875 
1876   if (Info.hasWorkGroupIDY()) {
1877     unsigned Reg = Info.addWorkGroupIDY();
1878     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1879     CCInfo.AllocateReg(Reg);
1880   }
1881 
1882   if (Info.hasWorkGroupIDZ()) {
1883     unsigned Reg = Info.addWorkGroupIDZ();
1884     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1885     CCInfo.AllocateReg(Reg);
1886   }
1887 
1888   if (Info.hasWorkGroupInfo()) {
1889     unsigned Reg = Info.addWorkGroupInfo();
1890     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1891     CCInfo.AllocateReg(Reg);
1892   }
1893 
1894   if (Info.hasPrivateSegmentWaveByteOffset()) {
1895     // Scratch wave offset passed in system SGPR.
1896     unsigned PrivateSegmentWaveByteOffsetReg;
1897 
1898     if (IsShader) {
1899       PrivateSegmentWaveByteOffsetReg =
1900         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1901 
1902       // This is true if the scratch wave byte offset doesn't have a fixed
1903       // location.
1904       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1905         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1906         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1907       }
1908     } else
1909       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1910 
1911     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1912     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1913   }
1914 }
1915 
1916 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1917                                      MachineFunction &MF,
1918                                      const SIRegisterInfo &TRI,
1919                                      SIMachineFunctionInfo &Info) {
1920   // Now that we've figured out where the scratch register inputs are, see if
1921   // should reserve the arguments and use them directly.
1922   MachineFrameInfo &MFI = MF.getFrameInfo();
1923   bool HasStackObjects = MFI.hasStackObjects();
1924   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1925 
1926   // Record that we know we have non-spill stack objects so we don't need to
1927   // check all stack objects later.
1928   if (HasStackObjects)
1929     Info.setHasNonSpillStackObjects(true);
1930 
1931   // Everything live out of a block is spilled with fast regalloc, so it's
1932   // almost certain that spilling will be required.
1933   if (TM.getOptLevel() == CodeGenOpt::None)
1934     HasStackObjects = true;
1935 
1936   // For now assume stack access is needed in any callee functions, so we need
1937   // the scratch registers to pass in.
1938   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1939 
1940   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1941     // If we have stack objects, we unquestionably need the private buffer
1942     // resource. For the Code Object V2 ABI, this will be the first 4 user
1943     // SGPR inputs. We can reserve those and use them directly.
1944 
1945     Register PrivateSegmentBufferReg =
1946         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1947     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1948   } else {
1949     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1950     // We tentatively reserve the last registers (skipping the last registers
1951     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1952     // we'll replace these with the ones immediately after those which were
1953     // really allocated. In the prologue copies will be inserted from the
1954     // argument to these reserved registers.
1955 
1956     // Without HSA, relocations are used for the scratch pointer and the
1957     // buffer resource setup is always inserted in the prologue. Scratch wave
1958     // offset is still in an input SGPR.
1959     Info.setScratchRSrcReg(ReservedBufferReg);
1960   }
1961 
1962   MachineRegisterInfo &MRI = MF.getRegInfo();
1963 
1964   // For entry functions we have to set up the stack pointer if we use it,
1965   // whereas non-entry functions get this "for free". This means there is no
1966   // intrinsic advantage to using S32 over S34 in cases where we do not have
1967   // calls but do need a frame pointer (i.e. if we are requested to have one
1968   // because frame pointer elimination is disabled). To keep things simple we
1969   // only ever use S32 as the call ABI stack pointer, and so using it does not
1970   // imply we need a separate frame pointer.
1971   //
1972   // Try to use s32 as the SP, but move it if it would interfere with input
1973   // arguments. This won't work with calls though.
1974   //
1975   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1976   // registers.
1977   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1978     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1979   } else {
1980     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1981 
1982     if (MFI.hasCalls())
1983       report_fatal_error("call in graphics shader with too many input SGPRs");
1984 
1985     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1986       if (!MRI.isLiveIn(Reg)) {
1987         Info.setStackPtrOffsetReg(Reg);
1988         break;
1989       }
1990     }
1991 
1992     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1993       report_fatal_error("failed to find register for SP");
1994   }
1995 
1996   // hasFP should be accurate for entry functions even before the frame is
1997   // finalized, because it does not rely on the known stack size, only
1998   // properties like whether variable sized objects are present.
1999   if (ST.getFrameLowering()->hasFP(MF)) {
2000     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2001   }
2002 }
2003 
2004 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2005   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2006   return !Info->isEntryFunction();
2007 }
2008 
2009 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2010 
2011 }
2012 
2013 void SITargetLowering::insertCopiesSplitCSR(
2014   MachineBasicBlock *Entry,
2015   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2016   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2017 
2018   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2019   if (!IStart)
2020     return;
2021 
2022   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2023   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2024   MachineBasicBlock::iterator MBBI = Entry->begin();
2025   for (const MCPhysReg *I = IStart; *I; ++I) {
2026     const TargetRegisterClass *RC = nullptr;
2027     if (AMDGPU::SReg_64RegClass.contains(*I))
2028       RC = &AMDGPU::SGPR_64RegClass;
2029     else if (AMDGPU::SReg_32RegClass.contains(*I))
2030       RC = &AMDGPU::SGPR_32RegClass;
2031     else
2032       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2033 
2034     Register NewVR = MRI->createVirtualRegister(RC);
2035     // Create copy from CSR to a virtual register.
2036     Entry->addLiveIn(*I);
2037     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2038       .addReg(*I);
2039 
2040     // Insert the copy-back instructions right before the terminator.
2041     for (auto *Exit : Exits)
2042       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2043               TII->get(TargetOpcode::COPY), *I)
2044         .addReg(NewVR);
2045   }
2046 }
2047 
2048 SDValue SITargetLowering::LowerFormalArguments(
2049     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2050     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2051     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2052   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2053 
2054   MachineFunction &MF = DAG.getMachineFunction();
2055   const Function &Fn = MF.getFunction();
2056   FunctionType *FType = MF.getFunction().getFunctionType();
2057   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2058 
2059   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2060     DiagnosticInfoUnsupported NoGraphicsHSA(
2061         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2062     DAG.getContext()->diagnose(NoGraphicsHSA);
2063     return DAG.getEntryNode();
2064   }
2065 
2066   SmallVector<ISD::InputArg, 16> Splits;
2067   SmallVector<CCValAssign, 16> ArgLocs;
2068   BitVector Skipped(Ins.size());
2069   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2070                  *DAG.getContext());
2071 
2072   bool IsShader = AMDGPU::isShader(CallConv);
2073   bool IsKernel = AMDGPU::isKernel(CallConv);
2074   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2075 
2076   if (IsShader) {
2077     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2078 
2079     // At least one interpolation mode must be enabled or else the GPU will
2080     // hang.
2081     //
2082     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2083     // set PSInputAddr, the user wants to enable some bits after the compilation
2084     // based on run-time states. Since we can't know what the final PSInputEna
2085     // will look like, so we shouldn't do anything here and the user should take
2086     // responsibility for the correct programming.
2087     //
2088     // Otherwise, the following restrictions apply:
2089     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2090     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2091     //   enabled too.
2092     if (CallConv == CallingConv::AMDGPU_PS) {
2093       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2094            ((Info->getPSInputAddr() & 0xF) == 0 &&
2095             Info->isPSInputAllocated(11))) {
2096         CCInfo.AllocateReg(AMDGPU::VGPR0);
2097         CCInfo.AllocateReg(AMDGPU::VGPR1);
2098         Info->markPSInputAllocated(0);
2099         Info->markPSInputEnabled(0);
2100       }
2101       if (Subtarget->isAmdPalOS()) {
2102         // For isAmdPalOS, the user does not enable some bits after compilation
2103         // based on run-time states; the register values being generated here are
2104         // the final ones set in hardware. Therefore we need to apply the
2105         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2106         // a bit is set in PSInputAddr but not PSInputEnable is where the
2107         // frontend set up an input arg for a particular interpolation mode, but
2108         // nothing uses that input arg. Really we should have an earlier pass
2109         // that removes such an arg.)
2110         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2111         if ((PsInputBits & 0x7F) == 0 ||
2112             ((PsInputBits & 0xF) == 0 &&
2113              (PsInputBits >> 11 & 1)))
2114           Info->markPSInputEnabled(
2115               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2116       }
2117     }
2118 
2119     assert(!Info->hasDispatchPtr() &&
2120            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2121            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2122            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2123            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2124            !Info->hasWorkItemIDZ());
2125   } else if (IsKernel) {
2126     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2127   } else {
2128     Splits.append(Ins.begin(), Ins.end());
2129   }
2130 
2131   if (IsEntryFunc) {
2132     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2133     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2134   } else {
2135     // For the fixed ABI, pass workitem IDs in the last argument register.
2136     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2137       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2138   }
2139 
2140   if (IsKernel) {
2141     analyzeFormalArgumentsCompute(CCInfo, Ins);
2142   } else {
2143     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2144     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2145   }
2146 
2147   SmallVector<SDValue, 16> Chains;
2148 
2149   // FIXME: This is the minimum kernel argument alignment. We should improve
2150   // this to the maximum alignment of the arguments.
2151   //
2152   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2153   // kern arg offset.
2154   const unsigned KernelArgBaseAlign = 16;
2155 
2156    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2157     const ISD::InputArg &Arg = Ins[i];
2158     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2159       InVals.push_back(DAG.getUNDEF(Arg.VT));
2160       continue;
2161     }
2162 
2163     CCValAssign &VA = ArgLocs[ArgIdx++];
2164     MVT VT = VA.getLocVT();
2165 
2166     if (IsEntryFunc && VA.isMemLoc()) {
2167       VT = Ins[i].VT;
2168       EVT MemVT = VA.getLocVT();
2169 
2170       const uint64_t Offset = VA.getLocMemOffset();
2171       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2172 
2173       SDValue Arg = lowerKernargMemParameter(
2174         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2175       Chains.push_back(Arg.getValue(1));
2176 
2177       auto *ParamTy =
2178         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2179       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2180           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2181                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2182         // On SI local pointers are just offsets into LDS, so they are always
2183         // less than 16-bits.  On CI and newer they could potentially be
2184         // real pointers, so we can't guarantee their size.
2185         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2186                           DAG.getValueType(MVT::i16));
2187       }
2188 
2189       InVals.push_back(Arg);
2190       continue;
2191     } else if (!IsEntryFunc && VA.isMemLoc()) {
2192       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2193       InVals.push_back(Val);
2194       if (!Arg.Flags.isByVal())
2195         Chains.push_back(Val.getValue(1));
2196       continue;
2197     }
2198 
2199     assert(VA.isRegLoc() && "Parameter must be in a register!");
2200 
2201     Register Reg = VA.getLocReg();
2202     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2203     EVT ValVT = VA.getValVT();
2204 
2205     Reg = MF.addLiveIn(Reg, RC);
2206     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2207 
2208     if (Arg.Flags.isSRet()) {
2209       // The return object should be reasonably addressable.
2210 
2211       // FIXME: This helps when the return is a real sret. If it is a
2212       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2213       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2214       unsigned NumBits
2215         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2216       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2217         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2218     }
2219 
2220     // If this is an 8 or 16-bit value, it is really passed promoted
2221     // to 32 bits. Insert an assert[sz]ext to capture this, then
2222     // truncate to the right size.
2223     switch (VA.getLocInfo()) {
2224     case CCValAssign::Full:
2225       break;
2226     case CCValAssign::BCvt:
2227       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2228       break;
2229     case CCValAssign::SExt:
2230       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2231                         DAG.getValueType(ValVT));
2232       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2233       break;
2234     case CCValAssign::ZExt:
2235       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2236                         DAG.getValueType(ValVT));
2237       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2238       break;
2239     case CCValAssign::AExt:
2240       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2241       break;
2242     default:
2243       llvm_unreachable("Unknown loc info!");
2244     }
2245 
2246     InVals.push_back(Val);
2247   }
2248 
2249   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2250     // Special inputs come after user arguments.
2251     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2252   }
2253 
2254   // Start adding system SGPRs.
2255   if (IsEntryFunc) {
2256     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2257   } else {
2258     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2259     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2260   }
2261 
2262   auto &ArgUsageInfo =
2263     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2264   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2265 
2266   unsigned StackArgSize = CCInfo.getNextStackOffset();
2267   Info->setBytesInStackArgArea(StackArgSize);
2268 
2269   return Chains.empty() ? Chain :
2270     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2271 }
2272 
2273 // TODO: If return values can't fit in registers, we should return as many as
2274 // possible in registers before passing on stack.
2275 bool SITargetLowering::CanLowerReturn(
2276   CallingConv::ID CallConv,
2277   MachineFunction &MF, bool IsVarArg,
2278   const SmallVectorImpl<ISD::OutputArg> &Outs,
2279   LLVMContext &Context) const {
2280   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2281   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2282   // for shaders. Vector types should be explicitly handled by CC.
2283   if (AMDGPU::isEntryFunctionCC(CallConv))
2284     return true;
2285 
2286   SmallVector<CCValAssign, 16> RVLocs;
2287   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2288   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2289 }
2290 
2291 SDValue
2292 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2293                               bool isVarArg,
2294                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2295                               const SmallVectorImpl<SDValue> &OutVals,
2296                               const SDLoc &DL, SelectionDAG &DAG) const {
2297   MachineFunction &MF = DAG.getMachineFunction();
2298   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2299 
2300   if (AMDGPU::isKernel(CallConv)) {
2301     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2302                                              OutVals, DL, DAG);
2303   }
2304 
2305   bool IsShader = AMDGPU::isShader(CallConv);
2306 
2307   Info->setIfReturnsVoid(Outs.empty());
2308   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2309 
2310   // CCValAssign - represent the assignment of the return value to a location.
2311   SmallVector<CCValAssign, 48> RVLocs;
2312   SmallVector<ISD::OutputArg, 48> Splits;
2313 
2314   // CCState - Info about the registers and stack slots.
2315   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2316                  *DAG.getContext());
2317 
2318   // Analyze outgoing return values.
2319   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2320 
2321   SDValue Flag;
2322   SmallVector<SDValue, 48> RetOps;
2323   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2324 
2325   // Add return address for callable functions.
2326   if (!Info->isEntryFunction()) {
2327     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2328     SDValue ReturnAddrReg = CreateLiveInRegister(
2329       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2330 
2331     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2332         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2333         MVT::i64);
2334     Chain =
2335         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2336     Flag = Chain.getValue(1);
2337     RetOps.push_back(ReturnAddrVirtualReg);
2338   }
2339 
2340   // Copy the result values into the output registers.
2341   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2342        ++I, ++RealRVLocIdx) {
2343     CCValAssign &VA = RVLocs[I];
2344     assert(VA.isRegLoc() && "Can only return in registers!");
2345     // TODO: Partially return in registers if return values don't fit.
2346     SDValue Arg = OutVals[RealRVLocIdx];
2347 
2348     // Copied from other backends.
2349     switch (VA.getLocInfo()) {
2350     case CCValAssign::Full:
2351       break;
2352     case CCValAssign::BCvt:
2353       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2354       break;
2355     case CCValAssign::SExt:
2356       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2357       break;
2358     case CCValAssign::ZExt:
2359       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2360       break;
2361     case CCValAssign::AExt:
2362       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2363       break;
2364     default:
2365       llvm_unreachable("Unknown loc info!");
2366     }
2367 
2368     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2369     Flag = Chain.getValue(1);
2370     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2371   }
2372 
2373   // FIXME: Does sret work properly?
2374   if (!Info->isEntryFunction()) {
2375     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2376     const MCPhysReg *I =
2377       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2378     if (I) {
2379       for (; *I; ++I) {
2380         if (AMDGPU::SReg_64RegClass.contains(*I))
2381           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2382         else if (AMDGPU::SReg_32RegClass.contains(*I))
2383           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2384         else
2385           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2386       }
2387     }
2388   }
2389 
2390   // Update chain and glue.
2391   RetOps[0] = Chain;
2392   if (Flag.getNode())
2393     RetOps.push_back(Flag);
2394 
2395   unsigned Opc = AMDGPUISD::ENDPGM;
2396   if (!IsWaveEnd)
2397     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2398   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2399 }
2400 
2401 SDValue SITargetLowering::LowerCallResult(
2402     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2403     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2404     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2405     SDValue ThisVal) const {
2406   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2407 
2408   // Assign locations to each value returned by this call.
2409   SmallVector<CCValAssign, 16> RVLocs;
2410   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2411                  *DAG.getContext());
2412   CCInfo.AnalyzeCallResult(Ins, RetCC);
2413 
2414   // Copy all of the result registers out of their specified physreg.
2415   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2416     CCValAssign VA = RVLocs[i];
2417     SDValue Val;
2418 
2419     if (VA.isRegLoc()) {
2420       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2421       Chain = Val.getValue(1);
2422       InFlag = Val.getValue(2);
2423     } else if (VA.isMemLoc()) {
2424       report_fatal_error("TODO: return values in memory");
2425     } else
2426       llvm_unreachable("unknown argument location type");
2427 
2428     switch (VA.getLocInfo()) {
2429     case CCValAssign::Full:
2430       break;
2431     case CCValAssign::BCvt:
2432       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2433       break;
2434     case CCValAssign::ZExt:
2435       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2436                         DAG.getValueType(VA.getValVT()));
2437       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2438       break;
2439     case CCValAssign::SExt:
2440       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2441                         DAG.getValueType(VA.getValVT()));
2442       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2443       break;
2444     case CCValAssign::AExt:
2445       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2446       break;
2447     default:
2448       llvm_unreachable("Unknown loc info!");
2449     }
2450 
2451     InVals.push_back(Val);
2452   }
2453 
2454   return Chain;
2455 }
2456 
2457 // Add code to pass special inputs required depending on used features separate
2458 // from the explicit user arguments present in the IR.
2459 void SITargetLowering::passSpecialInputs(
2460     CallLoweringInfo &CLI,
2461     CCState &CCInfo,
2462     const SIMachineFunctionInfo &Info,
2463     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2464     SmallVectorImpl<SDValue> &MemOpChains,
2465     SDValue Chain) const {
2466   // If we don't have a call site, this was a call inserted by
2467   // legalization. These can never use special inputs.
2468   if (!CLI.CB)
2469     return;
2470 
2471   SelectionDAG &DAG = CLI.DAG;
2472   const SDLoc &DL = CLI.DL;
2473 
2474   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2475   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2476 
2477   const AMDGPUFunctionArgInfo *CalleeArgInfo
2478     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2479   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2480     auto &ArgUsageInfo =
2481       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2482     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2483   }
2484 
2485   // TODO: Unify with private memory register handling. This is complicated by
2486   // the fact that at least in kernels, the input argument is not necessarily
2487   // in the same location as the input.
2488   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2489     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2490     AMDGPUFunctionArgInfo::QUEUE_PTR,
2491     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2492     AMDGPUFunctionArgInfo::DISPATCH_ID,
2493     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2494     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2495     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2496   };
2497 
2498   for (auto InputID : InputRegs) {
2499     const ArgDescriptor *OutgoingArg;
2500     const TargetRegisterClass *ArgRC;
2501 
2502     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID);
2503     if (!OutgoingArg)
2504       continue;
2505 
2506     const ArgDescriptor *IncomingArg;
2507     const TargetRegisterClass *IncomingArgRC;
2508     std::tie(IncomingArg, IncomingArgRC)
2509       = CallerArgInfo.getPreloadedValue(InputID);
2510     assert(IncomingArgRC == ArgRC);
2511 
2512     // All special arguments are ints for now.
2513     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2514     SDValue InputReg;
2515 
2516     if (IncomingArg) {
2517       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2518     } else {
2519       // The implicit arg ptr is special because it doesn't have a corresponding
2520       // input for kernels, and is computed from the kernarg segment pointer.
2521       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2522       InputReg = getImplicitArgPtr(DAG, DL);
2523     }
2524 
2525     if (OutgoingArg->isRegister()) {
2526       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2527       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2528         report_fatal_error("failed to allocate implicit input argument");
2529     } else {
2530       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2531       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2532                                               SpecialArgOffset);
2533       MemOpChains.push_back(ArgStore);
2534     }
2535   }
2536 
2537   // Pack workitem IDs into a single register or pass it as is if already
2538   // packed.
2539   const ArgDescriptor *OutgoingArg;
2540   const TargetRegisterClass *ArgRC;
2541 
2542   std::tie(OutgoingArg, ArgRC) =
2543     CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2544   if (!OutgoingArg)
2545     std::tie(OutgoingArg, ArgRC) =
2546       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2547   if (!OutgoingArg)
2548     std::tie(OutgoingArg, ArgRC) =
2549       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2550   if (!OutgoingArg)
2551     return;
2552 
2553   const ArgDescriptor *IncomingArgX
2554     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2555   const ArgDescriptor *IncomingArgY
2556     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2557   const ArgDescriptor *IncomingArgZ
2558     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2559 
2560   SDValue InputReg;
2561   SDLoc SL;
2562 
2563   // If incoming ids are not packed we need to pack them.
2564   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2565     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2566 
2567   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2568     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2569     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2570                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2571     InputReg = InputReg.getNode() ?
2572                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2573   }
2574 
2575   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2576     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2577     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2578                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2579     InputReg = InputReg.getNode() ?
2580                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2581   }
2582 
2583   if (!InputReg.getNode()) {
2584     // Workitem ids are already packed, any of present incoming arguments
2585     // will carry all required fields.
2586     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2587       IncomingArgX ? *IncomingArgX :
2588       IncomingArgY ? *IncomingArgY :
2589                      *IncomingArgZ, ~0u);
2590     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2591   }
2592 
2593   if (OutgoingArg->isRegister()) {
2594     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2595     CCInfo.AllocateReg(OutgoingArg->getRegister());
2596   } else {
2597     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2598     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2599                                             SpecialArgOffset);
2600     MemOpChains.push_back(ArgStore);
2601   }
2602 }
2603 
2604 static bool canGuaranteeTCO(CallingConv::ID CC) {
2605   return CC == CallingConv::Fast;
2606 }
2607 
2608 /// Return true if we might ever do TCO for calls with this calling convention.
2609 static bool mayTailCallThisCC(CallingConv::ID CC) {
2610   switch (CC) {
2611   case CallingConv::C:
2612     return true;
2613   default:
2614     return canGuaranteeTCO(CC);
2615   }
2616 }
2617 
2618 bool SITargetLowering::isEligibleForTailCallOptimization(
2619     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2620     const SmallVectorImpl<ISD::OutputArg> &Outs,
2621     const SmallVectorImpl<SDValue> &OutVals,
2622     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2623   if (!mayTailCallThisCC(CalleeCC))
2624     return false;
2625 
2626   MachineFunction &MF = DAG.getMachineFunction();
2627   const Function &CallerF = MF.getFunction();
2628   CallingConv::ID CallerCC = CallerF.getCallingConv();
2629   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2630   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2631 
2632   // Kernels aren't callable, and don't have a live in return address so it
2633   // doesn't make sense to do a tail call with entry functions.
2634   if (!CallerPreserved)
2635     return false;
2636 
2637   bool CCMatch = CallerCC == CalleeCC;
2638 
2639   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2640     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2641       return true;
2642     return false;
2643   }
2644 
2645   // TODO: Can we handle var args?
2646   if (IsVarArg)
2647     return false;
2648 
2649   for (const Argument &Arg : CallerF.args()) {
2650     if (Arg.hasByValAttr())
2651       return false;
2652   }
2653 
2654   LLVMContext &Ctx = *DAG.getContext();
2655 
2656   // Check that the call results are passed in the same way.
2657   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2658                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2659                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2660     return false;
2661 
2662   // The callee has to preserve all registers the caller needs to preserve.
2663   if (!CCMatch) {
2664     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2665     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2666       return false;
2667   }
2668 
2669   // Nothing more to check if the callee is taking no arguments.
2670   if (Outs.empty())
2671     return true;
2672 
2673   SmallVector<CCValAssign, 16> ArgLocs;
2674   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2675 
2676   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2677 
2678   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2679   // If the stack arguments for this call do not fit into our own save area then
2680   // the call cannot be made tail.
2681   // TODO: Is this really necessary?
2682   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2683     return false;
2684 
2685   const MachineRegisterInfo &MRI = MF.getRegInfo();
2686   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2687 }
2688 
2689 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2690   if (!CI->isTailCall())
2691     return false;
2692 
2693   const Function *ParentFn = CI->getParent()->getParent();
2694   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2695     return false;
2696   return true;
2697 }
2698 
2699 // The wave scratch offset register is used as the global base pointer.
2700 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2701                                     SmallVectorImpl<SDValue> &InVals) const {
2702   SelectionDAG &DAG = CLI.DAG;
2703   const SDLoc &DL = CLI.DL;
2704   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2705   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2706   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2707   SDValue Chain = CLI.Chain;
2708   SDValue Callee = CLI.Callee;
2709   bool &IsTailCall = CLI.IsTailCall;
2710   CallingConv::ID CallConv = CLI.CallConv;
2711   bool IsVarArg = CLI.IsVarArg;
2712   bool IsSibCall = false;
2713   bool IsThisReturn = false;
2714   MachineFunction &MF = DAG.getMachineFunction();
2715 
2716   if (Callee.isUndef() || isNullConstant(Callee)) {
2717     if (!CLI.IsTailCall) {
2718       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2719         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2720     }
2721 
2722     return Chain;
2723   }
2724 
2725   if (IsVarArg) {
2726     return lowerUnhandledCall(CLI, InVals,
2727                               "unsupported call to variadic function ");
2728   }
2729 
2730   if (!CLI.CB)
2731     report_fatal_error("unsupported libcall legalization");
2732 
2733   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2734       !CLI.CB->getCalledFunction()) {
2735     return lowerUnhandledCall(CLI, InVals,
2736                               "unsupported indirect call to function ");
2737   }
2738 
2739   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2740     return lowerUnhandledCall(CLI, InVals,
2741                               "unsupported required tail call to function ");
2742   }
2743 
2744   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2745     // Note the issue is with the CC of the calling function, not of the call
2746     // itself.
2747     return lowerUnhandledCall(CLI, InVals,
2748                           "unsupported call from graphics shader of function ");
2749   }
2750 
2751   if (IsTailCall) {
2752     IsTailCall = isEligibleForTailCallOptimization(
2753       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2754     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2755       report_fatal_error("failed to perform tail call elimination on a call "
2756                          "site marked musttail");
2757     }
2758 
2759     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2760 
2761     // A sibling call is one where we're under the usual C ABI and not planning
2762     // to change that but can still do a tail call:
2763     if (!TailCallOpt && IsTailCall)
2764       IsSibCall = true;
2765 
2766     if (IsTailCall)
2767       ++NumTailCalls;
2768   }
2769 
2770   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2771   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2772   SmallVector<SDValue, 8> MemOpChains;
2773 
2774   // Analyze operands of the call, assigning locations to each operand.
2775   SmallVector<CCValAssign, 16> ArgLocs;
2776   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2777   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2778 
2779   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2780     // With a fixed ABI, allocate fixed registers before user arguments.
2781     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2782   }
2783 
2784   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2785 
2786   // Get a count of how many bytes are to be pushed on the stack.
2787   unsigned NumBytes = CCInfo.getNextStackOffset();
2788 
2789   if (IsSibCall) {
2790     // Since we're not changing the ABI to make this a tail call, the memory
2791     // operands are already available in the caller's incoming argument space.
2792     NumBytes = 0;
2793   }
2794 
2795   // FPDiff is the byte offset of the call's argument area from the callee's.
2796   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2797   // by this amount for a tail call. In a sibling call it must be 0 because the
2798   // caller will deallocate the entire stack and the callee still expects its
2799   // arguments to begin at SP+0. Completely unused for non-tail calls.
2800   int32_t FPDiff = 0;
2801   MachineFrameInfo &MFI = MF.getFrameInfo();
2802 
2803   // Adjust the stack pointer for the new arguments...
2804   // These operations are automatically eliminated by the prolog/epilog pass
2805   if (!IsSibCall) {
2806     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2807 
2808     SmallVector<SDValue, 4> CopyFromChains;
2809 
2810     // In the HSA case, this should be an identity copy.
2811     SDValue ScratchRSrcReg
2812       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2813     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2814     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2815     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2816   }
2817 
2818   MVT PtrVT = MVT::i32;
2819 
2820   // Walk the register/memloc assignments, inserting copies/loads.
2821   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2822     CCValAssign &VA = ArgLocs[i];
2823     SDValue Arg = OutVals[i];
2824 
2825     // Promote the value if needed.
2826     switch (VA.getLocInfo()) {
2827     case CCValAssign::Full:
2828       break;
2829     case CCValAssign::BCvt:
2830       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2831       break;
2832     case CCValAssign::ZExt:
2833       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2834       break;
2835     case CCValAssign::SExt:
2836       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2837       break;
2838     case CCValAssign::AExt:
2839       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2840       break;
2841     case CCValAssign::FPExt:
2842       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2843       break;
2844     default:
2845       llvm_unreachable("Unknown loc info!");
2846     }
2847 
2848     if (VA.isRegLoc()) {
2849       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2850     } else {
2851       assert(VA.isMemLoc());
2852 
2853       SDValue DstAddr;
2854       MachinePointerInfo DstInfo;
2855 
2856       unsigned LocMemOffset = VA.getLocMemOffset();
2857       int32_t Offset = LocMemOffset;
2858 
2859       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2860       MaybeAlign Alignment;
2861 
2862       if (IsTailCall) {
2863         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2864         unsigned OpSize = Flags.isByVal() ?
2865           Flags.getByValSize() : VA.getValVT().getStoreSize();
2866 
2867         // FIXME: We can have better than the minimum byval required alignment.
2868         Alignment =
2869             Flags.isByVal()
2870                 ? Flags.getNonZeroByValAlign()
2871                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2872 
2873         Offset = Offset + FPDiff;
2874         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2875 
2876         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2877         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2878 
2879         // Make sure any stack arguments overlapping with where we're storing
2880         // are loaded before this eventual operation. Otherwise they'll be
2881         // clobbered.
2882 
2883         // FIXME: Why is this really necessary? This seems to just result in a
2884         // lot of code to copy the stack and write them back to the same
2885         // locations, which are supposed to be immutable?
2886         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2887       } else {
2888         DstAddr = PtrOff;
2889         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2890         Alignment =
2891             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2892       }
2893 
2894       if (Outs[i].Flags.isByVal()) {
2895         SDValue SizeNode =
2896             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2897         SDValue Cpy =
2898             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2899                           Outs[i].Flags.getNonZeroByValAlign(),
2900                           /*isVol = */ false, /*AlwaysInline = */ true,
2901                           /*isTailCall = */ false, DstInfo,
2902                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2903 
2904         MemOpChains.push_back(Cpy);
2905       } else {
2906         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2907                                      Alignment ? Alignment->value() : 0);
2908         MemOpChains.push_back(Store);
2909       }
2910     }
2911   }
2912 
2913   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
2914     // Copy special input registers after user input arguments.
2915     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2916   }
2917 
2918   if (!MemOpChains.empty())
2919     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2920 
2921   // Build a sequence of copy-to-reg nodes chained together with token chain
2922   // and flag operands which copy the outgoing args into the appropriate regs.
2923   SDValue InFlag;
2924   for (auto &RegToPass : RegsToPass) {
2925     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2926                              RegToPass.second, InFlag);
2927     InFlag = Chain.getValue(1);
2928   }
2929 
2930 
2931   SDValue PhysReturnAddrReg;
2932   if (IsTailCall) {
2933     // Since the return is being combined with the call, we need to pass on the
2934     // return address.
2935 
2936     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2937     SDValue ReturnAddrReg = CreateLiveInRegister(
2938       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2939 
2940     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2941                                         MVT::i64);
2942     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2943     InFlag = Chain.getValue(1);
2944   }
2945 
2946   // We don't usually want to end the call-sequence here because we would tidy
2947   // the frame up *after* the call, however in the ABI-changing tail-call case
2948   // we've carefully laid out the parameters so that when sp is reset they'll be
2949   // in the correct location.
2950   if (IsTailCall && !IsSibCall) {
2951     Chain = DAG.getCALLSEQ_END(Chain,
2952                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2953                                DAG.getTargetConstant(0, DL, MVT::i32),
2954                                InFlag, DL);
2955     InFlag = Chain.getValue(1);
2956   }
2957 
2958   std::vector<SDValue> Ops;
2959   Ops.push_back(Chain);
2960   Ops.push_back(Callee);
2961   // Add a redundant copy of the callee global which will not be legalized, as
2962   // we need direct access to the callee later.
2963   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
2964     const GlobalValue *GV = GSD->getGlobal();
2965     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2966   } else {
2967     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
2968   }
2969 
2970   if (IsTailCall) {
2971     // Each tail call may have to adjust the stack by a different amount, so
2972     // this information must travel along with the operation for eventual
2973     // consumption by emitEpilogue.
2974     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2975 
2976     Ops.push_back(PhysReturnAddrReg);
2977   }
2978 
2979   // Add argument registers to the end of the list so that they are known live
2980   // into the call.
2981   for (auto &RegToPass : RegsToPass) {
2982     Ops.push_back(DAG.getRegister(RegToPass.first,
2983                                   RegToPass.second.getValueType()));
2984   }
2985 
2986   // Add a register mask operand representing the call-preserved registers.
2987 
2988   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2989   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2990   assert(Mask && "Missing call preserved mask for calling convention");
2991   Ops.push_back(DAG.getRegisterMask(Mask));
2992 
2993   if (InFlag.getNode())
2994     Ops.push_back(InFlag);
2995 
2996   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2997 
2998   // If we're doing a tall call, use a TC_RETURN here rather than an
2999   // actual call instruction.
3000   if (IsTailCall) {
3001     MFI.setHasTailCall();
3002     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3003   }
3004 
3005   // Returns a chain and a flag for retval copy to use.
3006   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3007   Chain = Call.getValue(0);
3008   InFlag = Call.getValue(1);
3009 
3010   uint64_t CalleePopBytes = NumBytes;
3011   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3012                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3013                              InFlag, DL);
3014   if (!Ins.empty())
3015     InFlag = Chain.getValue(1);
3016 
3017   // Handle result values, copying them out of physregs into vregs that we
3018   // return.
3019   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3020                          InVals, IsThisReturn,
3021                          IsThisReturn ? OutVals[0] : SDValue());
3022 }
3023 
3024 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3025                                              const MachineFunction &MF) const {
3026   Register Reg = StringSwitch<Register>(RegName)
3027     .Case("m0", AMDGPU::M0)
3028     .Case("exec", AMDGPU::EXEC)
3029     .Case("exec_lo", AMDGPU::EXEC_LO)
3030     .Case("exec_hi", AMDGPU::EXEC_HI)
3031     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3032     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3033     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3034     .Default(Register());
3035 
3036   if (Reg == AMDGPU::NoRegister) {
3037     report_fatal_error(Twine("invalid register name \""
3038                              + StringRef(RegName)  + "\"."));
3039 
3040   }
3041 
3042   if (!Subtarget->hasFlatScrRegister() &&
3043        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3044     report_fatal_error(Twine("invalid register \""
3045                              + StringRef(RegName)  + "\" for subtarget."));
3046   }
3047 
3048   switch (Reg) {
3049   case AMDGPU::M0:
3050   case AMDGPU::EXEC_LO:
3051   case AMDGPU::EXEC_HI:
3052   case AMDGPU::FLAT_SCR_LO:
3053   case AMDGPU::FLAT_SCR_HI:
3054     if (VT.getSizeInBits() == 32)
3055       return Reg;
3056     break;
3057   case AMDGPU::EXEC:
3058   case AMDGPU::FLAT_SCR:
3059     if (VT.getSizeInBits() == 64)
3060       return Reg;
3061     break;
3062   default:
3063     llvm_unreachable("missing register type checking");
3064   }
3065 
3066   report_fatal_error(Twine("invalid type for register \""
3067                            + StringRef(RegName) + "\"."));
3068 }
3069 
3070 // If kill is not the last instruction, split the block so kill is always a
3071 // proper terminator.
3072 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3073                                                     MachineBasicBlock *BB) const {
3074   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3075 
3076   MachineBasicBlock::iterator SplitPoint(&MI);
3077   ++SplitPoint;
3078 
3079   if (SplitPoint == BB->end()) {
3080     // Don't bother with a new block.
3081     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3082     return BB;
3083   }
3084 
3085   MachineFunction *MF = BB->getParent();
3086   MachineBasicBlock *SplitBB
3087     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3088 
3089   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3090   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3091 
3092   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3093   BB->addSuccessor(SplitBB);
3094 
3095   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3096   return SplitBB;
3097 }
3098 
3099 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3100 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3101 // be the first instruction in the remainder block.
3102 //
3103 /// \returns { LoopBody, Remainder }
3104 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3105 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3106   MachineFunction *MF = MBB.getParent();
3107   MachineBasicBlock::iterator I(&MI);
3108 
3109   // To insert the loop we need to split the block. Move everything after this
3110   // point to a new block, and insert a new empty block between the two.
3111   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3112   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3113   MachineFunction::iterator MBBI(MBB);
3114   ++MBBI;
3115 
3116   MF->insert(MBBI, LoopBB);
3117   MF->insert(MBBI, RemainderBB);
3118 
3119   LoopBB->addSuccessor(LoopBB);
3120   LoopBB->addSuccessor(RemainderBB);
3121 
3122   // Move the rest of the block into a new block.
3123   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3124 
3125   if (InstInLoop) {
3126     auto Next = std::next(I);
3127 
3128     // Move instruction to loop body.
3129     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3130 
3131     // Move the rest of the block.
3132     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3133   } else {
3134     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3135   }
3136 
3137   MBB.addSuccessor(LoopBB);
3138 
3139   return std::make_pair(LoopBB, RemainderBB);
3140 }
3141 
3142 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3143 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3144   MachineBasicBlock *MBB = MI.getParent();
3145   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3146   auto I = MI.getIterator();
3147   auto E = std::next(I);
3148 
3149   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3150     .addImm(0);
3151 
3152   MIBundleBuilder Bundler(*MBB, I, E);
3153   finalizeBundle(*MBB, Bundler.begin());
3154 }
3155 
3156 MachineBasicBlock *
3157 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3158                                          MachineBasicBlock *BB) const {
3159   const DebugLoc &DL = MI.getDebugLoc();
3160 
3161   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3162 
3163   MachineBasicBlock *LoopBB;
3164   MachineBasicBlock *RemainderBB;
3165   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3166 
3167   // Apparently kill flags are only valid if the def is in the same block?
3168   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3169     Src->setIsKill(false);
3170 
3171   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3172 
3173   MachineBasicBlock::iterator I = LoopBB->end();
3174 
3175   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3176     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3177 
3178   // Clear TRAP_STS.MEM_VIOL
3179   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3180     .addImm(0)
3181     .addImm(EncodedReg);
3182 
3183   bundleInstWithWaitcnt(MI);
3184 
3185   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3186 
3187   // Load and check TRAP_STS.MEM_VIOL
3188   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3189     .addImm(EncodedReg);
3190 
3191   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3192   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3193     .addReg(Reg, RegState::Kill)
3194     .addImm(0);
3195   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3196     .addMBB(LoopBB);
3197 
3198   return RemainderBB;
3199 }
3200 
3201 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3202 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3203 // will only do one iteration. In the worst case, this will loop 64 times.
3204 //
3205 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3206 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3207   const SIInstrInfo *TII,
3208   MachineRegisterInfo &MRI,
3209   MachineBasicBlock &OrigBB,
3210   MachineBasicBlock &LoopBB,
3211   const DebugLoc &DL,
3212   const MachineOperand &IdxReg,
3213   unsigned InitReg,
3214   unsigned ResultReg,
3215   unsigned PhiReg,
3216   unsigned InitSaveExecReg,
3217   int Offset,
3218   bool UseGPRIdxMode,
3219   bool IsIndirectSrc) {
3220   MachineFunction *MF = OrigBB.getParent();
3221   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3222   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3223   MachineBasicBlock::iterator I = LoopBB.begin();
3224 
3225   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3226   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3227   Register NewExec = MRI.createVirtualRegister(BoolRC);
3228   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3229   Register CondReg = MRI.createVirtualRegister(BoolRC);
3230 
3231   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3232     .addReg(InitReg)
3233     .addMBB(&OrigBB)
3234     .addReg(ResultReg)
3235     .addMBB(&LoopBB);
3236 
3237   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3238     .addReg(InitSaveExecReg)
3239     .addMBB(&OrigBB)
3240     .addReg(NewExec)
3241     .addMBB(&LoopBB);
3242 
3243   // Read the next variant <- also loop target.
3244   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3245     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3246 
3247   // Compare the just read M0 value to all possible Idx values.
3248   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3249     .addReg(CurrentIdxReg)
3250     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3251 
3252   // Update EXEC, save the original EXEC value to VCC.
3253   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3254                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3255           NewExec)
3256     .addReg(CondReg, RegState::Kill);
3257 
3258   MRI.setSimpleHint(NewExec, CondReg);
3259 
3260   if (UseGPRIdxMode) {
3261     unsigned IdxReg;
3262     if (Offset == 0) {
3263       IdxReg = CurrentIdxReg;
3264     } else {
3265       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3266       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3267         .addReg(CurrentIdxReg, RegState::Kill)
3268         .addImm(Offset);
3269     }
3270     unsigned IdxMode = IsIndirectSrc ?
3271       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3272     MachineInstr *SetOn =
3273       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3274       .addReg(IdxReg, RegState::Kill)
3275       .addImm(IdxMode);
3276     SetOn->getOperand(3).setIsUndef();
3277   } else {
3278     // Move index from VCC into M0
3279     if (Offset == 0) {
3280       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3281         .addReg(CurrentIdxReg, RegState::Kill);
3282     } else {
3283       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3284         .addReg(CurrentIdxReg, RegState::Kill)
3285         .addImm(Offset);
3286     }
3287   }
3288 
3289   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3290   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3291   MachineInstr *InsertPt =
3292     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3293                                                   : AMDGPU::S_XOR_B64_term), Exec)
3294       .addReg(Exec)
3295       .addReg(NewExec);
3296 
3297   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3298   // s_cbranch_scc0?
3299 
3300   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3301   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3302     .addMBB(&LoopBB);
3303 
3304   return InsertPt->getIterator();
3305 }
3306 
3307 // This has slightly sub-optimal regalloc when the source vector is killed by
3308 // the read. The register allocator does not understand that the kill is
3309 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3310 // subregister from it, using 1 more VGPR than necessary. This was saved when
3311 // this was expanded after register allocation.
3312 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3313                                                   MachineBasicBlock &MBB,
3314                                                   MachineInstr &MI,
3315                                                   unsigned InitResultReg,
3316                                                   unsigned PhiReg,
3317                                                   int Offset,
3318                                                   bool UseGPRIdxMode,
3319                                                   bool IsIndirectSrc) {
3320   MachineFunction *MF = MBB.getParent();
3321   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3322   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3323   MachineRegisterInfo &MRI = MF->getRegInfo();
3324   const DebugLoc &DL = MI.getDebugLoc();
3325   MachineBasicBlock::iterator I(&MI);
3326 
3327   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3328   Register DstReg = MI.getOperand(0).getReg();
3329   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3330   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3331   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3332   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3333 
3334   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3335 
3336   // Save the EXEC mask
3337   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3338     .addReg(Exec);
3339 
3340   MachineBasicBlock *LoopBB;
3341   MachineBasicBlock *RemainderBB;
3342   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3343 
3344   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3345 
3346   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3347                                       InitResultReg, DstReg, PhiReg, TmpExec,
3348                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3349   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3350   MachineFunction::iterator MBBI(LoopBB);
3351   ++MBBI;
3352   MF->insert(MBBI, LandingPad);
3353   LoopBB->removeSuccessor(RemainderBB);
3354   LandingPad->addSuccessor(RemainderBB);
3355   LoopBB->addSuccessor(LandingPad);
3356   MachineBasicBlock::iterator First = LandingPad->begin();
3357   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3358     .addReg(SaveExec);
3359 
3360   return InsPt;
3361 }
3362 
3363 // Returns subreg index, offset
3364 static std::pair<unsigned, int>
3365 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3366                             const TargetRegisterClass *SuperRC,
3367                             unsigned VecReg,
3368                             int Offset) {
3369   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3370 
3371   // Skip out of bounds offsets, or else we would end up using an undefined
3372   // register.
3373   if (Offset >= NumElts || Offset < 0)
3374     return std::make_pair(AMDGPU::sub0, Offset);
3375 
3376   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3377 }
3378 
3379 // Return true if the index is an SGPR and was set.
3380 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3381                                  MachineRegisterInfo &MRI,
3382                                  MachineInstr &MI,
3383                                  int Offset,
3384                                  bool UseGPRIdxMode,
3385                                  bool IsIndirectSrc) {
3386   MachineBasicBlock *MBB = MI.getParent();
3387   const DebugLoc &DL = MI.getDebugLoc();
3388   MachineBasicBlock::iterator I(&MI);
3389 
3390   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3391   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3392 
3393   assert(Idx->getReg() != AMDGPU::NoRegister);
3394 
3395   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3396     return false;
3397 
3398   if (UseGPRIdxMode) {
3399     unsigned IdxMode = IsIndirectSrc ?
3400       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3401     if (Offset == 0) {
3402       MachineInstr *SetOn =
3403           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3404               .add(*Idx)
3405               .addImm(IdxMode);
3406 
3407       SetOn->getOperand(3).setIsUndef();
3408     } else {
3409       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3410       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3411           .add(*Idx)
3412           .addImm(Offset);
3413       MachineInstr *SetOn =
3414         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3415         .addReg(Tmp, RegState::Kill)
3416         .addImm(IdxMode);
3417 
3418       SetOn->getOperand(3).setIsUndef();
3419     }
3420 
3421     return true;
3422   }
3423 
3424   if (Offset == 0) {
3425     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3426       .add(*Idx);
3427   } else {
3428     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3429       .add(*Idx)
3430       .addImm(Offset);
3431   }
3432 
3433   return true;
3434 }
3435 
3436 // Control flow needs to be inserted if indexing with a VGPR.
3437 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3438                                           MachineBasicBlock &MBB,
3439                                           const GCNSubtarget &ST) {
3440   const SIInstrInfo *TII = ST.getInstrInfo();
3441   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3442   MachineFunction *MF = MBB.getParent();
3443   MachineRegisterInfo &MRI = MF->getRegInfo();
3444 
3445   Register Dst = MI.getOperand(0).getReg();
3446   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3447   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3448 
3449   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3450 
3451   unsigned SubReg;
3452   std::tie(SubReg, Offset)
3453     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3454 
3455   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3456 
3457   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3458     MachineBasicBlock::iterator I(&MI);
3459     const DebugLoc &DL = MI.getDebugLoc();
3460 
3461     if (UseGPRIdxMode) {
3462       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3463       // to avoid interfering with other uses, so probably requires a new
3464       // optimization pass.
3465       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3466         .addReg(SrcReg, RegState::Undef, SubReg)
3467         .addReg(SrcReg, RegState::Implicit)
3468         .addReg(AMDGPU::M0, RegState::Implicit);
3469       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3470     } else {
3471       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3472         .addReg(SrcReg, RegState::Undef, SubReg)
3473         .addReg(SrcReg, RegState::Implicit);
3474     }
3475 
3476     MI.eraseFromParent();
3477 
3478     return &MBB;
3479   }
3480 
3481   const DebugLoc &DL = MI.getDebugLoc();
3482   MachineBasicBlock::iterator I(&MI);
3483 
3484   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3485   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3486 
3487   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3488 
3489   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3490                               Offset, UseGPRIdxMode, true);
3491   MachineBasicBlock *LoopBB = InsPt->getParent();
3492 
3493   if (UseGPRIdxMode) {
3494     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3495       .addReg(SrcReg, RegState::Undef, SubReg)
3496       .addReg(SrcReg, RegState::Implicit)
3497       .addReg(AMDGPU::M0, RegState::Implicit);
3498     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3499   } else {
3500     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3501       .addReg(SrcReg, RegState::Undef, SubReg)
3502       .addReg(SrcReg, RegState::Implicit);
3503   }
3504 
3505   MI.eraseFromParent();
3506 
3507   return LoopBB;
3508 }
3509 
3510 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3511                                           MachineBasicBlock &MBB,
3512                                           const GCNSubtarget &ST) {
3513   const SIInstrInfo *TII = ST.getInstrInfo();
3514   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3515   MachineFunction *MF = MBB.getParent();
3516   MachineRegisterInfo &MRI = MF->getRegInfo();
3517 
3518   Register Dst = MI.getOperand(0).getReg();
3519   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3520   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3521   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3522   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3523   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3524 
3525   // This can be an immediate, but will be folded later.
3526   assert(Val->getReg());
3527 
3528   unsigned SubReg;
3529   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3530                                                          SrcVec->getReg(),
3531                                                          Offset);
3532   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3533 
3534   if (Idx->getReg() == AMDGPU::NoRegister) {
3535     MachineBasicBlock::iterator I(&MI);
3536     const DebugLoc &DL = MI.getDebugLoc();
3537 
3538     assert(Offset == 0);
3539 
3540     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3541         .add(*SrcVec)
3542         .add(*Val)
3543         .addImm(SubReg);
3544 
3545     MI.eraseFromParent();
3546     return &MBB;
3547   }
3548 
3549   const MCInstrDesc &MovRelDesc
3550     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3551 
3552   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3553     MachineBasicBlock::iterator I(&MI);
3554     const DebugLoc &DL = MI.getDebugLoc();
3555     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3556       .addReg(SrcVec->getReg())
3557       .add(*Val)
3558       .addImm(SubReg);
3559     if (UseGPRIdxMode)
3560       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3561 
3562     MI.eraseFromParent();
3563     return &MBB;
3564   }
3565 
3566   if (Val->isReg())
3567     MRI.clearKillFlags(Val->getReg());
3568 
3569   const DebugLoc &DL = MI.getDebugLoc();
3570 
3571   Register PhiReg = MRI.createVirtualRegister(VecRC);
3572 
3573   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3574                               Offset, UseGPRIdxMode, false);
3575   MachineBasicBlock *LoopBB = InsPt->getParent();
3576 
3577   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3578     .addReg(PhiReg)
3579     .add(*Val)
3580     .addImm(AMDGPU::sub0);
3581   if (UseGPRIdxMode)
3582     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3583 
3584   MI.eraseFromParent();
3585   return LoopBB;
3586 }
3587 
3588 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3589   MachineInstr &MI, MachineBasicBlock *BB) const {
3590 
3591   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3592   MachineFunction *MF = BB->getParent();
3593   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3594 
3595   if (TII->isMIMG(MI)) {
3596     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3597       report_fatal_error("missing mem operand from MIMG instruction");
3598     }
3599     // Add a memoperand for mimg instructions so that they aren't assumed to
3600     // be ordered memory instuctions.
3601 
3602     return BB;
3603   }
3604 
3605   switch (MI.getOpcode()) {
3606   case AMDGPU::S_UADDO_PSEUDO:
3607   case AMDGPU::S_USUBO_PSEUDO: {
3608     const DebugLoc &DL = MI.getDebugLoc();
3609     MachineOperand &Dest0 = MI.getOperand(0);
3610     MachineOperand &Dest1 = MI.getOperand(1);
3611     MachineOperand &Src0 = MI.getOperand(2);
3612     MachineOperand &Src1 = MI.getOperand(3);
3613 
3614     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3615                        ? AMDGPU::S_ADD_I32
3616                        : AMDGPU::S_SUB_I32;
3617     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3618 
3619     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3620         .addImm(1)
3621         .addImm(0);
3622 
3623     MI.eraseFromParent();
3624     return BB;
3625   }
3626   case AMDGPU::S_ADD_U64_PSEUDO:
3627   case AMDGPU::S_SUB_U64_PSEUDO: {
3628     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3629     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3630     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3631     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3632     const DebugLoc &DL = MI.getDebugLoc();
3633 
3634     MachineOperand &Dest = MI.getOperand(0);
3635     MachineOperand &Src0 = MI.getOperand(1);
3636     MachineOperand &Src1 = MI.getOperand(2);
3637 
3638     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3639     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3640 
3641     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3642         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3643     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3644         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3645 
3646     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3647         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3648     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3649         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3650 
3651     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3652 
3653     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3654     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3655     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3656     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3657     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3658         .addReg(DestSub0)
3659         .addImm(AMDGPU::sub0)
3660         .addReg(DestSub1)
3661         .addImm(AMDGPU::sub1);
3662     MI.eraseFromParent();
3663     return BB;
3664   }
3665   case AMDGPU::V_ADD_U64_PSEUDO:
3666   case AMDGPU::V_SUB_U64_PSEUDO: {
3667     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3668     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3669     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3670     const DebugLoc &DL = MI.getDebugLoc();
3671 
3672     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3673 
3674     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3675 
3676     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3677     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3678 
3679     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3680     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3681 
3682     MachineOperand &Dest = MI.getOperand(0);
3683     MachineOperand &Src0 = MI.getOperand(1);
3684     MachineOperand &Src1 = MI.getOperand(2);
3685 
3686     const TargetRegisterClass *Src0RC = Src0.isReg()
3687                                             ? MRI.getRegClass(Src0.getReg())
3688                                             : &AMDGPU::VReg_64RegClass;
3689     const TargetRegisterClass *Src1RC = Src1.isReg()
3690                                             ? MRI.getRegClass(Src1.getReg())
3691                                             : &AMDGPU::VReg_64RegClass;
3692 
3693     const TargetRegisterClass *Src0SubRC =
3694         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3695     const TargetRegisterClass *Src1SubRC =
3696         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3697 
3698     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3699         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3700     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3701         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3702 
3703     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3704         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3705     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3706         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3707 
3708     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
3709     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3710                                .addReg(CarryReg, RegState::Define)
3711                                .add(SrcReg0Sub0)
3712                                .add(SrcReg1Sub0)
3713                                .addImm(0); // clamp bit
3714 
3715     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3716     MachineInstr *HiHalf =
3717         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3718             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3719             .add(SrcReg0Sub1)
3720             .add(SrcReg1Sub1)
3721             .addReg(CarryReg, RegState::Kill)
3722             .addImm(0); // clamp bit
3723 
3724     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3725         .addReg(DestSub0)
3726         .addImm(AMDGPU::sub0)
3727         .addReg(DestSub1)
3728         .addImm(AMDGPU::sub1);
3729     TII->legalizeOperands(*LoHalf);
3730     TII->legalizeOperands(*HiHalf);
3731     MI.eraseFromParent();
3732     return BB;
3733   }
3734   case AMDGPU::S_ADD_CO_PSEUDO:
3735   case AMDGPU::S_SUB_CO_PSEUDO: {
3736     // This pseudo has a chance to be selected
3737     // only from uniform add/subcarry node. All the VGPR operands
3738     // therefore assumed to be splat vectors.
3739     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3740     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3741     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3742     MachineBasicBlock::iterator MII = MI;
3743     const DebugLoc &DL = MI.getDebugLoc();
3744     MachineOperand &Dest = MI.getOperand(0);
3745     MachineOperand &Src0 = MI.getOperand(2);
3746     MachineOperand &Src1 = MI.getOperand(3);
3747     MachineOperand &Src2 = MI.getOperand(4);
3748     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3749                        ? AMDGPU::S_ADDC_U32
3750                        : AMDGPU::S_SUBB_U32;
3751     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3752       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3753       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3754           .addReg(Src0.getReg());
3755       Src0.setReg(RegOp0);
3756     }
3757     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3758       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3759       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3760           .addReg(Src1.getReg());
3761       Src1.setReg(RegOp1);
3762     }
3763     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3764     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3765       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3766           .addReg(Src2.getReg());
3767       Src2.setReg(RegOp2);
3768     }
3769 
3770     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
3771       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3772           .addReg(Src2.getReg())
3773           .addImm(0);
3774     } else {
3775       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
3776           .addReg(Src2.getReg())
3777           .addImm(0);
3778     }
3779 
3780     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
3781     MI.eraseFromParent();
3782     return BB;
3783   }
3784   case AMDGPU::SI_INIT_M0: {
3785     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3786             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3787         .add(MI.getOperand(0));
3788     MI.eraseFromParent();
3789     return BB;
3790   }
3791   case AMDGPU::SI_INIT_EXEC:
3792     // This should be before all vector instructions.
3793     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3794             AMDGPU::EXEC)
3795         .addImm(MI.getOperand(0).getImm());
3796     MI.eraseFromParent();
3797     return BB;
3798 
3799   case AMDGPU::SI_INIT_EXEC_LO:
3800     // This should be before all vector instructions.
3801     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3802             AMDGPU::EXEC_LO)
3803         .addImm(MI.getOperand(0).getImm());
3804     MI.eraseFromParent();
3805     return BB;
3806 
3807   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3808     // Extract the thread count from an SGPR input and set EXEC accordingly.
3809     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3810     //
3811     // S_BFE_U32 count, input, {shift, 7}
3812     // S_BFM_B64 exec, count, 0
3813     // S_CMP_EQ_U32 count, 64
3814     // S_CMOV_B64 exec, -1
3815     MachineInstr *FirstMI = &*BB->begin();
3816     MachineRegisterInfo &MRI = MF->getRegInfo();
3817     Register InputReg = MI.getOperand(0).getReg();
3818     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3819     bool Found = false;
3820 
3821     // Move the COPY of the input reg to the beginning, so that we can use it.
3822     for (auto I = BB->begin(); I != &MI; I++) {
3823       if (I->getOpcode() != TargetOpcode::COPY ||
3824           I->getOperand(0).getReg() != InputReg)
3825         continue;
3826 
3827       if (I == FirstMI) {
3828         FirstMI = &*++BB->begin();
3829       } else {
3830         I->removeFromParent();
3831         BB->insert(FirstMI, &*I);
3832       }
3833       Found = true;
3834       break;
3835     }
3836     assert(Found);
3837     (void)Found;
3838 
3839     // This should be before all vector instructions.
3840     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3841     bool isWave32 = getSubtarget()->isWave32();
3842     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3843     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3844         .addReg(InputReg)
3845         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3846     BuildMI(*BB, FirstMI, DebugLoc(),
3847             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3848             Exec)
3849         .addReg(CountReg)
3850         .addImm(0);
3851     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3852         .addReg(CountReg, RegState::Kill)
3853         .addImm(getSubtarget()->getWavefrontSize());
3854     BuildMI(*BB, FirstMI, DebugLoc(),
3855             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3856             Exec)
3857         .addImm(-1);
3858     MI.eraseFromParent();
3859     return BB;
3860   }
3861 
3862   case AMDGPU::GET_GROUPSTATICSIZE: {
3863     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3864            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3865     DebugLoc DL = MI.getDebugLoc();
3866     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3867         .add(MI.getOperand(0))
3868         .addImm(MFI->getLDSSize());
3869     MI.eraseFromParent();
3870     return BB;
3871   }
3872   case AMDGPU::SI_INDIRECT_SRC_V1:
3873   case AMDGPU::SI_INDIRECT_SRC_V2:
3874   case AMDGPU::SI_INDIRECT_SRC_V4:
3875   case AMDGPU::SI_INDIRECT_SRC_V8:
3876   case AMDGPU::SI_INDIRECT_SRC_V16:
3877     return emitIndirectSrc(MI, *BB, *getSubtarget());
3878   case AMDGPU::SI_INDIRECT_DST_V1:
3879   case AMDGPU::SI_INDIRECT_DST_V2:
3880   case AMDGPU::SI_INDIRECT_DST_V4:
3881   case AMDGPU::SI_INDIRECT_DST_V8:
3882   case AMDGPU::SI_INDIRECT_DST_V16:
3883     return emitIndirectDst(MI, *BB, *getSubtarget());
3884   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3885   case AMDGPU::SI_KILL_I1_PSEUDO:
3886     return splitKillBlock(MI, BB);
3887   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3888     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3889     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3890     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3891 
3892     Register Dst = MI.getOperand(0).getReg();
3893     Register Src0 = MI.getOperand(1).getReg();
3894     Register Src1 = MI.getOperand(2).getReg();
3895     const DebugLoc &DL = MI.getDebugLoc();
3896     Register SrcCond = MI.getOperand(3).getReg();
3897 
3898     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3899     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3900     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3901     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3902 
3903     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3904       .addReg(SrcCond);
3905     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3906       .addImm(0)
3907       .addReg(Src0, 0, AMDGPU::sub0)
3908       .addImm(0)
3909       .addReg(Src1, 0, AMDGPU::sub0)
3910       .addReg(SrcCondCopy);
3911     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3912       .addImm(0)
3913       .addReg(Src0, 0, AMDGPU::sub1)
3914       .addImm(0)
3915       .addReg(Src1, 0, AMDGPU::sub1)
3916       .addReg(SrcCondCopy);
3917 
3918     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3919       .addReg(DstLo)
3920       .addImm(AMDGPU::sub0)
3921       .addReg(DstHi)
3922       .addImm(AMDGPU::sub1);
3923     MI.eraseFromParent();
3924     return BB;
3925   }
3926   case AMDGPU::SI_BR_UNDEF: {
3927     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3928     const DebugLoc &DL = MI.getDebugLoc();
3929     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3930                            .add(MI.getOperand(0));
3931     Br->getOperand(1).setIsUndef(true); // read undef SCC
3932     MI.eraseFromParent();
3933     return BB;
3934   }
3935   case AMDGPU::ADJCALLSTACKUP:
3936   case AMDGPU::ADJCALLSTACKDOWN: {
3937     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3938     MachineInstrBuilder MIB(*MF, &MI);
3939 
3940     // Add an implicit use of the frame offset reg to prevent the restore copy
3941     // inserted after the call from being reorderd after stack operations in the
3942     // the caller's frame.
3943     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3944         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3945         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3946     return BB;
3947   }
3948   case AMDGPU::SI_CALL_ISEL: {
3949     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3950     const DebugLoc &DL = MI.getDebugLoc();
3951 
3952     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3953 
3954     MachineInstrBuilder MIB;
3955     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3956 
3957     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3958       MIB.add(MI.getOperand(I));
3959 
3960     MIB.cloneMemRefs(MI);
3961     MI.eraseFromParent();
3962     return BB;
3963   }
3964   case AMDGPU::V_ADD_I32_e32:
3965   case AMDGPU::V_SUB_I32_e32:
3966   case AMDGPU::V_SUBREV_I32_e32: {
3967     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3968     const DebugLoc &DL = MI.getDebugLoc();
3969     unsigned Opc = MI.getOpcode();
3970 
3971     bool NeedClampOperand = false;
3972     if (TII->pseudoToMCOpcode(Opc) == -1) {
3973       Opc = AMDGPU::getVOPe64(Opc);
3974       NeedClampOperand = true;
3975     }
3976 
3977     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3978     if (TII->isVOP3(*I)) {
3979       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3980       const SIRegisterInfo *TRI = ST.getRegisterInfo();
3981       I.addReg(TRI->getVCC(), RegState::Define);
3982     }
3983     I.add(MI.getOperand(1))
3984      .add(MI.getOperand(2));
3985     if (NeedClampOperand)
3986       I.addImm(0); // clamp bit for e64 encoding
3987 
3988     TII->legalizeOperands(*I);
3989 
3990     MI.eraseFromParent();
3991     return BB;
3992   }
3993   case AMDGPU::DS_GWS_INIT:
3994   case AMDGPU::DS_GWS_SEMA_V:
3995   case AMDGPU::DS_GWS_SEMA_BR:
3996   case AMDGPU::DS_GWS_SEMA_P:
3997   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
3998   case AMDGPU::DS_GWS_BARRIER:
3999     // A s_waitcnt 0 is required to be the instruction immediately following.
4000     if (getSubtarget()->hasGWSAutoReplay()) {
4001       bundleInstWithWaitcnt(MI);
4002       return BB;
4003     }
4004 
4005     return emitGWSMemViolTestLoop(MI, BB);
4006   default:
4007     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4008   }
4009 }
4010 
4011 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4012   return isTypeLegal(VT.getScalarType());
4013 }
4014 
4015 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4016   // This currently forces unfolding various combinations of fsub into fma with
4017   // free fneg'd operands. As long as we have fast FMA (controlled by
4018   // isFMAFasterThanFMulAndFAdd), we should perform these.
4019 
4020   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4021   // most of these combines appear to be cycle neutral but save on instruction
4022   // count / code size.
4023   return true;
4024 }
4025 
4026 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4027                                          EVT VT) const {
4028   if (!VT.isVector()) {
4029     return MVT::i1;
4030   }
4031   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4032 }
4033 
4034 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4035   // TODO: Should i16 be used always if legal? For now it would force VALU
4036   // shifts.
4037   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4038 }
4039 
4040 // Answering this is somewhat tricky and depends on the specific device which
4041 // have different rates for fma or all f64 operations.
4042 //
4043 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4044 // regardless of which device (although the number of cycles differs between
4045 // devices), so it is always profitable for f64.
4046 //
4047 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4048 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4049 // which we can always do even without fused FP ops since it returns the same
4050 // result as the separate operations and since it is always full
4051 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4052 // however does not support denormals, so we do report fma as faster if we have
4053 // a fast fma device and require denormals.
4054 //
4055 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4056                                                   EVT VT) const {
4057   VT = VT.getScalarType();
4058 
4059   switch (VT.getSimpleVT().SimpleTy) {
4060   case MVT::f32: {
4061     // This is as fast on some subtargets. However, we always have full rate f32
4062     // mad available which returns the same result as the separate operations
4063     // which we should prefer over fma. We can't use this if we want to support
4064     // denormals, so only report this in these cases.
4065     if (hasFP32Denormals(MF))
4066       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4067 
4068     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4069     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4070   }
4071   case MVT::f64:
4072     return true;
4073   case MVT::f16:
4074     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4075   default:
4076     break;
4077   }
4078 
4079   return false;
4080 }
4081 
4082 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4083                                    const SDNode *N) const {
4084   // TODO: Check future ftz flag
4085   // v_mad_f32/v_mac_f32 do not support denormals.
4086   EVT VT = N->getValueType(0);
4087   if (VT == MVT::f32)
4088     return !hasFP32Denormals(DAG.getMachineFunction());
4089   if (VT == MVT::f16) {
4090     return Subtarget->hasMadF16() &&
4091            !hasFP64FP16Denormals(DAG.getMachineFunction());
4092   }
4093 
4094   return false;
4095 }
4096 
4097 //===----------------------------------------------------------------------===//
4098 // Custom DAG Lowering Operations
4099 //===----------------------------------------------------------------------===//
4100 
4101 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4102 // wider vector type is legal.
4103 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4104                                              SelectionDAG &DAG) const {
4105   unsigned Opc = Op.getOpcode();
4106   EVT VT = Op.getValueType();
4107   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4108 
4109   SDValue Lo, Hi;
4110   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4111 
4112   SDLoc SL(Op);
4113   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4114                              Op->getFlags());
4115   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4116                              Op->getFlags());
4117 
4118   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4119 }
4120 
4121 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4122 // wider vector type is legal.
4123 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4124                                               SelectionDAG &DAG) const {
4125   unsigned Opc = Op.getOpcode();
4126   EVT VT = Op.getValueType();
4127   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4128 
4129   SDValue Lo0, Hi0;
4130   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4131   SDValue Lo1, Hi1;
4132   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4133 
4134   SDLoc SL(Op);
4135 
4136   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4137                              Op->getFlags());
4138   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4139                              Op->getFlags());
4140 
4141   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4142 }
4143 
4144 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4145                                               SelectionDAG &DAG) const {
4146   unsigned Opc = Op.getOpcode();
4147   EVT VT = Op.getValueType();
4148   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4149 
4150   SDValue Lo0, Hi0;
4151   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4152   SDValue Lo1, Hi1;
4153   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4154   SDValue Lo2, Hi2;
4155   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4156 
4157   SDLoc SL(Op);
4158 
4159   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4160                              Op->getFlags());
4161   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4162                              Op->getFlags());
4163 
4164   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4165 }
4166 
4167 
4168 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4169   switch (Op.getOpcode()) {
4170   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4171   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4172   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4173   case ISD::LOAD: {
4174     SDValue Result = LowerLOAD(Op, DAG);
4175     assert((!Result.getNode() ||
4176             Result.getNode()->getNumValues() == 2) &&
4177            "Load should return a value and a chain");
4178     return Result;
4179   }
4180 
4181   case ISD::FSIN:
4182   case ISD::FCOS:
4183     return LowerTrig(Op, DAG);
4184   case ISD::SELECT: return LowerSELECT(Op, DAG);
4185   case ISD::FDIV: return LowerFDIV(Op, DAG);
4186   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4187   case ISD::STORE: return LowerSTORE(Op, DAG);
4188   case ISD::GlobalAddress: {
4189     MachineFunction &MF = DAG.getMachineFunction();
4190     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4191     return LowerGlobalAddress(MFI, Op, DAG);
4192   }
4193   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4194   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4195   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4196   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4197   case ISD::INSERT_SUBVECTOR:
4198     return lowerINSERT_SUBVECTOR(Op, DAG);
4199   case ISD::INSERT_VECTOR_ELT:
4200     return lowerINSERT_VECTOR_ELT(Op, DAG);
4201   case ISD::EXTRACT_VECTOR_ELT:
4202     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4203   case ISD::VECTOR_SHUFFLE:
4204     return lowerVECTOR_SHUFFLE(Op, DAG);
4205   case ISD::BUILD_VECTOR:
4206     return lowerBUILD_VECTOR(Op, DAG);
4207   case ISD::FP_ROUND:
4208     return lowerFP_ROUND(Op, DAG);
4209   case ISD::TRAP:
4210     return lowerTRAP(Op, DAG);
4211   case ISD::DEBUGTRAP:
4212     return lowerDEBUGTRAP(Op, DAG);
4213   case ISD::FABS:
4214   case ISD::FNEG:
4215   case ISD::FCANONICALIZE:
4216   case ISD::BSWAP:
4217     return splitUnaryVectorOp(Op, DAG);
4218   case ISD::FMINNUM:
4219   case ISD::FMAXNUM:
4220     return lowerFMINNUM_FMAXNUM(Op, DAG);
4221   case ISD::FMA:
4222     return splitTernaryVectorOp(Op, DAG);
4223   case ISD::SHL:
4224   case ISD::SRA:
4225   case ISD::SRL:
4226   case ISD::ADD:
4227   case ISD::SUB:
4228   case ISD::MUL:
4229   case ISD::SMIN:
4230   case ISD::SMAX:
4231   case ISD::UMIN:
4232   case ISD::UMAX:
4233   case ISD::FADD:
4234   case ISD::FMUL:
4235   case ISD::FMINNUM_IEEE:
4236   case ISD::FMAXNUM_IEEE:
4237     return splitBinaryVectorOp(Op, DAG);
4238   }
4239   return SDValue();
4240 }
4241 
4242 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4243                                        const SDLoc &DL,
4244                                        SelectionDAG &DAG, bool Unpacked) {
4245   if (!LoadVT.isVector())
4246     return Result;
4247 
4248   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4249     // Truncate to v2i16/v4i16.
4250     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4251 
4252     // Workaround legalizer not scalarizing truncate after vector op
4253     // legalization byt not creating intermediate vector trunc.
4254     SmallVector<SDValue, 4> Elts;
4255     DAG.ExtractVectorElements(Result, Elts);
4256     for (SDValue &Elt : Elts)
4257       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4258 
4259     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4260 
4261     // Bitcast to original type (v2f16/v4f16).
4262     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4263   }
4264 
4265   // Cast back to the original packed type.
4266   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4267 }
4268 
4269 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4270                                               MemSDNode *M,
4271                                               SelectionDAG &DAG,
4272                                               ArrayRef<SDValue> Ops,
4273                                               bool IsIntrinsic) const {
4274   SDLoc DL(M);
4275 
4276   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4277   EVT LoadVT = M->getValueType(0);
4278 
4279   EVT EquivLoadVT = LoadVT;
4280   if (Unpacked && LoadVT.isVector()) {
4281     EquivLoadVT = LoadVT.isVector() ?
4282       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4283                        LoadVT.getVectorNumElements()) : LoadVT;
4284   }
4285 
4286   // Change from v4f16/v2f16 to EquivLoadVT.
4287   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4288 
4289   SDValue Load
4290     = DAG.getMemIntrinsicNode(
4291       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4292       VTList, Ops, M->getMemoryVT(),
4293       M->getMemOperand());
4294   if (!Unpacked) // Just adjusted the opcode.
4295     return Load;
4296 
4297   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4298 
4299   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4300 }
4301 
4302 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4303                                              SelectionDAG &DAG,
4304                                              ArrayRef<SDValue> Ops) const {
4305   SDLoc DL(M);
4306   EVT LoadVT = M->getValueType(0);
4307   EVT EltType = LoadVT.getScalarType();
4308   EVT IntVT = LoadVT.changeTypeToInteger();
4309 
4310   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4311 
4312   unsigned Opc =
4313       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4314 
4315   if (IsD16) {
4316     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4317   }
4318 
4319   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4320   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4321     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4322 
4323   if (isTypeLegal(LoadVT)) {
4324     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4325                                M->getMemOperand(), DAG);
4326   }
4327 
4328   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4329   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4330   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4331                                         M->getMemOperand(), DAG);
4332   return DAG.getMergeValues(
4333       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4334       DL);
4335 }
4336 
4337 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4338                                   SDNode *N, SelectionDAG &DAG) {
4339   EVT VT = N->getValueType(0);
4340   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4341   int CondCode = CD->getSExtValue();
4342   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4343       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4344     return DAG.getUNDEF(VT);
4345 
4346   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4347 
4348   SDValue LHS = N->getOperand(1);
4349   SDValue RHS = N->getOperand(2);
4350 
4351   SDLoc DL(N);
4352 
4353   EVT CmpVT = LHS.getValueType();
4354   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4355     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4356       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4357     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4358     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4359   }
4360 
4361   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4362 
4363   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4364   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4365 
4366   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4367                               DAG.getCondCode(CCOpcode));
4368   if (VT.bitsEq(CCVT))
4369     return SetCC;
4370   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4371 }
4372 
4373 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4374                                   SDNode *N, SelectionDAG &DAG) {
4375   EVT VT = N->getValueType(0);
4376   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4377 
4378   int CondCode = CD->getSExtValue();
4379   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4380       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4381     return DAG.getUNDEF(VT);
4382   }
4383 
4384   SDValue Src0 = N->getOperand(1);
4385   SDValue Src1 = N->getOperand(2);
4386   EVT CmpVT = Src0.getValueType();
4387   SDLoc SL(N);
4388 
4389   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4390     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4391     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4392   }
4393 
4394   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4395   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4396   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4397   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4398   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4399                               Src1, DAG.getCondCode(CCOpcode));
4400   if (VT.bitsEq(CCVT))
4401     return SetCC;
4402   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4403 }
4404 
4405 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4406                                     SelectionDAG &DAG) {
4407   EVT VT = N->getValueType(0);
4408   SDValue Src = N->getOperand(1);
4409   SDLoc SL(N);
4410 
4411   if (Src.getOpcode() == ISD::SETCC) {
4412     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4413     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4414                        Src.getOperand(1), Src.getOperand(2));
4415   }
4416   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4417     // (ballot 0) -> 0
4418     if (Arg->isNullValue())
4419       return DAG.getConstant(0, SL, VT);
4420 
4421     // (ballot 1) -> EXEC/EXEC_LO
4422     if (Arg->isOne()) {
4423       Register Exec;
4424       if (VT.getScalarSizeInBits() == 32)
4425         Exec = AMDGPU::EXEC_LO;
4426       else if (VT.getScalarSizeInBits() == 64)
4427         Exec = AMDGPU::EXEC;
4428       else
4429         return SDValue();
4430 
4431       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4432     }
4433   }
4434 
4435   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4436   // ISD::SETNE)
4437   return DAG.getNode(
4438       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4439       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4440 }
4441 
4442 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4443                                           SmallVectorImpl<SDValue> &Results,
4444                                           SelectionDAG &DAG) const {
4445   switch (N->getOpcode()) {
4446   case ISD::INSERT_VECTOR_ELT: {
4447     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4448       Results.push_back(Res);
4449     return;
4450   }
4451   case ISD::EXTRACT_VECTOR_ELT: {
4452     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4453       Results.push_back(Res);
4454     return;
4455   }
4456   case ISD::INTRINSIC_WO_CHAIN: {
4457     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4458     switch (IID) {
4459     case Intrinsic::amdgcn_cvt_pkrtz: {
4460       SDValue Src0 = N->getOperand(1);
4461       SDValue Src1 = N->getOperand(2);
4462       SDLoc SL(N);
4463       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4464                                 Src0, Src1);
4465       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4466       return;
4467     }
4468     case Intrinsic::amdgcn_cvt_pknorm_i16:
4469     case Intrinsic::amdgcn_cvt_pknorm_u16:
4470     case Intrinsic::amdgcn_cvt_pk_i16:
4471     case Intrinsic::amdgcn_cvt_pk_u16: {
4472       SDValue Src0 = N->getOperand(1);
4473       SDValue Src1 = N->getOperand(2);
4474       SDLoc SL(N);
4475       unsigned Opcode;
4476 
4477       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4478         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4479       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4480         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4481       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4482         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4483       else
4484         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4485 
4486       EVT VT = N->getValueType(0);
4487       if (isTypeLegal(VT))
4488         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4489       else {
4490         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4491         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4492       }
4493       return;
4494     }
4495     }
4496     break;
4497   }
4498   case ISD::INTRINSIC_W_CHAIN: {
4499     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4500       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4501         // FIXME: Hacky
4502         Results.push_back(Res.getOperand(0));
4503         Results.push_back(Res.getOperand(1));
4504       } else {
4505         Results.push_back(Res);
4506         Results.push_back(Res.getValue(1));
4507       }
4508       return;
4509     }
4510 
4511     break;
4512   }
4513   case ISD::SELECT: {
4514     SDLoc SL(N);
4515     EVT VT = N->getValueType(0);
4516     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4517     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4518     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4519 
4520     EVT SelectVT = NewVT;
4521     if (NewVT.bitsLT(MVT::i32)) {
4522       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4523       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4524       SelectVT = MVT::i32;
4525     }
4526 
4527     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4528                                     N->getOperand(0), LHS, RHS);
4529 
4530     if (NewVT != SelectVT)
4531       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4532     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4533     return;
4534   }
4535   case ISD::FNEG: {
4536     if (N->getValueType(0) != MVT::v2f16)
4537       break;
4538 
4539     SDLoc SL(N);
4540     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4541 
4542     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4543                              BC,
4544                              DAG.getConstant(0x80008000, SL, MVT::i32));
4545     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4546     return;
4547   }
4548   case ISD::FABS: {
4549     if (N->getValueType(0) != MVT::v2f16)
4550       break;
4551 
4552     SDLoc SL(N);
4553     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4554 
4555     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4556                              BC,
4557                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4558     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4559     return;
4560   }
4561   default:
4562     break;
4563   }
4564 }
4565 
4566 /// Helper function for LowerBRCOND
4567 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4568 
4569   SDNode *Parent = Value.getNode();
4570   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4571        I != E; ++I) {
4572 
4573     if (I.getUse().get() != Value)
4574       continue;
4575 
4576     if (I->getOpcode() == Opcode)
4577       return *I;
4578   }
4579   return nullptr;
4580 }
4581 
4582 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4583   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4584     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4585     case Intrinsic::amdgcn_if:
4586       return AMDGPUISD::IF;
4587     case Intrinsic::amdgcn_else:
4588       return AMDGPUISD::ELSE;
4589     case Intrinsic::amdgcn_loop:
4590       return AMDGPUISD::LOOP;
4591     case Intrinsic::amdgcn_end_cf:
4592       llvm_unreachable("should not occur");
4593     default:
4594       return 0;
4595     }
4596   }
4597 
4598   // break, if_break, else_break are all only used as inputs to loop, not
4599   // directly as branch conditions.
4600   return 0;
4601 }
4602 
4603 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4604   const Triple &TT = getTargetMachine().getTargetTriple();
4605   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4606           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4607          AMDGPU::shouldEmitConstantsToTextSection(TT);
4608 }
4609 
4610 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4611   // FIXME: Either avoid relying on address space here or change the default
4612   // address space for functions to avoid the explicit check.
4613   return (GV->getValueType()->isFunctionTy() ||
4614           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4615          !shouldEmitFixup(GV) &&
4616          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4617 }
4618 
4619 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4620   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4621 }
4622 
4623 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4624   if (!GV->hasExternalLinkage())
4625     return true;
4626 
4627   const auto OS = getTargetMachine().getTargetTriple().getOS();
4628   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4629 }
4630 
4631 /// This transforms the control flow intrinsics to get the branch destination as
4632 /// last parameter, also switches branch target with BR if the need arise
4633 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4634                                       SelectionDAG &DAG) const {
4635   SDLoc DL(BRCOND);
4636 
4637   SDNode *Intr = BRCOND.getOperand(1).getNode();
4638   SDValue Target = BRCOND.getOperand(2);
4639   SDNode *BR = nullptr;
4640   SDNode *SetCC = nullptr;
4641 
4642   if (Intr->getOpcode() == ISD::SETCC) {
4643     // As long as we negate the condition everything is fine
4644     SetCC = Intr;
4645     Intr = SetCC->getOperand(0).getNode();
4646 
4647   } else {
4648     // Get the target from BR if we don't negate the condition
4649     BR = findUser(BRCOND, ISD::BR);
4650     Target = BR->getOperand(1);
4651   }
4652 
4653   // FIXME: This changes the types of the intrinsics instead of introducing new
4654   // nodes with the correct types.
4655   // e.g. llvm.amdgcn.loop
4656 
4657   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4658   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4659 
4660   unsigned CFNode = isCFIntrinsic(Intr);
4661   if (CFNode == 0) {
4662     // This is a uniform branch so we don't need to legalize.
4663     return BRCOND;
4664   }
4665 
4666   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4667                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4668 
4669   assert(!SetCC ||
4670         (SetCC->getConstantOperandVal(1) == 1 &&
4671          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4672                                                              ISD::SETNE));
4673 
4674   // operands of the new intrinsic call
4675   SmallVector<SDValue, 4> Ops;
4676   if (HaveChain)
4677     Ops.push_back(BRCOND.getOperand(0));
4678 
4679   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4680   Ops.push_back(Target);
4681 
4682   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4683 
4684   // build the new intrinsic call
4685   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4686 
4687   if (!HaveChain) {
4688     SDValue Ops[] =  {
4689       SDValue(Result, 0),
4690       BRCOND.getOperand(0)
4691     };
4692 
4693     Result = DAG.getMergeValues(Ops, DL).getNode();
4694   }
4695 
4696   if (BR) {
4697     // Give the branch instruction our target
4698     SDValue Ops[] = {
4699       BR->getOperand(0),
4700       BRCOND.getOperand(2)
4701     };
4702     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4703     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4704   }
4705 
4706   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4707 
4708   // Copy the intrinsic results to registers
4709   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4710     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4711     if (!CopyToReg)
4712       continue;
4713 
4714     Chain = DAG.getCopyToReg(
4715       Chain, DL,
4716       CopyToReg->getOperand(1),
4717       SDValue(Result, i - 1),
4718       SDValue());
4719 
4720     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4721   }
4722 
4723   // Remove the old intrinsic from the chain
4724   DAG.ReplaceAllUsesOfValueWith(
4725     SDValue(Intr, Intr->getNumValues() - 1),
4726     Intr->getOperand(0));
4727 
4728   return Chain;
4729 }
4730 
4731 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4732                                           SelectionDAG &DAG) const {
4733   MVT VT = Op.getSimpleValueType();
4734   SDLoc DL(Op);
4735   // Checking the depth
4736   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4737     return DAG.getConstant(0, DL, VT);
4738 
4739   MachineFunction &MF = DAG.getMachineFunction();
4740   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4741   // Check for kernel and shader functions
4742   if (Info->isEntryFunction())
4743     return DAG.getConstant(0, DL, VT);
4744 
4745   MachineFrameInfo &MFI = MF.getFrameInfo();
4746   // There is a call to @llvm.returnaddress in this function
4747   MFI.setReturnAddressIsTaken(true);
4748 
4749   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4750   // Get the return address reg and mark it as an implicit live-in
4751   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4752 
4753   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4754 }
4755 
4756 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4757                                             SDValue Op,
4758                                             const SDLoc &DL,
4759                                             EVT VT) const {
4760   return Op.getValueType().bitsLE(VT) ?
4761       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4762     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4763                 DAG.getTargetConstant(0, DL, MVT::i32));
4764 }
4765 
4766 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4767   assert(Op.getValueType() == MVT::f16 &&
4768          "Do not know how to custom lower FP_ROUND for non-f16 type");
4769 
4770   SDValue Src = Op.getOperand(0);
4771   EVT SrcVT = Src.getValueType();
4772   if (SrcVT != MVT::f64)
4773     return Op;
4774 
4775   SDLoc DL(Op);
4776 
4777   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4778   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4779   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4780 }
4781 
4782 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4783                                                SelectionDAG &DAG) const {
4784   EVT VT = Op.getValueType();
4785   const MachineFunction &MF = DAG.getMachineFunction();
4786   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4787   bool IsIEEEMode = Info->getMode().IEEE;
4788 
4789   // FIXME: Assert during selection that this is only selected for
4790   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4791   // mode functions, but this happens to be OK since it's only done in cases
4792   // where there is known no sNaN.
4793   if (IsIEEEMode)
4794     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4795 
4796   if (VT == MVT::v4f16)
4797     return splitBinaryVectorOp(Op, DAG);
4798   return Op;
4799 }
4800 
4801 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4802   SDLoc SL(Op);
4803   SDValue Chain = Op.getOperand(0);
4804 
4805   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4806       !Subtarget->isTrapHandlerEnabled())
4807     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4808 
4809   MachineFunction &MF = DAG.getMachineFunction();
4810   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4811   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4812   assert(UserSGPR != AMDGPU::NoRegister);
4813   SDValue QueuePtr = CreateLiveInRegister(
4814     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4815   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4816   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4817                                    QueuePtr, SDValue());
4818   SDValue Ops[] = {
4819     ToReg,
4820     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4821     SGPR01,
4822     ToReg.getValue(1)
4823   };
4824   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4825 }
4826 
4827 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4828   SDLoc SL(Op);
4829   SDValue Chain = Op.getOperand(0);
4830   MachineFunction &MF = DAG.getMachineFunction();
4831 
4832   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4833       !Subtarget->isTrapHandlerEnabled()) {
4834     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4835                                      "debugtrap handler not supported",
4836                                      Op.getDebugLoc(),
4837                                      DS_Warning);
4838     LLVMContext &Ctx = MF.getFunction().getContext();
4839     Ctx.diagnose(NoTrap);
4840     return Chain;
4841   }
4842 
4843   SDValue Ops[] = {
4844     Chain,
4845     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4846   };
4847   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4848 }
4849 
4850 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4851                                              SelectionDAG &DAG) const {
4852   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4853   if (Subtarget->hasApertureRegs()) {
4854     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4855         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4856         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4857     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4858         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4859         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4860     unsigned Encoding =
4861         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4862         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4863         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4864 
4865     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4866     SDValue ApertureReg = SDValue(
4867         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4868     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4869     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4870   }
4871 
4872   MachineFunction &MF = DAG.getMachineFunction();
4873   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4874   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4875   assert(UserSGPR != AMDGPU::NoRegister);
4876 
4877   SDValue QueuePtr = CreateLiveInRegister(
4878     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4879 
4880   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4881   // private_segment_aperture_base_hi.
4882   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4883 
4884   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4885 
4886   // TODO: Use custom target PseudoSourceValue.
4887   // TODO: We should use the value from the IR intrinsic call, but it might not
4888   // be available and how do we get it?
4889   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
4890   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4891                      MinAlign(64, StructOffset),
4892                      MachineMemOperand::MODereferenceable |
4893                          MachineMemOperand::MOInvariant);
4894 }
4895 
4896 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4897                                              SelectionDAG &DAG) const {
4898   SDLoc SL(Op);
4899   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4900 
4901   SDValue Src = ASC->getOperand(0);
4902   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4903 
4904   const AMDGPUTargetMachine &TM =
4905     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4906 
4907   // flat -> local/private
4908   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4909     unsigned DestAS = ASC->getDestAddressSpace();
4910 
4911     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4912         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4913       unsigned NullVal = TM.getNullPointerValue(DestAS);
4914       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4915       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4916       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4917 
4918       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4919                          NonNull, Ptr, SegmentNullPtr);
4920     }
4921   }
4922 
4923   // local/private -> flat
4924   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4925     unsigned SrcAS = ASC->getSrcAddressSpace();
4926 
4927     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4928         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4929       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4930       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4931 
4932       SDValue NonNull
4933         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4934 
4935       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4936       SDValue CvtPtr
4937         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4938 
4939       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4940                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4941                          FlatNullPtr);
4942     }
4943   }
4944 
4945   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
4946       Src.getValueType() == MVT::i64)
4947     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4948 
4949   // global <-> flat are no-ops and never emitted.
4950 
4951   const MachineFunction &MF = DAG.getMachineFunction();
4952   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4953     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4954   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4955 
4956   return DAG.getUNDEF(ASC->getValueType(0));
4957 }
4958 
4959 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4960 // the small vector and inserting them into the big vector. That is better than
4961 // the default expansion of doing it via a stack slot. Even though the use of
4962 // the stack slot would be optimized away afterwards, the stack slot itself
4963 // remains.
4964 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4965                                                 SelectionDAG &DAG) const {
4966   SDValue Vec = Op.getOperand(0);
4967   SDValue Ins = Op.getOperand(1);
4968   SDValue Idx = Op.getOperand(2);
4969   EVT VecVT = Vec.getValueType();
4970   EVT InsVT = Ins.getValueType();
4971   EVT EltVT = VecVT.getVectorElementType();
4972   unsigned InsNumElts = InsVT.getVectorNumElements();
4973   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4974   SDLoc SL(Op);
4975 
4976   for (unsigned I = 0; I != InsNumElts; ++I) {
4977     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4978                               DAG.getConstant(I, SL, MVT::i32));
4979     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4980                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
4981   }
4982   return Vec;
4983 }
4984 
4985 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4986                                                  SelectionDAG &DAG) const {
4987   SDValue Vec = Op.getOperand(0);
4988   SDValue InsVal = Op.getOperand(1);
4989   SDValue Idx = Op.getOperand(2);
4990   EVT VecVT = Vec.getValueType();
4991   EVT EltVT = VecVT.getVectorElementType();
4992   unsigned VecSize = VecVT.getSizeInBits();
4993   unsigned EltSize = EltVT.getSizeInBits();
4994 
4995 
4996   assert(VecSize <= 64);
4997 
4998   unsigned NumElts = VecVT.getVectorNumElements();
4999   SDLoc SL(Op);
5000   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5001 
5002   if (NumElts == 4 && EltSize == 16 && KIdx) {
5003     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5004 
5005     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5006                                  DAG.getConstant(0, SL, MVT::i32));
5007     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5008                                  DAG.getConstant(1, SL, MVT::i32));
5009 
5010     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5011     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5012 
5013     unsigned Idx = KIdx->getZExtValue();
5014     bool InsertLo = Idx < 2;
5015     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5016       InsertLo ? LoVec : HiVec,
5017       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5018       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5019 
5020     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5021 
5022     SDValue Concat = InsertLo ?
5023       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5024       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5025 
5026     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5027   }
5028 
5029   if (isa<ConstantSDNode>(Idx))
5030     return SDValue();
5031 
5032   MVT IntVT = MVT::getIntegerVT(VecSize);
5033 
5034   // Avoid stack access for dynamic indexing.
5035   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5036 
5037   // Create a congruent vector with the target value in each element so that
5038   // the required element can be masked and ORed into the target vector.
5039   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5040                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5041 
5042   assert(isPowerOf2_32(EltSize));
5043   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5044 
5045   // Convert vector index to bit-index.
5046   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5047 
5048   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5049   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5050                             DAG.getConstant(0xffff, SL, IntVT),
5051                             ScaledIdx);
5052 
5053   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5054   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5055                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5056 
5057   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5058   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5059 }
5060 
5061 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5062                                                   SelectionDAG &DAG) const {
5063   SDLoc SL(Op);
5064 
5065   EVT ResultVT = Op.getValueType();
5066   SDValue Vec = Op.getOperand(0);
5067   SDValue Idx = Op.getOperand(1);
5068   EVT VecVT = Vec.getValueType();
5069   unsigned VecSize = VecVT.getSizeInBits();
5070   EVT EltVT = VecVT.getVectorElementType();
5071   assert(VecSize <= 64);
5072 
5073   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5074 
5075   // Make sure we do any optimizations that will make it easier to fold
5076   // source modifiers before obscuring it with bit operations.
5077 
5078   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5079   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5080     return Combined;
5081 
5082   unsigned EltSize = EltVT.getSizeInBits();
5083   assert(isPowerOf2_32(EltSize));
5084 
5085   MVT IntVT = MVT::getIntegerVT(VecSize);
5086   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5087 
5088   // Convert vector index to bit-index (* EltSize)
5089   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5090 
5091   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5092   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5093 
5094   if (ResultVT == MVT::f16) {
5095     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5096     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5097   }
5098 
5099   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5100 }
5101 
5102 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5103   assert(Elt % 2 == 0);
5104   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5105 }
5106 
5107 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5108                                               SelectionDAG &DAG) const {
5109   SDLoc SL(Op);
5110   EVT ResultVT = Op.getValueType();
5111   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5112 
5113   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5114   EVT EltVT = PackVT.getVectorElementType();
5115   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5116 
5117   // vector_shuffle <0,1,6,7> lhs, rhs
5118   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5119   //
5120   // vector_shuffle <6,7,2,3> lhs, rhs
5121   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5122   //
5123   // vector_shuffle <6,7,0,1> lhs, rhs
5124   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5125 
5126   // Avoid scalarizing when both halves are reading from consecutive elements.
5127   SmallVector<SDValue, 4> Pieces;
5128   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5129     if (elementPairIsContiguous(SVN->getMask(), I)) {
5130       const int Idx = SVN->getMaskElt(I);
5131       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5132       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5133       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5134                                     PackVT, SVN->getOperand(VecIdx),
5135                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5136       Pieces.push_back(SubVec);
5137     } else {
5138       const int Idx0 = SVN->getMaskElt(I);
5139       const int Idx1 = SVN->getMaskElt(I + 1);
5140       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5141       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5142       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5143       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5144 
5145       SDValue Vec0 = SVN->getOperand(VecIdx0);
5146       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5147                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5148 
5149       SDValue Vec1 = SVN->getOperand(VecIdx1);
5150       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5151                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5152       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5153     }
5154   }
5155 
5156   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5157 }
5158 
5159 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5160                                             SelectionDAG &DAG) const {
5161   SDLoc SL(Op);
5162   EVT VT = Op.getValueType();
5163 
5164   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5165     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5166 
5167     // Turn into pair of packed build_vectors.
5168     // TODO: Special case for constants that can be materialized with s_mov_b64.
5169     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5170                                     { Op.getOperand(0), Op.getOperand(1) });
5171     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5172                                     { Op.getOperand(2), Op.getOperand(3) });
5173 
5174     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5175     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5176 
5177     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5178     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5179   }
5180 
5181   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5182   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5183 
5184   SDValue Lo = Op.getOperand(0);
5185   SDValue Hi = Op.getOperand(1);
5186 
5187   // Avoid adding defined bits with the zero_extend.
5188   if (Hi.isUndef()) {
5189     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5190     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5191     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5192   }
5193 
5194   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5195   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5196 
5197   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5198                               DAG.getConstant(16, SL, MVT::i32));
5199   if (Lo.isUndef())
5200     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5201 
5202   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5203   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5204 
5205   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5206   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5207 }
5208 
5209 bool
5210 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5211   // We can fold offsets for anything that doesn't require a GOT relocation.
5212   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5213           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5214           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5215          !shouldEmitGOTReloc(GA->getGlobal());
5216 }
5217 
5218 static SDValue
5219 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5220                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5221                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5222   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5223   // lowered to the following code sequence:
5224   //
5225   // For constant address space:
5226   //   s_getpc_b64 s[0:1]
5227   //   s_add_u32 s0, s0, $symbol
5228   //   s_addc_u32 s1, s1, 0
5229   //
5230   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5231   //   a fixup or relocation is emitted to replace $symbol with a literal
5232   //   constant, which is a pc-relative offset from the encoding of the $symbol
5233   //   operand to the global variable.
5234   //
5235   // For global address space:
5236   //   s_getpc_b64 s[0:1]
5237   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5238   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5239   //
5240   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5241   //   fixups or relocations are emitted to replace $symbol@*@lo and
5242   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5243   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5244   //   operand to the global variable.
5245   //
5246   // What we want here is an offset from the value returned by s_getpc
5247   // (which is the address of the s_add_u32 instruction) to the global
5248   // variable, but since the encoding of $symbol starts 4 bytes after the start
5249   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5250   // small. This requires us to add 4 to the global variable offset in order to
5251   // compute the correct address.
5252   SDValue PtrLo =
5253       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5254   SDValue PtrHi;
5255   if (GAFlags == SIInstrInfo::MO_NONE) {
5256     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5257   } else {
5258     PtrHi =
5259         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5260   }
5261   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5262 }
5263 
5264 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5265                                              SDValue Op,
5266                                              SelectionDAG &DAG) const {
5267   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5268   const GlobalValue *GV = GSD->getGlobal();
5269   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5270        shouldUseLDSConstAddress(GV)) ||
5271       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5272       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5273     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5274 
5275   SDLoc DL(GSD);
5276   EVT PtrVT = Op.getValueType();
5277 
5278   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5279     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5280                                             SIInstrInfo::MO_ABS32_LO);
5281     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5282   }
5283 
5284   if (shouldEmitFixup(GV))
5285     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5286   else if (shouldEmitPCReloc(GV))
5287     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5288                                    SIInstrInfo::MO_REL32);
5289 
5290   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5291                                             SIInstrInfo::MO_GOTPCREL32);
5292 
5293   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5294   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5295   const DataLayout &DataLayout = DAG.getDataLayout();
5296   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5297   MachinePointerInfo PtrInfo
5298     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5299 
5300   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5301                      MachineMemOperand::MODereferenceable |
5302                          MachineMemOperand::MOInvariant);
5303 }
5304 
5305 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5306                                    const SDLoc &DL, SDValue V) const {
5307   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5308   // the destination register.
5309   //
5310   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5311   // so we will end up with redundant moves to m0.
5312   //
5313   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5314 
5315   // A Null SDValue creates a glue result.
5316   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5317                                   V, Chain);
5318   return SDValue(M0, 0);
5319 }
5320 
5321 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5322                                                  SDValue Op,
5323                                                  MVT VT,
5324                                                  unsigned Offset) const {
5325   SDLoc SL(Op);
5326   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5327                                            DAG.getEntryNode(), Offset, 4, false);
5328   // The local size values will have the hi 16-bits as zero.
5329   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5330                      DAG.getValueType(VT));
5331 }
5332 
5333 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5334                                         EVT VT) {
5335   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5336                                       "non-hsa intrinsic with hsa target",
5337                                       DL.getDebugLoc());
5338   DAG.getContext()->diagnose(BadIntrin);
5339   return DAG.getUNDEF(VT);
5340 }
5341 
5342 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5343                                          EVT VT) {
5344   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5345                                       "intrinsic not supported on subtarget",
5346                                       DL.getDebugLoc());
5347   DAG.getContext()->diagnose(BadIntrin);
5348   return DAG.getUNDEF(VT);
5349 }
5350 
5351 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5352                                     ArrayRef<SDValue> Elts) {
5353   assert(!Elts.empty());
5354   MVT Type;
5355   unsigned NumElts;
5356 
5357   if (Elts.size() == 1) {
5358     Type = MVT::f32;
5359     NumElts = 1;
5360   } else if (Elts.size() == 2) {
5361     Type = MVT::v2f32;
5362     NumElts = 2;
5363   } else if (Elts.size() == 3) {
5364     Type = MVT::v3f32;
5365     NumElts = 3;
5366   } else if (Elts.size() <= 4) {
5367     Type = MVT::v4f32;
5368     NumElts = 4;
5369   } else if (Elts.size() <= 8) {
5370     Type = MVT::v8f32;
5371     NumElts = 8;
5372   } else {
5373     assert(Elts.size() <= 16);
5374     Type = MVT::v16f32;
5375     NumElts = 16;
5376   }
5377 
5378   SmallVector<SDValue, 16> VecElts(NumElts);
5379   for (unsigned i = 0; i < Elts.size(); ++i) {
5380     SDValue Elt = Elts[i];
5381     if (Elt.getValueType() != MVT::f32)
5382       Elt = DAG.getBitcast(MVT::f32, Elt);
5383     VecElts[i] = Elt;
5384   }
5385   for (unsigned i = Elts.size(); i < NumElts; ++i)
5386     VecElts[i] = DAG.getUNDEF(MVT::f32);
5387 
5388   if (NumElts == 1)
5389     return VecElts[0];
5390   return DAG.getBuildVector(Type, DL, VecElts);
5391 }
5392 
5393 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5394                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5395   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5396 
5397   uint64_t Value = CachePolicyConst->getZExtValue();
5398   SDLoc DL(CachePolicy);
5399   if (GLC) {
5400     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5401     Value &= ~(uint64_t)0x1;
5402   }
5403   if (SLC) {
5404     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5405     Value &= ~(uint64_t)0x2;
5406   }
5407   if (DLC) {
5408     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5409     Value &= ~(uint64_t)0x4;
5410   }
5411 
5412   return Value == 0;
5413 }
5414 
5415 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5416                               SDValue Src, int ExtraElts) {
5417   EVT SrcVT = Src.getValueType();
5418 
5419   SmallVector<SDValue, 8> Elts;
5420 
5421   if (SrcVT.isVector())
5422     DAG.ExtractVectorElements(Src, Elts);
5423   else
5424     Elts.push_back(Src);
5425 
5426   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5427   while (ExtraElts--)
5428     Elts.push_back(Undef);
5429 
5430   return DAG.getBuildVector(CastVT, DL, Elts);
5431 }
5432 
5433 // Re-construct the required return value for a image load intrinsic.
5434 // This is more complicated due to the optional use TexFailCtrl which means the required
5435 // return type is an aggregate
5436 static SDValue constructRetValue(SelectionDAG &DAG,
5437                                  MachineSDNode *Result,
5438                                  ArrayRef<EVT> ResultTypes,
5439                                  bool IsTexFail, bool Unpacked, bool IsD16,
5440                                  int DMaskPop, int NumVDataDwords,
5441                                  const SDLoc &DL, LLVMContext &Context) {
5442   // Determine the required return type. This is the same regardless of IsTexFail flag
5443   EVT ReqRetVT = ResultTypes[0];
5444   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5445   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5446     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5447 
5448   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5449     DMaskPop : (DMaskPop + 1) / 2;
5450 
5451   MVT DataDwordVT = NumDataDwords == 1 ?
5452     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5453 
5454   MVT MaskPopVT = MaskPopDwords == 1 ?
5455     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5456 
5457   SDValue Data(Result, 0);
5458   SDValue TexFail;
5459 
5460   if (IsTexFail) {
5461     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5462     if (MaskPopVT.isVector()) {
5463       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5464                          SDValue(Result, 0), ZeroIdx);
5465     } else {
5466       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5467                          SDValue(Result, 0), ZeroIdx);
5468     }
5469 
5470     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5471                           SDValue(Result, 0),
5472                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5473   }
5474 
5475   if (DataDwordVT.isVector())
5476     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5477                           NumDataDwords - MaskPopDwords);
5478 
5479   if (IsD16)
5480     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5481 
5482   if (!ReqRetVT.isVector())
5483     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5484 
5485   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5486 
5487   if (TexFail)
5488     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5489 
5490   if (Result->getNumValues() == 1)
5491     return Data;
5492 
5493   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5494 }
5495 
5496 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5497                          SDValue *LWE, bool &IsTexFail) {
5498   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5499 
5500   uint64_t Value = TexFailCtrlConst->getZExtValue();
5501   if (Value) {
5502     IsTexFail = true;
5503   }
5504 
5505   SDLoc DL(TexFailCtrlConst);
5506   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5507   Value &= ~(uint64_t)0x1;
5508   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5509   Value &= ~(uint64_t)0x2;
5510 
5511   return Value == 0;
5512 }
5513 
5514 SDValue SITargetLowering::lowerImage(SDValue Op,
5515                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5516                                      SelectionDAG &DAG) const {
5517   SDLoc DL(Op);
5518   MachineFunction &MF = DAG.getMachineFunction();
5519   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5520   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5521       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5522   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5523   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5524       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5525   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5526       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5527   unsigned IntrOpcode = Intr->BaseOpcode;
5528   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5529 
5530   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5531   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5532   bool IsD16 = false;
5533   bool IsA16 = false;
5534   SDValue VData;
5535   int NumVDataDwords;
5536   bool AdjustRetType = false;
5537 
5538   unsigned AddrIdx; // Index of first address argument
5539   unsigned DMask;
5540   unsigned DMaskLanes = 0;
5541 
5542   if (BaseOpcode->Atomic) {
5543     VData = Op.getOperand(2);
5544 
5545     bool Is64Bit = VData.getValueType() == MVT::i64;
5546     if (BaseOpcode->AtomicX2) {
5547       SDValue VData2 = Op.getOperand(3);
5548       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5549                                  {VData, VData2});
5550       if (Is64Bit)
5551         VData = DAG.getBitcast(MVT::v4i32, VData);
5552 
5553       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5554       DMask = Is64Bit ? 0xf : 0x3;
5555       NumVDataDwords = Is64Bit ? 4 : 2;
5556       AddrIdx = 4;
5557     } else {
5558       DMask = Is64Bit ? 0x3 : 0x1;
5559       NumVDataDwords = Is64Bit ? 2 : 1;
5560       AddrIdx = 3;
5561     }
5562   } else {
5563     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5564     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5565     DMask = DMaskConst->getZExtValue();
5566     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5567 
5568     if (BaseOpcode->Store) {
5569       VData = Op.getOperand(2);
5570 
5571       MVT StoreVT = VData.getSimpleValueType();
5572       if (StoreVT.getScalarType() == MVT::f16) {
5573         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5574           return Op; // D16 is unsupported for this instruction
5575 
5576         IsD16 = true;
5577         VData = handleD16VData(VData, DAG);
5578       }
5579 
5580       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5581     } else {
5582       // Work out the num dwords based on the dmask popcount and underlying type
5583       // and whether packing is supported.
5584       MVT LoadVT = ResultTypes[0].getSimpleVT();
5585       if (LoadVT.getScalarType() == MVT::f16) {
5586         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5587           return Op; // D16 is unsupported for this instruction
5588 
5589         IsD16 = true;
5590       }
5591 
5592       // Confirm that the return type is large enough for the dmask specified
5593       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5594           (!LoadVT.isVector() && DMaskLanes > 1))
5595           return Op;
5596 
5597       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5598         NumVDataDwords = (DMaskLanes + 1) / 2;
5599       else
5600         NumVDataDwords = DMaskLanes;
5601 
5602       AdjustRetType = true;
5603     }
5604 
5605     AddrIdx = DMaskIdx + 1;
5606   }
5607 
5608   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5609   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5610   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5611   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5612                        NumCoords + NumLCM;
5613   unsigned NumMIVAddrs = NumVAddrs;
5614 
5615   SmallVector<SDValue, 4> VAddrs;
5616 
5617   // Optimize _L to _LZ when _L is zero
5618   if (LZMappingInfo) {
5619     if (auto ConstantLod =
5620          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5621       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5622         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5623         NumMIVAddrs--;               // remove 'lod'
5624       }
5625     }
5626   }
5627 
5628   // Optimize _mip away, when 'lod' is zero
5629   if (MIPMappingInfo) {
5630     if (auto ConstantLod =
5631          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5632       if (ConstantLod->isNullValue()) {
5633         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5634         NumMIVAddrs--;               // remove 'lod'
5635       }
5636     }
5637   }
5638 
5639   // Check for 16 bit addresses and pack if true.
5640   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5641   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5642   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5643   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) {
5644     // Illegal to use a16 images
5645     if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16))
5646       return Op;
5647 
5648     IsA16 = true;
5649     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5650     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5651       SDValue AddrLo;
5652       // Push back extra arguments.
5653       if (i < DimIdx) {
5654         AddrLo = Op.getOperand(i);
5655       } else {
5656         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5657         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5658         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5659             ((NumGradients / 2) % 2 == 1 &&
5660             (i == DimIdx + (NumGradients / 2) - 1 ||
5661              i == DimIdx + NumGradients - 1))) {
5662           AddrLo = Op.getOperand(i);
5663           if (AddrLo.getValueType() != MVT::i16)
5664             AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i));
5665           AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo);
5666         } else {
5667           AddrLo = DAG.getBuildVector(VectorVT, DL,
5668                                       {Op.getOperand(i), Op.getOperand(i + 1)});
5669           i++;
5670         }
5671         AddrLo = DAG.getBitcast(MVT::f32, AddrLo);
5672       }
5673       VAddrs.push_back(AddrLo);
5674     }
5675   } else {
5676     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5677       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5678   }
5679 
5680   // If the register allocator cannot place the address registers contiguously
5681   // without introducing moves, then using the non-sequential address encoding
5682   // is always preferable, since it saves VALU instructions and is usually a
5683   // wash in terms of code size or even better.
5684   //
5685   // However, we currently have no way of hinting to the register allocator that
5686   // MIMG addresses should be placed contiguously when it is possible to do so,
5687   // so force non-NSA for the common 2-address case as a heuristic.
5688   //
5689   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5690   // allocation when possible.
5691   bool UseNSA =
5692       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5693   SDValue VAddr;
5694   if (!UseNSA)
5695     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5696 
5697   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5698   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5699   unsigned CtrlIdx; // Index of texfailctrl argument
5700   SDValue Unorm;
5701   if (!BaseOpcode->Sampler) {
5702     Unorm = True;
5703     CtrlIdx = AddrIdx + NumVAddrs + 1;
5704   } else {
5705     auto UnormConst =
5706         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5707 
5708     Unorm = UnormConst->getZExtValue() ? True : False;
5709     CtrlIdx = AddrIdx + NumVAddrs + 3;
5710   }
5711 
5712   SDValue TFE;
5713   SDValue LWE;
5714   SDValue TexFail = Op.getOperand(CtrlIdx);
5715   bool IsTexFail = false;
5716   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5717     return Op;
5718 
5719   if (IsTexFail) {
5720     if (!DMaskLanes) {
5721       // Expecting to get an error flag since TFC is on - and dmask is 0
5722       // Force dmask to be at least 1 otherwise the instruction will fail
5723       DMask = 0x1;
5724       DMaskLanes = 1;
5725       NumVDataDwords = 1;
5726     }
5727     NumVDataDwords += 1;
5728     AdjustRetType = true;
5729   }
5730 
5731   // Has something earlier tagged that the return type needs adjusting
5732   // This happens if the instruction is a load or has set TexFailCtrl flags
5733   if (AdjustRetType) {
5734     // NumVDataDwords reflects the true number of dwords required in the return type
5735     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5736       // This is a no-op load. This can be eliminated
5737       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5738       if (isa<MemSDNode>(Op))
5739         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5740       return Undef;
5741     }
5742 
5743     EVT NewVT = NumVDataDwords > 1 ?
5744                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
5745                 : MVT::i32;
5746 
5747     ResultTypes[0] = NewVT;
5748     if (ResultTypes.size() == 3) {
5749       // Original result was aggregate type used for TexFailCtrl results
5750       // The actual instruction returns as a vector type which has now been
5751       // created. Remove the aggregate result.
5752       ResultTypes.erase(&ResultTypes[1]);
5753     }
5754   }
5755 
5756   SDValue GLC;
5757   SDValue SLC;
5758   SDValue DLC;
5759   if (BaseOpcode->Atomic) {
5760     GLC = True; // TODO no-return optimization
5761     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5762                           IsGFX10 ? &DLC : nullptr))
5763       return Op;
5764   } else {
5765     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5766                           IsGFX10 ? &DLC : nullptr))
5767       return Op;
5768   }
5769 
5770   SmallVector<SDValue, 26> Ops;
5771   if (BaseOpcode->Store || BaseOpcode->Atomic)
5772     Ops.push_back(VData); // vdata
5773   if (UseNSA) {
5774     for (const SDValue &Addr : VAddrs)
5775       Ops.push_back(Addr);
5776   } else {
5777     Ops.push_back(VAddr);
5778   }
5779   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5780   if (BaseOpcode->Sampler)
5781     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5782   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5783   if (IsGFX10)
5784     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5785   Ops.push_back(Unorm);
5786   if (IsGFX10)
5787     Ops.push_back(DLC);
5788   Ops.push_back(GLC);
5789   Ops.push_back(SLC);
5790   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
5791                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5792   if (IsGFX10)
5793     Ops.push_back(IsA16 ? True : False);
5794   Ops.push_back(TFE);
5795   Ops.push_back(LWE);
5796   if (!IsGFX10)
5797     Ops.push_back(DimInfo->DA ? True : False);
5798   if (BaseOpcode->HasD16)
5799     Ops.push_back(IsD16 ? True : False);
5800   if (isa<MemSDNode>(Op))
5801     Ops.push_back(Op.getOperand(0)); // chain
5802 
5803   int NumVAddrDwords =
5804       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5805   int Opcode = -1;
5806 
5807   if (IsGFX10) {
5808     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5809                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5810                                           : AMDGPU::MIMGEncGfx10Default,
5811                                    NumVDataDwords, NumVAddrDwords);
5812   } else {
5813     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5814       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5815                                      NumVDataDwords, NumVAddrDwords);
5816     if (Opcode == -1)
5817       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5818                                      NumVDataDwords, NumVAddrDwords);
5819   }
5820   assert(Opcode != -1);
5821 
5822   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5823   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5824     MachineMemOperand *MemRef = MemOp->getMemOperand();
5825     DAG.setNodeMemRefs(NewNode, {MemRef});
5826   }
5827 
5828   if (BaseOpcode->AtomicX2) {
5829     SmallVector<SDValue, 1> Elt;
5830     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5831     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5832   } else if (!BaseOpcode->Store) {
5833     return constructRetValue(DAG, NewNode,
5834                              OrigResultTypes, IsTexFail,
5835                              Subtarget->hasUnpackedD16VMem(), IsD16,
5836                              DMaskLanes, NumVDataDwords, DL,
5837                              *DAG.getContext());
5838   }
5839 
5840   return SDValue(NewNode, 0);
5841 }
5842 
5843 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5844                                        SDValue Offset, SDValue CachePolicy,
5845                                        SelectionDAG &DAG) const {
5846   MachineFunction &MF = DAG.getMachineFunction();
5847 
5848   const DataLayout &DataLayout = DAG.getDataLayout();
5849   Align Alignment =
5850       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
5851 
5852   MachineMemOperand *MMO = MF.getMachineMemOperand(
5853       MachinePointerInfo(),
5854       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5855           MachineMemOperand::MOInvariant,
5856       VT.getStoreSize(), Alignment);
5857 
5858   if (!Offset->isDivergent()) {
5859     SDValue Ops[] = {
5860         Rsrc,
5861         Offset, // Offset
5862         CachePolicy
5863     };
5864 
5865     // Widen vec3 load to vec4.
5866     if (VT.isVector() && VT.getVectorNumElements() == 3) {
5867       EVT WidenedVT =
5868           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
5869       auto WidenedOp = DAG.getMemIntrinsicNode(
5870           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
5871           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
5872       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
5873                                    DAG.getVectorIdxConstant(0, DL));
5874       return Subvector;
5875     }
5876 
5877     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5878                                    DAG.getVTList(VT), Ops, VT, MMO);
5879   }
5880 
5881   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5882   // assume that the buffer is unswizzled.
5883   SmallVector<SDValue, 4> Loads;
5884   unsigned NumLoads = 1;
5885   MVT LoadVT = VT.getSimpleVT();
5886   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5887   assert((LoadVT.getScalarType() == MVT::i32 ||
5888           LoadVT.getScalarType() == MVT::f32));
5889 
5890   if (NumElts == 8 || NumElts == 16) {
5891     NumLoads = NumElts / 4;
5892     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
5893   }
5894 
5895   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5896   SDValue Ops[] = {
5897       DAG.getEntryNode(),                               // Chain
5898       Rsrc,                                             // rsrc
5899       DAG.getConstant(0, DL, MVT::i32),                 // vindex
5900       {},                                               // voffset
5901       {},                                               // soffset
5902       {},                                               // offset
5903       CachePolicy,                                      // cachepolicy
5904       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
5905   };
5906 
5907   // Use the alignment to ensure that the required offsets will fit into the
5908   // immediate offsets.
5909   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5910 
5911   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5912   for (unsigned i = 0; i < NumLoads; ++i) {
5913     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5914     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
5915                                         LoadVT, MMO, DAG));
5916   }
5917 
5918   if (NumElts == 8 || NumElts == 16)
5919     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5920 
5921   return Loads[0];
5922 }
5923 
5924 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5925                                                   SelectionDAG &DAG) const {
5926   MachineFunction &MF = DAG.getMachineFunction();
5927   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5928 
5929   EVT VT = Op.getValueType();
5930   SDLoc DL(Op);
5931   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5932 
5933   // TODO: Should this propagate fast-math-flags?
5934 
5935   switch (IntrinsicID) {
5936   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5937     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5938       return emitNonHSAIntrinsicError(DAG, DL, VT);
5939     return getPreloadedValue(DAG, *MFI, VT,
5940                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5941   }
5942   case Intrinsic::amdgcn_dispatch_ptr:
5943   case Intrinsic::amdgcn_queue_ptr: {
5944     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5945       DiagnosticInfoUnsupported BadIntrin(
5946           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5947           DL.getDebugLoc());
5948       DAG.getContext()->diagnose(BadIntrin);
5949       return DAG.getUNDEF(VT);
5950     }
5951 
5952     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5953       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5954     return getPreloadedValue(DAG, *MFI, VT, RegID);
5955   }
5956   case Intrinsic::amdgcn_implicitarg_ptr: {
5957     if (MFI->isEntryFunction())
5958       return getImplicitArgPtr(DAG, DL);
5959     return getPreloadedValue(DAG, *MFI, VT,
5960                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5961   }
5962   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5963     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
5964       // This only makes sense to call in a kernel, so just lower to null.
5965       return DAG.getConstant(0, DL, VT);
5966     }
5967 
5968     return getPreloadedValue(DAG, *MFI, VT,
5969                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5970   }
5971   case Intrinsic::amdgcn_dispatch_id: {
5972     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5973   }
5974   case Intrinsic::amdgcn_rcp:
5975     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5976   case Intrinsic::amdgcn_rsq:
5977     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5978   case Intrinsic::amdgcn_rsq_legacy:
5979     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5980       return emitRemovedIntrinsicError(DAG, DL, VT);
5981     return SDValue();
5982   case Intrinsic::amdgcn_rcp_legacy:
5983     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5984       return emitRemovedIntrinsicError(DAG, DL, VT);
5985     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5986   case Intrinsic::amdgcn_rsq_clamp: {
5987     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5988       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5989 
5990     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5991     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5992     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5993 
5994     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5995     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5996                               DAG.getConstantFP(Max, DL, VT));
5997     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5998                        DAG.getConstantFP(Min, DL, VT));
5999   }
6000   case Intrinsic::r600_read_ngroups_x:
6001     if (Subtarget->isAmdHsaOS())
6002       return emitNonHSAIntrinsicError(DAG, DL, VT);
6003 
6004     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6005                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
6006   case Intrinsic::r600_read_ngroups_y:
6007     if (Subtarget->isAmdHsaOS())
6008       return emitNonHSAIntrinsicError(DAG, DL, VT);
6009 
6010     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6011                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
6012   case Intrinsic::r600_read_ngroups_z:
6013     if (Subtarget->isAmdHsaOS())
6014       return emitNonHSAIntrinsicError(DAG, DL, VT);
6015 
6016     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6017                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
6018   case Intrinsic::r600_read_global_size_x:
6019     if (Subtarget->isAmdHsaOS())
6020       return emitNonHSAIntrinsicError(DAG, DL, VT);
6021 
6022     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6023                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
6024   case Intrinsic::r600_read_global_size_y:
6025     if (Subtarget->isAmdHsaOS())
6026       return emitNonHSAIntrinsicError(DAG, DL, VT);
6027 
6028     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6029                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
6030   case Intrinsic::r600_read_global_size_z:
6031     if (Subtarget->isAmdHsaOS())
6032       return emitNonHSAIntrinsicError(DAG, DL, VT);
6033 
6034     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6035                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
6036   case Intrinsic::r600_read_local_size_x:
6037     if (Subtarget->isAmdHsaOS())
6038       return emitNonHSAIntrinsicError(DAG, DL, VT);
6039 
6040     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6041                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6042   case Intrinsic::r600_read_local_size_y:
6043     if (Subtarget->isAmdHsaOS())
6044       return emitNonHSAIntrinsicError(DAG, DL, VT);
6045 
6046     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6047                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6048   case Intrinsic::r600_read_local_size_z:
6049     if (Subtarget->isAmdHsaOS())
6050       return emitNonHSAIntrinsicError(DAG, DL, VT);
6051 
6052     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6053                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6054   case Intrinsic::amdgcn_workgroup_id_x:
6055     return getPreloadedValue(DAG, *MFI, VT,
6056                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6057   case Intrinsic::amdgcn_workgroup_id_y:
6058     return getPreloadedValue(DAG, *MFI, VT,
6059                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6060   case Intrinsic::amdgcn_workgroup_id_z:
6061     return getPreloadedValue(DAG, *MFI, VT,
6062                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6063   case Intrinsic::amdgcn_workitem_id_x:
6064     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6065                           SDLoc(DAG.getEntryNode()),
6066                           MFI->getArgInfo().WorkItemIDX);
6067   case Intrinsic::amdgcn_workitem_id_y:
6068     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6069                           SDLoc(DAG.getEntryNode()),
6070                           MFI->getArgInfo().WorkItemIDY);
6071   case Intrinsic::amdgcn_workitem_id_z:
6072     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6073                           SDLoc(DAG.getEntryNode()),
6074                           MFI->getArgInfo().WorkItemIDZ);
6075   case Intrinsic::amdgcn_wavefrontsize:
6076     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6077                            SDLoc(Op), MVT::i32);
6078   case Intrinsic::amdgcn_s_buffer_load: {
6079     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6080     SDValue GLC;
6081     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6082     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6083                           IsGFX10 ? &DLC : nullptr))
6084       return Op;
6085     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6086                         DAG);
6087   }
6088   case Intrinsic::amdgcn_fdiv_fast:
6089     return lowerFDIV_FAST(Op, DAG);
6090   case Intrinsic::amdgcn_sin:
6091     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6092 
6093   case Intrinsic::amdgcn_cos:
6094     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6095 
6096   case Intrinsic::amdgcn_mul_u24:
6097     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6098   case Intrinsic::amdgcn_mul_i24:
6099     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6100 
6101   case Intrinsic::amdgcn_log_clamp: {
6102     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6103       return SDValue();
6104 
6105     DiagnosticInfoUnsupported BadIntrin(
6106       MF.getFunction(), "intrinsic not supported on subtarget",
6107       DL.getDebugLoc());
6108       DAG.getContext()->diagnose(BadIntrin);
6109       return DAG.getUNDEF(VT);
6110   }
6111   case Intrinsic::amdgcn_ldexp:
6112     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6113                        Op.getOperand(1), Op.getOperand(2));
6114 
6115   case Intrinsic::amdgcn_fract:
6116     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6117 
6118   case Intrinsic::amdgcn_class:
6119     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6120                        Op.getOperand(1), Op.getOperand(2));
6121   case Intrinsic::amdgcn_div_fmas:
6122     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6123                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6124                        Op.getOperand(4));
6125 
6126   case Intrinsic::amdgcn_div_fixup:
6127     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6128                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6129 
6130   case Intrinsic::amdgcn_trig_preop:
6131     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
6132                        Op.getOperand(1), Op.getOperand(2));
6133   case Intrinsic::amdgcn_div_scale: {
6134     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6135 
6136     // Translate to the operands expected by the machine instruction. The
6137     // first parameter must be the same as the first instruction.
6138     SDValue Numerator = Op.getOperand(1);
6139     SDValue Denominator = Op.getOperand(2);
6140 
6141     // Note this order is opposite of the machine instruction's operations,
6142     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6143     // intrinsic has the numerator as the first operand to match a normal
6144     // division operation.
6145 
6146     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6147 
6148     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6149                        Denominator, Numerator);
6150   }
6151   case Intrinsic::amdgcn_icmp: {
6152     // There is a Pat that handles this variant, so return it as-is.
6153     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6154         Op.getConstantOperandVal(2) == 0 &&
6155         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6156       return Op;
6157     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6158   }
6159   case Intrinsic::amdgcn_fcmp: {
6160     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6161   }
6162   case Intrinsic::amdgcn_ballot:
6163     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6164   case Intrinsic::amdgcn_fmed3:
6165     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6166                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6167   case Intrinsic::amdgcn_fdot2:
6168     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6169                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6170                        Op.getOperand(4));
6171   case Intrinsic::amdgcn_fmul_legacy:
6172     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6173                        Op.getOperand(1), Op.getOperand(2));
6174   case Intrinsic::amdgcn_sffbh:
6175     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6176   case Intrinsic::amdgcn_sbfe:
6177     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6178                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6179   case Intrinsic::amdgcn_ubfe:
6180     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6181                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6182   case Intrinsic::amdgcn_cvt_pkrtz:
6183   case Intrinsic::amdgcn_cvt_pknorm_i16:
6184   case Intrinsic::amdgcn_cvt_pknorm_u16:
6185   case Intrinsic::amdgcn_cvt_pk_i16:
6186   case Intrinsic::amdgcn_cvt_pk_u16: {
6187     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6188     EVT VT = Op.getValueType();
6189     unsigned Opcode;
6190 
6191     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6192       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6193     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6194       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6195     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6196       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6197     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6198       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6199     else
6200       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6201 
6202     if (isTypeLegal(VT))
6203       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6204 
6205     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6206                                Op.getOperand(1), Op.getOperand(2));
6207     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6208   }
6209   case Intrinsic::amdgcn_fmad_ftz:
6210     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6211                        Op.getOperand(2), Op.getOperand(3));
6212 
6213   case Intrinsic::amdgcn_if_break:
6214     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6215                                       Op->getOperand(1), Op->getOperand(2)), 0);
6216 
6217   case Intrinsic::amdgcn_groupstaticsize: {
6218     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6219     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6220       return Op;
6221 
6222     const Module *M = MF.getFunction().getParent();
6223     const GlobalValue *GV =
6224         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6225     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6226                                             SIInstrInfo::MO_ABS32_LO);
6227     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6228   }
6229   case Intrinsic::amdgcn_is_shared:
6230   case Intrinsic::amdgcn_is_private: {
6231     SDLoc SL(Op);
6232     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6233       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6234     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6235     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6236                                  Op.getOperand(1));
6237 
6238     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6239                                 DAG.getConstant(1, SL, MVT::i32));
6240     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6241   }
6242   case Intrinsic::amdgcn_alignbit:
6243     return DAG.getNode(ISD::FSHR, DL, VT,
6244                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6245   case Intrinsic::amdgcn_reloc_constant: {
6246     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6247     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6248     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6249     auto RelocSymbol = cast<GlobalVariable>(
6250         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6251     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6252                                             SIInstrInfo::MO_ABS32_LO);
6253     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6254   }
6255   default:
6256     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6257             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6258       return lowerImage(Op, ImageDimIntr, DAG);
6259 
6260     return Op;
6261   }
6262 }
6263 
6264 // This function computes an appropriate offset to pass to
6265 // MachineMemOperand::setOffset() based on the offset inputs to
6266 // an intrinsic.  If any of the offsets are non-contstant or
6267 // if VIndex is non-zero then this function returns 0.  Otherwise,
6268 // it returns the sum of VOffset, SOffset, and Offset.
6269 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6270                                       SDValue SOffset,
6271                                       SDValue Offset,
6272                                       SDValue VIndex = SDValue()) {
6273 
6274   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6275       !isa<ConstantSDNode>(Offset))
6276     return 0;
6277 
6278   if (VIndex) {
6279     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6280       return 0;
6281   }
6282 
6283   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6284          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6285          cast<ConstantSDNode>(Offset)->getSExtValue();
6286 }
6287 
6288 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6289   switch (MF.getFunction().getCallingConv()) {
6290   case CallingConv::AMDGPU_PS:
6291     return 1;
6292   case CallingConv::AMDGPU_VS:
6293     return 2;
6294   case CallingConv::AMDGPU_GS:
6295     return 3;
6296   case CallingConv::AMDGPU_HS:
6297   case CallingConv::AMDGPU_LS:
6298   case CallingConv::AMDGPU_ES:
6299     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6300   case CallingConv::AMDGPU_CS:
6301   case CallingConv::AMDGPU_KERNEL:
6302   case CallingConv::C:
6303   case CallingConv::Fast:
6304   default:
6305     // Assume other calling conventions are various compute callable functions
6306     return 0;
6307   }
6308 }
6309 
6310 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6311                                                  SelectionDAG &DAG) const {
6312   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6313   SDLoc DL(Op);
6314 
6315   switch (IntrID) {
6316   case Intrinsic::amdgcn_ds_ordered_add:
6317   case Intrinsic::amdgcn_ds_ordered_swap: {
6318     MemSDNode *M = cast<MemSDNode>(Op);
6319     SDValue Chain = M->getOperand(0);
6320     SDValue M0 = M->getOperand(2);
6321     SDValue Value = M->getOperand(3);
6322     unsigned IndexOperand = M->getConstantOperandVal(7);
6323     unsigned WaveRelease = M->getConstantOperandVal(8);
6324     unsigned WaveDone = M->getConstantOperandVal(9);
6325 
6326     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6327     IndexOperand &= ~0x3f;
6328     unsigned CountDw = 0;
6329 
6330     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6331       CountDw = (IndexOperand >> 24) & 0xf;
6332       IndexOperand &= ~(0xf << 24);
6333 
6334       if (CountDw < 1 || CountDw > 4) {
6335         report_fatal_error(
6336             "ds_ordered_count: dword count must be between 1 and 4");
6337       }
6338     }
6339 
6340     if (IndexOperand)
6341       report_fatal_error("ds_ordered_count: bad index operand");
6342 
6343     if (WaveDone && !WaveRelease)
6344       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6345 
6346     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6347     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6348     unsigned Offset0 = OrderedCountIndex << 2;
6349     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6350                        (Instruction << 4);
6351 
6352     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6353       Offset1 |= (CountDw - 1) << 6;
6354 
6355     unsigned Offset = Offset0 | (Offset1 << 8);
6356 
6357     SDValue Ops[] = {
6358       Chain,
6359       Value,
6360       DAG.getTargetConstant(Offset, DL, MVT::i16),
6361       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6362     };
6363     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6364                                    M->getVTList(), Ops, M->getMemoryVT(),
6365                                    M->getMemOperand());
6366   }
6367   case Intrinsic::amdgcn_ds_fadd: {
6368     MemSDNode *M = cast<MemSDNode>(Op);
6369     unsigned Opc;
6370     switch (IntrID) {
6371     case Intrinsic::amdgcn_ds_fadd:
6372       Opc = ISD::ATOMIC_LOAD_FADD;
6373       break;
6374     }
6375 
6376     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6377                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6378                          M->getMemOperand());
6379   }
6380   case Intrinsic::amdgcn_atomic_inc:
6381   case Intrinsic::amdgcn_atomic_dec:
6382   case Intrinsic::amdgcn_ds_fmin:
6383   case Intrinsic::amdgcn_ds_fmax: {
6384     MemSDNode *M = cast<MemSDNode>(Op);
6385     unsigned Opc;
6386     switch (IntrID) {
6387     case Intrinsic::amdgcn_atomic_inc:
6388       Opc = AMDGPUISD::ATOMIC_INC;
6389       break;
6390     case Intrinsic::amdgcn_atomic_dec:
6391       Opc = AMDGPUISD::ATOMIC_DEC;
6392       break;
6393     case Intrinsic::amdgcn_ds_fmin:
6394       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6395       break;
6396     case Intrinsic::amdgcn_ds_fmax:
6397       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6398       break;
6399     default:
6400       llvm_unreachable("Unknown intrinsic!");
6401     }
6402     SDValue Ops[] = {
6403       M->getOperand(0), // Chain
6404       M->getOperand(2), // Ptr
6405       M->getOperand(3)  // Value
6406     };
6407 
6408     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6409                                    M->getMemoryVT(), M->getMemOperand());
6410   }
6411   case Intrinsic::amdgcn_buffer_load:
6412   case Intrinsic::amdgcn_buffer_load_format: {
6413     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6414     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6415     unsigned IdxEn = 1;
6416     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6417       IdxEn = Idx->getZExtValue() != 0;
6418     SDValue Ops[] = {
6419       Op.getOperand(0), // Chain
6420       Op.getOperand(2), // rsrc
6421       Op.getOperand(3), // vindex
6422       SDValue(),        // voffset -- will be set by setBufferOffsets
6423       SDValue(),        // soffset -- will be set by setBufferOffsets
6424       SDValue(),        // offset -- will be set by setBufferOffsets
6425       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6426       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6427     };
6428 
6429     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6430     // We don't know the offset if vindex is non-zero, so clear it.
6431     if (IdxEn)
6432       Offset = 0;
6433 
6434     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6435         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6436 
6437     EVT VT = Op.getValueType();
6438     EVT IntVT = VT.changeTypeToInteger();
6439     auto *M = cast<MemSDNode>(Op);
6440     M->getMemOperand()->setOffset(Offset);
6441     EVT LoadVT = Op.getValueType();
6442 
6443     if (LoadVT.getScalarType() == MVT::f16)
6444       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6445                                  M, DAG, Ops);
6446 
6447     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6448     if (LoadVT.getScalarType() == MVT::i8 ||
6449         LoadVT.getScalarType() == MVT::i16)
6450       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6451 
6452     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6453                                M->getMemOperand(), DAG);
6454   }
6455   case Intrinsic::amdgcn_raw_buffer_load:
6456   case Intrinsic::amdgcn_raw_buffer_load_format: {
6457     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6458 
6459     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6460     SDValue Ops[] = {
6461       Op.getOperand(0), // Chain
6462       Op.getOperand(2), // rsrc
6463       DAG.getConstant(0, DL, MVT::i32), // vindex
6464       Offsets.first,    // voffset
6465       Op.getOperand(4), // soffset
6466       Offsets.second,   // offset
6467       Op.getOperand(5), // cachepolicy, swizzled buffer
6468       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6469     };
6470 
6471     auto *M = cast<MemSDNode>(Op);
6472     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6473     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6474   }
6475   case Intrinsic::amdgcn_struct_buffer_load:
6476   case Intrinsic::amdgcn_struct_buffer_load_format: {
6477     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6478 
6479     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6480     SDValue Ops[] = {
6481       Op.getOperand(0), // Chain
6482       Op.getOperand(2), // rsrc
6483       Op.getOperand(3), // vindex
6484       Offsets.first,    // voffset
6485       Op.getOperand(5), // soffset
6486       Offsets.second,   // offset
6487       Op.getOperand(6), // cachepolicy, swizzled buffer
6488       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6489     };
6490 
6491     auto *M = cast<MemSDNode>(Op);
6492     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6493                                                         Ops[2]));
6494     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6495   }
6496   case Intrinsic::amdgcn_tbuffer_load: {
6497     MemSDNode *M = cast<MemSDNode>(Op);
6498     EVT LoadVT = Op.getValueType();
6499 
6500     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6501     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6502     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6503     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6504     unsigned IdxEn = 1;
6505     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6506       IdxEn = Idx->getZExtValue() != 0;
6507     SDValue Ops[] = {
6508       Op.getOperand(0),  // Chain
6509       Op.getOperand(2),  // rsrc
6510       Op.getOperand(3),  // vindex
6511       Op.getOperand(4),  // voffset
6512       Op.getOperand(5),  // soffset
6513       Op.getOperand(6),  // offset
6514       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6515       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6516       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6517     };
6518 
6519     if (LoadVT.getScalarType() == MVT::f16)
6520       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6521                                  M, DAG, Ops);
6522     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6523                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6524                                DAG);
6525   }
6526   case Intrinsic::amdgcn_raw_tbuffer_load: {
6527     MemSDNode *M = cast<MemSDNode>(Op);
6528     EVT LoadVT = Op.getValueType();
6529     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6530 
6531     SDValue Ops[] = {
6532       Op.getOperand(0),  // Chain
6533       Op.getOperand(2),  // rsrc
6534       DAG.getConstant(0, DL, MVT::i32), // vindex
6535       Offsets.first,     // voffset
6536       Op.getOperand(4),  // soffset
6537       Offsets.second,    // offset
6538       Op.getOperand(5),  // format
6539       Op.getOperand(6),  // cachepolicy, swizzled buffer
6540       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6541     };
6542 
6543     if (LoadVT.getScalarType() == MVT::f16)
6544       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6545                                  M, DAG, Ops);
6546     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6547                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6548                                DAG);
6549   }
6550   case Intrinsic::amdgcn_struct_tbuffer_load: {
6551     MemSDNode *M = cast<MemSDNode>(Op);
6552     EVT LoadVT = Op.getValueType();
6553     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6554 
6555     SDValue Ops[] = {
6556       Op.getOperand(0),  // Chain
6557       Op.getOperand(2),  // rsrc
6558       Op.getOperand(3),  // vindex
6559       Offsets.first,     // voffset
6560       Op.getOperand(5),  // soffset
6561       Offsets.second,    // offset
6562       Op.getOperand(6),  // format
6563       Op.getOperand(7),  // cachepolicy, swizzled buffer
6564       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6565     };
6566 
6567     if (LoadVT.getScalarType() == MVT::f16)
6568       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6569                                  M, DAG, Ops);
6570     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6571                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6572                                DAG);
6573   }
6574   case Intrinsic::amdgcn_buffer_atomic_swap:
6575   case Intrinsic::amdgcn_buffer_atomic_add:
6576   case Intrinsic::amdgcn_buffer_atomic_sub:
6577   case Intrinsic::amdgcn_buffer_atomic_smin:
6578   case Intrinsic::amdgcn_buffer_atomic_umin:
6579   case Intrinsic::amdgcn_buffer_atomic_smax:
6580   case Intrinsic::amdgcn_buffer_atomic_umax:
6581   case Intrinsic::amdgcn_buffer_atomic_and:
6582   case Intrinsic::amdgcn_buffer_atomic_or:
6583   case Intrinsic::amdgcn_buffer_atomic_xor: {
6584     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6585     unsigned IdxEn = 1;
6586     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6587       IdxEn = Idx->getZExtValue() != 0;
6588     SDValue Ops[] = {
6589       Op.getOperand(0), // Chain
6590       Op.getOperand(2), // vdata
6591       Op.getOperand(3), // rsrc
6592       Op.getOperand(4), // vindex
6593       SDValue(),        // voffset -- will be set by setBufferOffsets
6594       SDValue(),        // soffset -- will be set by setBufferOffsets
6595       SDValue(),        // offset -- will be set by setBufferOffsets
6596       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6597       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6598     };
6599     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6600     // We don't know the offset if vindex is non-zero, so clear it.
6601     if (IdxEn)
6602       Offset = 0;
6603     EVT VT = Op.getValueType();
6604 
6605     auto *M = cast<MemSDNode>(Op);
6606     M->getMemOperand()->setOffset(Offset);
6607     unsigned Opcode = 0;
6608 
6609     switch (IntrID) {
6610     case Intrinsic::amdgcn_buffer_atomic_swap:
6611       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6612       break;
6613     case Intrinsic::amdgcn_buffer_atomic_add:
6614       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6615       break;
6616     case Intrinsic::amdgcn_buffer_atomic_sub:
6617       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6618       break;
6619     case Intrinsic::amdgcn_buffer_atomic_smin:
6620       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6621       break;
6622     case Intrinsic::amdgcn_buffer_atomic_umin:
6623       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6624       break;
6625     case Intrinsic::amdgcn_buffer_atomic_smax:
6626       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6627       break;
6628     case Intrinsic::amdgcn_buffer_atomic_umax:
6629       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6630       break;
6631     case Intrinsic::amdgcn_buffer_atomic_and:
6632       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6633       break;
6634     case Intrinsic::amdgcn_buffer_atomic_or:
6635       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6636       break;
6637     case Intrinsic::amdgcn_buffer_atomic_xor:
6638       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6639       break;
6640     default:
6641       llvm_unreachable("unhandled atomic opcode");
6642     }
6643 
6644     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6645                                    M->getMemOperand());
6646   }
6647   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6648   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6649   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6650   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6651   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6652   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6653   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6654   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6655   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6656   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6657   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6658   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6659     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6660     SDValue Ops[] = {
6661       Op.getOperand(0), // Chain
6662       Op.getOperand(2), // vdata
6663       Op.getOperand(3), // rsrc
6664       DAG.getConstant(0, DL, MVT::i32), // vindex
6665       Offsets.first,    // voffset
6666       Op.getOperand(5), // soffset
6667       Offsets.second,   // offset
6668       Op.getOperand(6), // cachepolicy
6669       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6670     };
6671     EVT VT = Op.getValueType();
6672 
6673     auto *M = cast<MemSDNode>(Op);
6674     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6675     unsigned Opcode = 0;
6676 
6677     switch (IntrID) {
6678     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6679       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6680       break;
6681     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6682       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6683       break;
6684     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6685       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6686       break;
6687     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6688       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6689       break;
6690     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6691       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6692       break;
6693     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6694       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6695       break;
6696     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6697       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6698       break;
6699     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6700       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6701       break;
6702     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6703       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6704       break;
6705     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6706       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6707       break;
6708     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6709       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6710       break;
6711     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6712       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6713       break;
6714     default:
6715       llvm_unreachable("unhandled atomic opcode");
6716     }
6717 
6718     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6719                                    M->getMemOperand());
6720   }
6721   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6722   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6723   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6724   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6725   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6726   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6727   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6728   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6729   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6730   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6731   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6732   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6733     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6734     SDValue Ops[] = {
6735       Op.getOperand(0), // Chain
6736       Op.getOperand(2), // vdata
6737       Op.getOperand(3), // rsrc
6738       Op.getOperand(4), // vindex
6739       Offsets.first,    // voffset
6740       Op.getOperand(6), // soffset
6741       Offsets.second,   // offset
6742       Op.getOperand(7), // cachepolicy
6743       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6744     };
6745     EVT VT = Op.getValueType();
6746 
6747     auto *M = cast<MemSDNode>(Op);
6748     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6749                                                         Ops[3]));
6750     unsigned Opcode = 0;
6751 
6752     switch (IntrID) {
6753     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6754       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6755       break;
6756     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6757       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6758       break;
6759     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6760       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6761       break;
6762     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6763       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6764       break;
6765     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6766       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6767       break;
6768     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6769       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6770       break;
6771     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6772       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6773       break;
6774     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6775       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6776       break;
6777     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6778       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6779       break;
6780     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6781       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6782       break;
6783     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6784       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6785       break;
6786     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6787       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6788       break;
6789     default:
6790       llvm_unreachable("unhandled atomic opcode");
6791     }
6792 
6793     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6794                                    M->getMemOperand());
6795   }
6796   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6797     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6798     unsigned IdxEn = 1;
6799     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6800       IdxEn = Idx->getZExtValue() != 0;
6801     SDValue Ops[] = {
6802       Op.getOperand(0), // Chain
6803       Op.getOperand(2), // src
6804       Op.getOperand(3), // cmp
6805       Op.getOperand(4), // rsrc
6806       Op.getOperand(5), // vindex
6807       SDValue(),        // voffset -- will be set by setBufferOffsets
6808       SDValue(),        // soffset -- will be set by setBufferOffsets
6809       SDValue(),        // offset -- will be set by setBufferOffsets
6810       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6811       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6812     };
6813     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6814     // We don't know the offset if vindex is non-zero, so clear it.
6815     if (IdxEn)
6816       Offset = 0;
6817     EVT VT = Op.getValueType();
6818     auto *M = cast<MemSDNode>(Op);
6819     M->getMemOperand()->setOffset(Offset);
6820 
6821     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6822                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6823   }
6824   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6825     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6826     SDValue Ops[] = {
6827       Op.getOperand(0), // Chain
6828       Op.getOperand(2), // src
6829       Op.getOperand(3), // cmp
6830       Op.getOperand(4), // rsrc
6831       DAG.getConstant(0, DL, MVT::i32), // vindex
6832       Offsets.first,    // voffset
6833       Op.getOperand(6), // soffset
6834       Offsets.second,   // offset
6835       Op.getOperand(7), // cachepolicy
6836       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6837     };
6838     EVT VT = Op.getValueType();
6839     auto *M = cast<MemSDNode>(Op);
6840     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
6841 
6842     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6843                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6844   }
6845   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6846     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6847     SDValue Ops[] = {
6848       Op.getOperand(0), // Chain
6849       Op.getOperand(2), // src
6850       Op.getOperand(3), // cmp
6851       Op.getOperand(4), // rsrc
6852       Op.getOperand(5), // vindex
6853       Offsets.first,    // voffset
6854       Op.getOperand(7), // soffset
6855       Offsets.second,   // offset
6856       Op.getOperand(8), // cachepolicy
6857       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6858     };
6859     EVT VT = Op.getValueType();
6860     auto *M = cast<MemSDNode>(Op);
6861     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
6862                                                         Ops[4]));
6863 
6864     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6865                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6866   }
6867 
6868   default:
6869     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6870             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6871       return lowerImage(Op, ImageDimIntr, DAG);
6872 
6873     return SDValue();
6874   }
6875 }
6876 
6877 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6878 // dwordx4 if on SI.
6879 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6880                                               SDVTList VTList,
6881                                               ArrayRef<SDValue> Ops, EVT MemVT,
6882                                               MachineMemOperand *MMO,
6883                                               SelectionDAG &DAG) const {
6884   EVT VT = VTList.VTs[0];
6885   EVT WidenedVT = VT;
6886   EVT WidenedMemVT = MemVT;
6887   if (!Subtarget->hasDwordx3LoadStores() &&
6888       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6889     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6890                                  WidenedVT.getVectorElementType(), 4);
6891     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6892                                     WidenedMemVT.getVectorElementType(), 4);
6893     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6894   }
6895 
6896   assert(VTList.NumVTs == 2);
6897   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6898 
6899   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6900                                        WidenedMemVT, MMO);
6901   if (WidenedVT != VT) {
6902     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6903                                DAG.getVectorIdxConstant(0, DL));
6904     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6905   }
6906   return NewOp;
6907 }
6908 
6909 SDValue SITargetLowering::handleD16VData(SDValue VData,
6910                                          SelectionDAG &DAG) const {
6911   EVT StoreVT = VData.getValueType();
6912 
6913   // No change for f16 and legal vector D16 types.
6914   if (!StoreVT.isVector())
6915     return VData;
6916 
6917   SDLoc DL(VData);
6918   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6919 
6920   if (Subtarget->hasUnpackedD16VMem()) {
6921     // We need to unpack the packed data to store.
6922     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6923     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6924 
6925     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6926                                         StoreVT.getVectorNumElements());
6927     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6928     return DAG.UnrollVectorOp(ZExt.getNode());
6929   }
6930 
6931   assert(isTypeLegal(StoreVT));
6932   return VData;
6933 }
6934 
6935 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6936                                               SelectionDAG &DAG) const {
6937   SDLoc DL(Op);
6938   SDValue Chain = Op.getOperand(0);
6939   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6940   MachineFunction &MF = DAG.getMachineFunction();
6941 
6942   switch (IntrinsicID) {
6943   case Intrinsic::amdgcn_exp_compr: {
6944     SDValue Src0 = Op.getOperand(4);
6945     SDValue Src1 = Op.getOperand(5);
6946     // Hack around illegal type on SI by directly selecting it.
6947     if (isTypeLegal(Src0.getValueType()))
6948       return SDValue();
6949 
6950     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6951     SDValue Undef = DAG.getUNDEF(MVT::f32);
6952     const SDValue Ops[] = {
6953       Op.getOperand(2), // tgt
6954       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
6955       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
6956       Undef, // src2
6957       Undef, // src3
6958       Op.getOperand(7), // vm
6959       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6960       Op.getOperand(3), // en
6961       Op.getOperand(0) // Chain
6962     };
6963 
6964     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
6965     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
6966   }
6967   case Intrinsic::amdgcn_s_barrier: {
6968     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6969       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6970       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6971       if (WGSize <= ST.getWavefrontSize())
6972         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6973                                           Op.getOperand(0)), 0);
6974     }
6975     return SDValue();
6976   };
6977   case Intrinsic::amdgcn_tbuffer_store: {
6978     SDValue VData = Op.getOperand(2);
6979     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6980     if (IsD16)
6981       VData = handleD16VData(VData, DAG);
6982     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6983     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6984     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6985     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6986     unsigned IdxEn = 1;
6987     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6988       IdxEn = Idx->getZExtValue() != 0;
6989     SDValue Ops[] = {
6990       Chain,
6991       VData,             // vdata
6992       Op.getOperand(3),  // rsrc
6993       Op.getOperand(4),  // vindex
6994       Op.getOperand(5),  // voffset
6995       Op.getOperand(6),  // soffset
6996       Op.getOperand(7),  // offset
6997       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6998       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6999       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7000     };
7001     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7002                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7003     MemSDNode *M = cast<MemSDNode>(Op);
7004     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7005                                    M->getMemoryVT(), M->getMemOperand());
7006   }
7007 
7008   case Intrinsic::amdgcn_struct_tbuffer_store: {
7009     SDValue VData = Op.getOperand(2);
7010     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7011     if (IsD16)
7012       VData = handleD16VData(VData, DAG);
7013     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7014     SDValue Ops[] = {
7015       Chain,
7016       VData,             // vdata
7017       Op.getOperand(3),  // rsrc
7018       Op.getOperand(4),  // vindex
7019       Offsets.first,     // voffset
7020       Op.getOperand(6),  // soffset
7021       Offsets.second,    // offset
7022       Op.getOperand(7),  // format
7023       Op.getOperand(8),  // cachepolicy, swizzled buffer
7024       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7025     };
7026     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7027                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7028     MemSDNode *M = cast<MemSDNode>(Op);
7029     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7030                                    M->getMemoryVT(), M->getMemOperand());
7031   }
7032 
7033   case Intrinsic::amdgcn_raw_tbuffer_store: {
7034     SDValue VData = Op.getOperand(2);
7035     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7036     if (IsD16)
7037       VData = handleD16VData(VData, DAG);
7038     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7039     SDValue Ops[] = {
7040       Chain,
7041       VData,             // vdata
7042       Op.getOperand(3),  // rsrc
7043       DAG.getConstant(0, DL, MVT::i32), // vindex
7044       Offsets.first,     // voffset
7045       Op.getOperand(5),  // soffset
7046       Offsets.second,    // offset
7047       Op.getOperand(6),  // format
7048       Op.getOperand(7),  // cachepolicy, swizzled buffer
7049       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7050     };
7051     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7052                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7053     MemSDNode *M = cast<MemSDNode>(Op);
7054     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7055                                    M->getMemoryVT(), M->getMemOperand());
7056   }
7057 
7058   case Intrinsic::amdgcn_buffer_store:
7059   case Intrinsic::amdgcn_buffer_store_format: {
7060     SDValue VData = Op.getOperand(2);
7061     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7062     if (IsD16)
7063       VData = handleD16VData(VData, DAG);
7064     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7065     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7066     unsigned IdxEn = 1;
7067     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7068       IdxEn = Idx->getZExtValue() != 0;
7069     SDValue Ops[] = {
7070       Chain,
7071       VData,
7072       Op.getOperand(3), // rsrc
7073       Op.getOperand(4), // vindex
7074       SDValue(), // voffset -- will be set by setBufferOffsets
7075       SDValue(), // soffset -- will be set by setBufferOffsets
7076       SDValue(), // offset -- will be set by setBufferOffsets
7077       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7078       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7079     };
7080     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7081     // We don't know the offset if vindex is non-zero, so clear it.
7082     if (IdxEn)
7083       Offset = 0;
7084     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7085                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7086     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7087     MemSDNode *M = cast<MemSDNode>(Op);
7088     M->getMemOperand()->setOffset(Offset);
7089 
7090     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7091     EVT VDataType = VData.getValueType().getScalarType();
7092     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7093       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7094 
7095     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7096                                    M->getMemoryVT(), M->getMemOperand());
7097   }
7098 
7099   case Intrinsic::amdgcn_raw_buffer_store:
7100   case Intrinsic::amdgcn_raw_buffer_store_format: {
7101     const bool IsFormat =
7102         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7103 
7104     SDValue VData = Op.getOperand(2);
7105     EVT VDataVT = VData.getValueType();
7106     EVT EltType = VDataVT.getScalarType();
7107     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7108     if (IsD16)
7109       VData = handleD16VData(VData, DAG);
7110 
7111     if (!isTypeLegal(VDataVT)) {
7112       VData =
7113           DAG.getNode(ISD::BITCAST, DL,
7114                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7115     }
7116 
7117     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7118     SDValue Ops[] = {
7119       Chain,
7120       VData,
7121       Op.getOperand(3), // rsrc
7122       DAG.getConstant(0, DL, MVT::i32), // vindex
7123       Offsets.first,    // voffset
7124       Op.getOperand(5), // soffset
7125       Offsets.second,   // offset
7126       Op.getOperand(6), // cachepolicy, swizzled buffer
7127       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7128     };
7129     unsigned Opc =
7130         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7131     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7132     MemSDNode *M = cast<MemSDNode>(Op);
7133     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7134 
7135     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7136     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7137       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7138 
7139     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7140                                    M->getMemoryVT(), M->getMemOperand());
7141   }
7142 
7143   case Intrinsic::amdgcn_struct_buffer_store:
7144   case Intrinsic::amdgcn_struct_buffer_store_format: {
7145     const bool IsFormat =
7146         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7147 
7148     SDValue VData = Op.getOperand(2);
7149     EVT VDataVT = VData.getValueType();
7150     EVT EltType = VDataVT.getScalarType();
7151     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7152 
7153     if (IsD16)
7154       VData = handleD16VData(VData, DAG);
7155 
7156     if (!isTypeLegal(VDataVT)) {
7157       VData =
7158           DAG.getNode(ISD::BITCAST, DL,
7159                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7160     }
7161 
7162     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7163     SDValue Ops[] = {
7164       Chain,
7165       VData,
7166       Op.getOperand(3), // rsrc
7167       Op.getOperand(4), // vindex
7168       Offsets.first,    // voffset
7169       Op.getOperand(6), // soffset
7170       Offsets.second,   // offset
7171       Op.getOperand(7), // cachepolicy, swizzled buffer
7172       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7173     };
7174     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7175                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7176     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7177     MemSDNode *M = cast<MemSDNode>(Op);
7178     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7179                                                         Ops[3]));
7180 
7181     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7182     EVT VDataType = VData.getValueType().getScalarType();
7183     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7184       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7185 
7186     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7187                                    M->getMemoryVT(), M->getMemOperand());
7188   }
7189 
7190   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7191     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7192     unsigned IdxEn = 1;
7193     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7194       IdxEn = Idx->getZExtValue() != 0;
7195     SDValue Ops[] = {
7196       Chain,
7197       Op.getOperand(2), // vdata
7198       Op.getOperand(3), // rsrc
7199       Op.getOperand(4), // vindex
7200       SDValue(),        // voffset -- will be set by setBufferOffsets
7201       SDValue(),        // soffset -- will be set by setBufferOffsets
7202       SDValue(),        // offset -- will be set by setBufferOffsets
7203       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7204       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7205     };
7206     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7207     // We don't know the offset if vindex is non-zero, so clear it.
7208     if (IdxEn)
7209       Offset = 0;
7210     EVT VT = Op.getOperand(2).getValueType();
7211 
7212     auto *M = cast<MemSDNode>(Op);
7213     M->getMemOperand()->setOffset(Offset);
7214     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7215                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7216 
7217     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7218                                    M->getMemOperand());
7219   }
7220 
7221   case Intrinsic::amdgcn_global_atomic_fadd: {
7222     SDValue Ops[] = {
7223       Chain,
7224       Op.getOperand(2), // ptr
7225       Op.getOperand(3)  // vdata
7226     };
7227     EVT VT = Op.getOperand(3).getValueType();
7228 
7229     auto *M = cast<MemSDNode>(Op);
7230     if (VT.isVector()) {
7231       return DAG.getMemIntrinsicNode(
7232         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7233         M->getMemOperand());
7234     }
7235 
7236     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7237                          DAG.getVTList(VT, MVT::Other), Ops,
7238                          M->getMemOperand()).getValue(1);
7239   }
7240   case Intrinsic::amdgcn_end_cf:
7241     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7242                                       Op->getOperand(2), Chain), 0);
7243 
7244   default: {
7245     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7246             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7247       return lowerImage(Op, ImageDimIntr, DAG);
7248 
7249     return Op;
7250   }
7251   }
7252 }
7253 
7254 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7255 // offset (the offset that is included in bounds checking and swizzling, to be
7256 // split between the instruction's voffset and immoffset fields) and soffset
7257 // (the offset that is excluded from bounds checking and swizzling, to go in
7258 // the instruction's soffset field).  This function takes the first kind of
7259 // offset and figures out how to split it between voffset and immoffset.
7260 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7261     SDValue Offset, SelectionDAG &DAG) const {
7262   SDLoc DL(Offset);
7263   const unsigned MaxImm = 4095;
7264   SDValue N0 = Offset;
7265   ConstantSDNode *C1 = nullptr;
7266 
7267   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7268     N0 = SDValue();
7269   else if (DAG.isBaseWithConstantOffset(N0)) {
7270     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7271     N0 = N0.getOperand(0);
7272   }
7273 
7274   if (C1) {
7275     unsigned ImmOffset = C1->getZExtValue();
7276     // If the immediate value is too big for the immoffset field, put the value
7277     // and -4096 into the immoffset field so that the value that is copied/added
7278     // for the voffset field is a multiple of 4096, and it stands more chance
7279     // of being CSEd with the copy/add for another similar load/store.
7280     // However, do not do that rounding down to a multiple of 4096 if that is a
7281     // negative number, as it appears to be illegal to have a negative offset
7282     // in the vgpr, even if adding the immediate offset makes it positive.
7283     unsigned Overflow = ImmOffset & ~MaxImm;
7284     ImmOffset -= Overflow;
7285     if ((int32_t)Overflow < 0) {
7286       Overflow += ImmOffset;
7287       ImmOffset = 0;
7288     }
7289     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7290     if (Overflow) {
7291       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7292       if (!N0)
7293         N0 = OverflowVal;
7294       else {
7295         SDValue Ops[] = { N0, OverflowVal };
7296         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7297       }
7298     }
7299   }
7300   if (!N0)
7301     N0 = DAG.getConstant(0, DL, MVT::i32);
7302   if (!C1)
7303     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7304   return {N0, SDValue(C1, 0)};
7305 }
7306 
7307 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7308 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7309 // pointed to by Offsets.
7310 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7311                                         SelectionDAG &DAG, SDValue *Offsets,
7312                                         unsigned Align) const {
7313   SDLoc DL(CombinedOffset);
7314   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7315     uint32_t Imm = C->getZExtValue();
7316     uint32_t SOffset, ImmOffset;
7317     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7318       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7319       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7320       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7321       return SOffset + ImmOffset;
7322     }
7323   }
7324   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7325     SDValue N0 = CombinedOffset.getOperand(0);
7326     SDValue N1 = CombinedOffset.getOperand(1);
7327     uint32_t SOffset, ImmOffset;
7328     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7329     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7330                                                 Subtarget, Align)) {
7331       Offsets[0] = N0;
7332       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7333       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7334       return 0;
7335     }
7336   }
7337   Offsets[0] = CombinedOffset;
7338   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7339   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7340   return 0;
7341 }
7342 
7343 // Handle 8 bit and 16 bit buffer loads
7344 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7345                                                      EVT LoadVT, SDLoc DL,
7346                                                      ArrayRef<SDValue> Ops,
7347                                                      MemSDNode *M) const {
7348   EVT IntVT = LoadVT.changeTypeToInteger();
7349   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7350          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7351 
7352   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7353   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7354                                                Ops, IntVT,
7355                                                M->getMemOperand());
7356   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7357   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7358 
7359   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7360 }
7361 
7362 // Handle 8 bit and 16 bit buffer stores
7363 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7364                                                       EVT VDataType, SDLoc DL,
7365                                                       SDValue Ops[],
7366                                                       MemSDNode *M) const {
7367   if (VDataType == MVT::f16)
7368     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7369 
7370   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7371   Ops[1] = BufferStoreExt;
7372   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7373                                  AMDGPUISD::BUFFER_STORE_SHORT;
7374   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7375   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7376                                      M->getMemOperand());
7377 }
7378 
7379 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7380                                  ISD::LoadExtType ExtType, SDValue Op,
7381                                  const SDLoc &SL, EVT VT) {
7382   if (VT.bitsLT(Op.getValueType()))
7383     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7384 
7385   switch (ExtType) {
7386   case ISD::SEXTLOAD:
7387     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7388   case ISD::ZEXTLOAD:
7389     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7390   case ISD::EXTLOAD:
7391     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7392   case ISD::NON_EXTLOAD:
7393     return Op;
7394   }
7395 
7396   llvm_unreachable("invalid ext type");
7397 }
7398 
7399 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7400   SelectionDAG &DAG = DCI.DAG;
7401   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7402     return SDValue();
7403 
7404   // FIXME: Constant loads should all be marked invariant.
7405   unsigned AS = Ld->getAddressSpace();
7406   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7407       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7408       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7409     return SDValue();
7410 
7411   // Don't do this early, since it may interfere with adjacent load merging for
7412   // illegal types. We can avoid losing alignment information for exotic types
7413   // pre-legalize.
7414   EVT MemVT = Ld->getMemoryVT();
7415   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7416       MemVT.getSizeInBits() >= 32)
7417     return SDValue();
7418 
7419   SDLoc SL(Ld);
7420 
7421   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7422          "unexpected vector extload");
7423 
7424   // TODO: Drop only high part of range.
7425   SDValue Ptr = Ld->getBasePtr();
7426   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7427                                 MVT::i32, SL, Ld->getChain(), Ptr,
7428                                 Ld->getOffset(),
7429                                 Ld->getPointerInfo(), MVT::i32,
7430                                 Ld->getAlignment(),
7431                                 Ld->getMemOperand()->getFlags(),
7432                                 Ld->getAAInfo(),
7433                                 nullptr); // Drop ranges
7434 
7435   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7436   if (MemVT.isFloatingPoint()) {
7437     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7438            "unexpected fp extload");
7439     TruncVT = MemVT.changeTypeToInteger();
7440   }
7441 
7442   SDValue Cvt = NewLoad;
7443   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7444     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7445                       DAG.getValueType(TruncVT));
7446   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7447              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7448     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7449   } else {
7450     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7451   }
7452 
7453   EVT VT = Ld->getValueType(0);
7454   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7455 
7456   DCI.AddToWorklist(Cvt.getNode());
7457 
7458   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7459   // the appropriate extension from the 32-bit load.
7460   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7461   DCI.AddToWorklist(Cvt.getNode());
7462 
7463   // Handle conversion back to floating point if necessary.
7464   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7465 
7466   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7467 }
7468 
7469 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7470   SDLoc DL(Op);
7471   LoadSDNode *Load = cast<LoadSDNode>(Op);
7472   ISD::LoadExtType ExtType = Load->getExtensionType();
7473   EVT MemVT = Load->getMemoryVT();
7474 
7475   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7476     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7477       return SDValue();
7478 
7479     // FIXME: Copied from PPC
7480     // First, load into 32 bits, then truncate to 1 bit.
7481 
7482     SDValue Chain = Load->getChain();
7483     SDValue BasePtr = Load->getBasePtr();
7484     MachineMemOperand *MMO = Load->getMemOperand();
7485 
7486     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7487 
7488     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7489                                    BasePtr, RealMemVT, MMO);
7490 
7491     if (!MemVT.isVector()) {
7492       SDValue Ops[] = {
7493         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7494         NewLD.getValue(1)
7495       };
7496 
7497       return DAG.getMergeValues(Ops, DL);
7498     }
7499 
7500     SmallVector<SDValue, 3> Elts;
7501     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7502       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7503                                 DAG.getConstant(I, DL, MVT::i32));
7504 
7505       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7506     }
7507 
7508     SDValue Ops[] = {
7509       DAG.getBuildVector(MemVT, DL, Elts),
7510       NewLD.getValue(1)
7511     };
7512 
7513     return DAG.getMergeValues(Ops, DL);
7514   }
7515 
7516   if (!MemVT.isVector())
7517     return SDValue();
7518 
7519   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7520          "Custom lowering for non-i32 vectors hasn't been implemented.");
7521 
7522   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7523                                       MemVT, *Load->getMemOperand())) {
7524     SDValue Ops[2];
7525     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7526     return DAG.getMergeValues(Ops, DL);
7527   }
7528 
7529   unsigned Alignment = Load->getAlignment();
7530   unsigned AS = Load->getAddressSpace();
7531   if (Subtarget->hasLDSMisalignedBug() &&
7532       AS == AMDGPUAS::FLAT_ADDRESS &&
7533       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7534     return SplitVectorLoad(Op, DAG);
7535   }
7536 
7537   MachineFunction &MF = DAG.getMachineFunction();
7538   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7539   // If there is a possibilty that flat instruction access scratch memory
7540   // then we need to use the same legalization rules we use for private.
7541   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7542       !Subtarget->hasMultiDwordFlatScratchAddressing())
7543     AS = MFI->hasFlatScratchInit() ?
7544          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7545 
7546   unsigned NumElements = MemVT.getVectorNumElements();
7547 
7548   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7549       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7550     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7551       if (MemVT.isPow2VectorType())
7552         return SDValue();
7553       if (NumElements == 3)
7554         return WidenVectorLoad(Op, DAG);
7555       return SplitVectorLoad(Op, DAG);
7556     }
7557     // Non-uniform loads will be selected to MUBUF instructions, so they
7558     // have the same legalization requirements as global and private
7559     // loads.
7560     //
7561   }
7562 
7563   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7564       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7565       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7566     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7567         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7568         Alignment >= 4 && NumElements < 32) {
7569       if (MemVT.isPow2VectorType())
7570         return SDValue();
7571       if (NumElements == 3)
7572         return WidenVectorLoad(Op, DAG);
7573       return SplitVectorLoad(Op, DAG);
7574     }
7575     // Non-uniform loads will be selected to MUBUF instructions, so they
7576     // have the same legalization requirements as global and private
7577     // loads.
7578     //
7579   }
7580   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7581       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7582       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7583       AS == AMDGPUAS::FLAT_ADDRESS) {
7584     if (NumElements > 4)
7585       return SplitVectorLoad(Op, DAG);
7586     // v3 loads not supported on SI.
7587     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7588       return WidenVectorLoad(Op, DAG);
7589     // v3 and v4 loads are supported for private and global memory.
7590     return SDValue();
7591   }
7592   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7593     // Depending on the setting of the private_element_size field in the
7594     // resource descriptor, we can only make private accesses up to a certain
7595     // size.
7596     switch (Subtarget->getMaxPrivateElementSize()) {
7597     case 4: {
7598       SDValue Ops[2];
7599       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7600       return DAG.getMergeValues(Ops, DL);
7601     }
7602     case 8:
7603       if (NumElements > 2)
7604         return SplitVectorLoad(Op, DAG);
7605       return SDValue();
7606     case 16:
7607       // Same as global/flat
7608       if (NumElements > 4)
7609         return SplitVectorLoad(Op, DAG);
7610       // v3 loads not supported on SI.
7611       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7612         return WidenVectorLoad(Op, DAG);
7613       return SDValue();
7614     default:
7615       llvm_unreachable("unsupported private_element_size");
7616     }
7617   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7618     // Use ds_read_b128 if possible.
7619     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7620         MemVT.getStoreSize() == 16)
7621       return SDValue();
7622 
7623     if (NumElements > 2)
7624       return SplitVectorLoad(Op, DAG);
7625 
7626     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7627     // address is negative, then the instruction is incorrectly treated as
7628     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7629     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7630     // load later in the SILoadStoreOptimizer.
7631     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7632         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7633         Load->getAlignment() < 8) {
7634       return SplitVectorLoad(Op, DAG);
7635     }
7636   }
7637   return SDValue();
7638 }
7639 
7640 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7641   EVT VT = Op.getValueType();
7642   assert(VT.getSizeInBits() == 64);
7643 
7644   SDLoc DL(Op);
7645   SDValue Cond = Op.getOperand(0);
7646 
7647   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7648   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7649 
7650   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7651   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7652 
7653   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7654   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7655 
7656   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7657 
7658   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7659   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7660 
7661   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7662 
7663   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7664   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7665 }
7666 
7667 // Catch division cases where we can use shortcuts with rcp and rsq
7668 // instructions.
7669 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7670                                               SelectionDAG &DAG) const {
7671   SDLoc SL(Op);
7672   SDValue LHS = Op.getOperand(0);
7673   SDValue RHS = Op.getOperand(1);
7674   EVT VT = Op.getValueType();
7675   const SDNodeFlags Flags = Op->getFlags();
7676 
7677   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7678                             Flags.hasApproximateFuncs();
7679 
7680   // Without !fpmath accuracy information, we can't do more because we don't
7681   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7682   if (!AllowInaccurateRcp)
7683     return SDValue();
7684 
7685   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7686     if (CLHS->isExactlyValue(1.0)) {
7687       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7688       // the CI documentation has a worst case error of 1 ulp.
7689       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7690       // use it as long as we aren't trying to use denormals.
7691       //
7692       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7693 
7694       // 1.0 / sqrt(x) -> rsq(x)
7695 
7696       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7697       // error seems really high at 2^29 ULP.
7698       if (RHS.getOpcode() == ISD::FSQRT)
7699         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7700 
7701       // 1.0 / x -> rcp(x)
7702       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7703     }
7704 
7705     // Same as for 1.0, but expand the sign out of the constant.
7706     if (CLHS->isExactlyValue(-1.0)) {
7707       // -1.0 / x -> rcp (fneg x)
7708       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7709       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7710     }
7711   }
7712 
7713   // Turn into multiply by the reciprocal.
7714   // x / y -> x * (1.0 / y)
7715   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7716   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7717 }
7718 
7719 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7720                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7721   if (GlueChain->getNumValues() <= 1) {
7722     return DAG.getNode(Opcode, SL, VT, A, B);
7723   }
7724 
7725   assert(GlueChain->getNumValues() == 3);
7726 
7727   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7728   switch (Opcode) {
7729   default: llvm_unreachable("no chain equivalent for opcode");
7730   case ISD::FMUL:
7731     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7732     break;
7733   }
7734 
7735   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7736                      GlueChain.getValue(2));
7737 }
7738 
7739 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7740                            EVT VT, SDValue A, SDValue B, SDValue C,
7741                            SDValue GlueChain) {
7742   if (GlueChain->getNumValues() <= 1) {
7743     return DAG.getNode(Opcode, SL, VT, A, B, C);
7744   }
7745 
7746   assert(GlueChain->getNumValues() == 3);
7747 
7748   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7749   switch (Opcode) {
7750   default: llvm_unreachable("no chain equivalent for opcode");
7751   case ISD::FMA:
7752     Opcode = AMDGPUISD::FMA_W_CHAIN;
7753     break;
7754   }
7755 
7756   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7757                      GlueChain.getValue(2));
7758 }
7759 
7760 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7761   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7762     return FastLowered;
7763 
7764   SDLoc SL(Op);
7765   SDValue Src0 = Op.getOperand(0);
7766   SDValue Src1 = Op.getOperand(1);
7767 
7768   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7769   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7770 
7771   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7772   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7773 
7774   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7775   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7776 
7777   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7778 }
7779 
7780 // Faster 2.5 ULP division that does not support denormals.
7781 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7782   SDLoc SL(Op);
7783   SDValue LHS = Op.getOperand(1);
7784   SDValue RHS = Op.getOperand(2);
7785 
7786   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7787 
7788   const APFloat K0Val(BitsToFloat(0x6f800000));
7789   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7790 
7791   const APFloat K1Val(BitsToFloat(0x2f800000));
7792   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7793 
7794   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7795 
7796   EVT SetCCVT =
7797     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7798 
7799   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7800 
7801   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7802 
7803   // TODO: Should this propagate fast-math-flags?
7804   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7805 
7806   // rcp does not support denormals.
7807   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7808 
7809   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7810 
7811   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7812 }
7813 
7814 // Returns immediate value for setting the F32 denorm mode when using the
7815 // S_DENORM_MODE instruction.
7816 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7817                                           const SDLoc &SL, const GCNSubtarget *ST) {
7818   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7819   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
7820                                 ? FP_DENORM_FLUSH_NONE
7821                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7822 
7823   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7824   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7825 }
7826 
7827 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7828   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7829     return FastLowered;
7830 
7831   SDLoc SL(Op);
7832   SDValue LHS = Op.getOperand(0);
7833   SDValue RHS = Op.getOperand(1);
7834 
7835   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7836 
7837   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7838 
7839   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7840                                           RHS, RHS, LHS);
7841   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7842                                         LHS, RHS, LHS);
7843 
7844   // Denominator is scaled to not be denormal, so using rcp is ok.
7845   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7846                                   DenominatorScaled);
7847   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7848                                      DenominatorScaled);
7849 
7850   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7851                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7852                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7853   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7854 
7855   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
7856 
7857   if (!HasFP32Denormals) {
7858     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7859 
7860     SDValue EnableDenorm;
7861     if (Subtarget->hasDenormModeInst()) {
7862       const SDValue EnableDenormValue =
7863           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7864 
7865       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7866                                  DAG.getEntryNode(), EnableDenormValue);
7867     } else {
7868       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7869                                                         SL, MVT::i32);
7870       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7871                                  DAG.getEntryNode(), EnableDenormValue,
7872                                  BitField);
7873     }
7874 
7875     SDValue Ops[3] = {
7876       NegDivScale0,
7877       EnableDenorm.getValue(0),
7878       EnableDenorm.getValue(1)
7879     };
7880 
7881     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7882   }
7883 
7884   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7885                              ApproxRcp, One, NegDivScale0);
7886 
7887   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7888                              ApproxRcp, Fma0);
7889 
7890   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7891                            Fma1, Fma1);
7892 
7893   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7894                              NumeratorScaled, Mul);
7895 
7896   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7897 
7898   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7899                              NumeratorScaled, Fma3);
7900 
7901   if (!HasFP32Denormals) {
7902     SDValue DisableDenorm;
7903     if (Subtarget->hasDenormModeInst()) {
7904       const SDValue DisableDenormValue =
7905           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7906 
7907       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7908                                   Fma4.getValue(1), DisableDenormValue,
7909                                   Fma4.getValue(2));
7910     } else {
7911       const SDValue DisableDenormValue =
7912           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7913 
7914       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7915                                   Fma4.getValue(1), DisableDenormValue,
7916                                   BitField, Fma4.getValue(2));
7917     }
7918 
7919     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7920                                       DisableDenorm, DAG.getRoot());
7921     DAG.setRoot(OutputChain);
7922   }
7923 
7924   SDValue Scale = NumeratorScaled.getValue(1);
7925   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7926                              Fma4, Fma1, Fma3, Scale);
7927 
7928   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7929 }
7930 
7931 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7932   if (DAG.getTarget().Options.UnsafeFPMath)
7933     return lowerFastUnsafeFDIV(Op, DAG);
7934 
7935   SDLoc SL(Op);
7936   SDValue X = Op.getOperand(0);
7937   SDValue Y = Op.getOperand(1);
7938 
7939   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7940 
7941   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7942 
7943   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7944 
7945   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7946 
7947   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7948 
7949   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7950 
7951   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7952 
7953   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7954 
7955   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7956 
7957   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7958   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7959 
7960   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7961                              NegDivScale0, Mul, DivScale1);
7962 
7963   SDValue Scale;
7964 
7965   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
7966     // Workaround a hardware bug on SI where the condition output from div_scale
7967     // is not usable.
7968 
7969     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7970 
7971     // Figure out if the scale to use for div_fmas.
7972     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7973     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7974     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7975     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7976 
7977     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7978     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7979 
7980     SDValue Scale0Hi
7981       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7982     SDValue Scale1Hi
7983       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7984 
7985     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7986     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7987     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7988   } else {
7989     Scale = DivScale1.getValue(1);
7990   }
7991 
7992   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7993                              Fma4, Fma3, Mul, Scale);
7994 
7995   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7996 }
7997 
7998 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7999   EVT VT = Op.getValueType();
8000 
8001   if (VT == MVT::f32)
8002     return LowerFDIV32(Op, DAG);
8003 
8004   if (VT == MVT::f64)
8005     return LowerFDIV64(Op, DAG);
8006 
8007   if (VT == MVT::f16)
8008     return LowerFDIV16(Op, DAG);
8009 
8010   llvm_unreachable("Unexpected type for fdiv");
8011 }
8012 
8013 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8014   SDLoc DL(Op);
8015   StoreSDNode *Store = cast<StoreSDNode>(Op);
8016   EVT VT = Store->getMemoryVT();
8017 
8018   if (VT == MVT::i1) {
8019     return DAG.getTruncStore(Store->getChain(), DL,
8020        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8021        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8022   }
8023 
8024   assert(VT.isVector() &&
8025          Store->getValue().getValueType().getScalarType() == MVT::i32);
8026 
8027   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8028                                       VT, *Store->getMemOperand())) {
8029     return expandUnalignedStore(Store, DAG);
8030   }
8031 
8032   unsigned AS = Store->getAddressSpace();
8033   if (Subtarget->hasLDSMisalignedBug() &&
8034       AS == AMDGPUAS::FLAT_ADDRESS &&
8035       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8036     return SplitVectorStore(Op, DAG);
8037   }
8038 
8039   MachineFunction &MF = DAG.getMachineFunction();
8040   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8041   // If there is a possibilty that flat instruction access scratch memory
8042   // then we need to use the same legalization rules we use for private.
8043   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8044       !Subtarget->hasMultiDwordFlatScratchAddressing())
8045     AS = MFI->hasFlatScratchInit() ?
8046          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8047 
8048   unsigned NumElements = VT.getVectorNumElements();
8049   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8050       AS == AMDGPUAS::FLAT_ADDRESS) {
8051     if (NumElements > 4)
8052       return SplitVectorStore(Op, DAG);
8053     // v3 stores not supported on SI.
8054     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8055       return SplitVectorStore(Op, DAG);
8056     return SDValue();
8057   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8058     switch (Subtarget->getMaxPrivateElementSize()) {
8059     case 4:
8060       return scalarizeVectorStore(Store, DAG);
8061     case 8:
8062       if (NumElements > 2)
8063         return SplitVectorStore(Op, DAG);
8064       return SDValue();
8065     case 16:
8066       if (NumElements > 4 || NumElements == 3)
8067         return SplitVectorStore(Op, DAG);
8068       return SDValue();
8069     default:
8070       llvm_unreachable("unsupported private_element_size");
8071     }
8072   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8073     // Use ds_write_b128 if possible.
8074     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8075         VT.getStoreSize() == 16 && NumElements != 3)
8076       return SDValue();
8077 
8078     if (NumElements > 2)
8079       return SplitVectorStore(Op, DAG);
8080 
8081     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8082     // address is negative, then the instruction is incorrectly treated as
8083     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8084     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8085     // store later in the SILoadStoreOptimizer.
8086     if (!Subtarget->hasUsableDSOffset() &&
8087         NumElements == 2 && VT.getStoreSize() == 8 &&
8088         Store->getAlignment() < 8) {
8089       return SplitVectorStore(Op, DAG);
8090     }
8091 
8092     return SDValue();
8093   } else {
8094     llvm_unreachable("unhandled address space");
8095   }
8096 }
8097 
8098 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8099   SDLoc DL(Op);
8100   EVT VT = Op.getValueType();
8101   SDValue Arg = Op.getOperand(0);
8102   SDValue TrigVal;
8103 
8104   // TODO: Should this propagate fast-math-flags?
8105 
8106   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
8107 
8108   if (Subtarget->hasTrigReducedRange()) {
8109     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
8110     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
8111   } else {
8112     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
8113   }
8114 
8115   switch (Op.getOpcode()) {
8116   case ISD::FCOS:
8117     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
8118   case ISD::FSIN:
8119     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
8120   default:
8121     llvm_unreachable("Wrong trig opcode");
8122   }
8123 }
8124 
8125 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8126   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8127   assert(AtomicNode->isCompareAndSwap());
8128   unsigned AS = AtomicNode->getAddressSpace();
8129 
8130   // No custom lowering required for local address space
8131   if (!isFlatGlobalAddrSpace(AS))
8132     return Op;
8133 
8134   // Non-local address space requires custom lowering for atomic compare
8135   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8136   SDLoc DL(Op);
8137   SDValue ChainIn = Op.getOperand(0);
8138   SDValue Addr = Op.getOperand(1);
8139   SDValue Old = Op.getOperand(2);
8140   SDValue New = Op.getOperand(3);
8141   EVT VT = Op.getValueType();
8142   MVT SimpleVT = VT.getSimpleVT();
8143   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8144 
8145   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8146   SDValue Ops[] = { ChainIn, Addr, NewOld };
8147 
8148   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8149                                  Ops, VT, AtomicNode->getMemOperand());
8150 }
8151 
8152 //===----------------------------------------------------------------------===//
8153 // Custom DAG optimizations
8154 //===----------------------------------------------------------------------===//
8155 
8156 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8157                                                      DAGCombinerInfo &DCI) const {
8158   EVT VT = N->getValueType(0);
8159   EVT ScalarVT = VT.getScalarType();
8160   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8161     return SDValue();
8162 
8163   SelectionDAG &DAG = DCI.DAG;
8164   SDLoc DL(N);
8165 
8166   SDValue Src = N->getOperand(0);
8167   EVT SrcVT = Src.getValueType();
8168 
8169   // TODO: We could try to match extracting the higher bytes, which would be
8170   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8171   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8172   // about in practice.
8173   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8174     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8175       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8176       DCI.AddToWorklist(Cvt.getNode());
8177 
8178       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8179       if (ScalarVT != MVT::f32) {
8180         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8181                           DAG.getTargetConstant(0, DL, MVT::i32));
8182       }
8183       return Cvt;
8184     }
8185   }
8186 
8187   return SDValue();
8188 }
8189 
8190 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8191 
8192 // This is a variant of
8193 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8194 //
8195 // The normal DAG combiner will do this, but only if the add has one use since
8196 // that would increase the number of instructions.
8197 //
8198 // This prevents us from seeing a constant offset that can be folded into a
8199 // memory instruction's addressing mode. If we know the resulting add offset of
8200 // a pointer can be folded into an addressing offset, we can replace the pointer
8201 // operand with the add of new constant offset. This eliminates one of the uses,
8202 // and may allow the remaining use to also be simplified.
8203 //
8204 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8205                                                unsigned AddrSpace,
8206                                                EVT MemVT,
8207                                                DAGCombinerInfo &DCI) const {
8208   SDValue N0 = N->getOperand(0);
8209   SDValue N1 = N->getOperand(1);
8210 
8211   // We only do this to handle cases where it's profitable when there are
8212   // multiple uses of the add, so defer to the standard combine.
8213   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8214       N0->hasOneUse())
8215     return SDValue();
8216 
8217   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8218   if (!CN1)
8219     return SDValue();
8220 
8221   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8222   if (!CAdd)
8223     return SDValue();
8224 
8225   // If the resulting offset is too large, we can't fold it into the addressing
8226   // mode offset.
8227   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8228   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8229 
8230   AddrMode AM;
8231   AM.HasBaseReg = true;
8232   AM.BaseOffs = Offset.getSExtValue();
8233   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8234     return SDValue();
8235 
8236   SelectionDAG &DAG = DCI.DAG;
8237   SDLoc SL(N);
8238   EVT VT = N->getValueType(0);
8239 
8240   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8241   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8242 
8243   SDNodeFlags Flags;
8244   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8245                           (N0.getOpcode() == ISD::OR ||
8246                            N0->getFlags().hasNoUnsignedWrap()));
8247 
8248   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8249 }
8250 
8251 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8252                                                   DAGCombinerInfo &DCI) const {
8253   SDValue Ptr = N->getBasePtr();
8254   SelectionDAG &DAG = DCI.DAG;
8255   SDLoc SL(N);
8256 
8257   // TODO: We could also do this for multiplies.
8258   if (Ptr.getOpcode() == ISD::SHL) {
8259     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8260                                           N->getMemoryVT(), DCI);
8261     if (NewPtr) {
8262       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8263 
8264       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8265       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8266     }
8267   }
8268 
8269   return SDValue();
8270 }
8271 
8272 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8273   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8274          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8275          (Opc == ISD::XOR && Val == 0);
8276 }
8277 
8278 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8279 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8280 // integer combine opportunities since most 64-bit operations are decomposed
8281 // this way.  TODO: We won't want this for SALU especially if it is an inline
8282 // immediate.
8283 SDValue SITargetLowering::splitBinaryBitConstantOp(
8284   DAGCombinerInfo &DCI,
8285   const SDLoc &SL,
8286   unsigned Opc, SDValue LHS,
8287   const ConstantSDNode *CRHS) const {
8288   uint64_t Val = CRHS->getZExtValue();
8289   uint32_t ValLo = Lo_32(Val);
8290   uint32_t ValHi = Hi_32(Val);
8291   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8292 
8293     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8294          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8295         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8296     // If we need to materialize a 64-bit immediate, it will be split up later
8297     // anyway. Avoid creating the harder to understand 64-bit immediate
8298     // materialization.
8299     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8300   }
8301 
8302   return SDValue();
8303 }
8304 
8305 // Returns true if argument is a boolean value which is not serialized into
8306 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8307 static bool isBoolSGPR(SDValue V) {
8308   if (V.getValueType() != MVT::i1)
8309     return false;
8310   switch (V.getOpcode()) {
8311   default: break;
8312   case ISD::SETCC:
8313   case ISD::AND:
8314   case ISD::OR:
8315   case ISD::XOR:
8316   case AMDGPUISD::FP_CLASS:
8317     return true;
8318   }
8319   return false;
8320 }
8321 
8322 // If a constant has all zeroes or all ones within each byte return it.
8323 // Otherwise return 0.
8324 static uint32_t getConstantPermuteMask(uint32_t C) {
8325   // 0xff for any zero byte in the mask
8326   uint32_t ZeroByteMask = 0;
8327   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8328   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8329   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8330   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8331   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8332   if ((NonZeroByteMask & C) != NonZeroByteMask)
8333     return 0; // Partial bytes selected.
8334   return C;
8335 }
8336 
8337 // Check if a node selects whole bytes from its operand 0 starting at a byte
8338 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8339 // or -1 if not succeeded.
8340 // Note byte select encoding:
8341 // value 0-3 selects corresponding source byte;
8342 // value 0xc selects zero;
8343 // value 0xff selects 0xff.
8344 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8345   assert(V.getValueSizeInBits() == 32);
8346 
8347   if (V.getNumOperands() != 2)
8348     return ~0;
8349 
8350   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8351   if (!N1)
8352     return ~0;
8353 
8354   uint32_t C = N1->getZExtValue();
8355 
8356   switch (V.getOpcode()) {
8357   default:
8358     break;
8359   case ISD::AND:
8360     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8361       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8362     }
8363     break;
8364 
8365   case ISD::OR:
8366     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8367       return (0x03020100 & ~ConstMask) | ConstMask;
8368     }
8369     break;
8370 
8371   case ISD::SHL:
8372     if (C % 8)
8373       return ~0;
8374 
8375     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8376 
8377   case ISD::SRL:
8378     if (C % 8)
8379       return ~0;
8380 
8381     return uint32_t(0x0c0c0c0c03020100ull >> C);
8382   }
8383 
8384   return ~0;
8385 }
8386 
8387 SDValue SITargetLowering::performAndCombine(SDNode *N,
8388                                             DAGCombinerInfo &DCI) const {
8389   if (DCI.isBeforeLegalize())
8390     return SDValue();
8391 
8392   SelectionDAG &DAG = DCI.DAG;
8393   EVT VT = N->getValueType(0);
8394   SDValue LHS = N->getOperand(0);
8395   SDValue RHS = N->getOperand(1);
8396 
8397 
8398   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8399   if (VT == MVT::i64 && CRHS) {
8400     if (SDValue Split
8401         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8402       return Split;
8403   }
8404 
8405   if (CRHS && VT == MVT::i32) {
8406     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8407     // nb = number of trailing zeroes in mask
8408     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8409     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8410     uint64_t Mask = CRHS->getZExtValue();
8411     unsigned Bits = countPopulation(Mask);
8412     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8413         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8414       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8415         unsigned Shift = CShift->getZExtValue();
8416         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8417         unsigned Offset = NB + Shift;
8418         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8419           SDLoc SL(N);
8420           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8421                                     LHS->getOperand(0),
8422                                     DAG.getConstant(Offset, SL, MVT::i32),
8423                                     DAG.getConstant(Bits, SL, MVT::i32));
8424           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8425           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8426                                     DAG.getValueType(NarrowVT));
8427           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8428                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8429           return Shl;
8430         }
8431       }
8432     }
8433 
8434     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8435     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8436         isa<ConstantSDNode>(LHS.getOperand(2))) {
8437       uint32_t Sel = getConstantPermuteMask(Mask);
8438       if (!Sel)
8439         return SDValue();
8440 
8441       // Select 0xc for all zero bytes
8442       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8443       SDLoc DL(N);
8444       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8445                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8446     }
8447   }
8448 
8449   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8450   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8451   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8452     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8453     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8454 
8455     SDValue X = LHS.getOperand(0);
8456     SDValue Y = RHS.getOperand(0);
8457     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8458       return SDValue();
8459 
8460     if (LCC == ISD::SETO) {
8461       if (X != LHS.getOperand(1))
8462         return SDValue();
8463 
8464       if (RCC == ISD::SETUNE) {
8465         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8466         if (!C1 || !C1->isInfinity() || C1->isNegative())
8467           return SDValue();
8468 
8469         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8470                               SIInstrFlags::N_SUBNORMAL |
8471                               SIInstrFlags::N_ZERO |
8472                               SIInstrFlags::P_ZERO |
8473                               SIInstrFlags::P_SUBNORMAL |
8474                               SIInstrFlags::P_NORMAL;
8475 
8476         static_assert(((~(SIInstrFlags::S_NAN |
8477                           SIInstrFlags::Q_NAN |
8478                           SIInstrFlags::N_INFINITY |
8479                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8480                       "mask not equal");
8481 
8482         SDLoc DL(N);
8483         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8484                            X, DAG.getConstant(Mask, DL, MVT::i32));
8485       }
8486     }
8487   }
8488 
8489   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8490     std::swap(LHS, RHS);
8491 
8492   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8493       RHS.hasOneUse()) {
8494     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8495     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8496     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8497     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8498     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8499         (RHS.getOperand(0) == LHS.getOperand(0) &&
8500          LHS.getOperand(0) == LHS.getOperand(1))) {
8501       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8502       unsigned NewMask = LCC == ISD::SETO ?
8503         Mask->getZExtValue() & ~OrdMask :
8504         Mask->getZExtValue() & OrdMask;
8505 
8506       SDLoc DL(N);
8507       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8508                          DAG.getConstant(NewMask, DL, MVT::i32));
8509     }
8510   }
8511 
8512   if (VT == MVT::i32 &&
8513       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8514     // and x, (sext cc from i1) => select cc, x, 0
8515     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8516       std::swap(LHS, RHS);
8517     if (isBoolSGPR(RHS.getOperand(0)))
8518       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8519                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8520   }
8521 
8522   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8523   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8524   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8525       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8526     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8527     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8528     if (LHSMask != ~0u && RHSMask != ~0u) {
8529       // Canonicalize the expression in an attempt to have fewer unique masks
8530       // and therefore fewer registers used to hold the masks.
8531       if (LHSMask > RHSMask) {
8532         std::swap(LHSMask, RHSMask);
8533         std::swap(LHS, RHS);
8534       }
8535 
8536       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8537       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8538       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8539       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8540 
8541       // Check of we need to combine values from two sources within a byte.
8542       if (!(LHSUsedLanes & RHSUsedLanes) &&
8543           // If we select high and lower word keep it for SDWA.
8544           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8545           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8546         // Each byte in each mask is either selector mask 0-3, or has higher
8547         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8548         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8549         // mask which is not 0xff wins. By anding both masks we have a correct
8550         // result except that 0x0c shall be corrected to give 0x0c only.
8551         uint32_t Mask = LHSMask & RHSMask;
8552         for (unsigned I = 0; I < 32; I += 8) {
8553           uint32_t ByteSel = 0xff << I;
8554           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8555             Mask &= (0x0c << I) & 0xffffffff;
8556         }
8557 
8558         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8559         // or 0x0c.
8560         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8561         SDLoc DL(N);
8562 
8563         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8564                            LHS.getOperand(0), RHS.getOperand(0),
8565                            DAG.getConstant(Sel, DL, MVT::i32));
8566       }
8567     }
8568   }
8569 
8570   return SDValue();
8571 }
8572 
8573 SDValue SITargetLowering::performOrCombine(SDNode *N,
8574                                            DAGCombinerInfo &DCI) const {
8575   SelectionDAG &DAG = DCI.DAG;
8576   SDValue LHS = N->getOperand(0);
8577   SDValue RHS = N->getOperand(1);
8578 
8579   EVT VT = N->getValueType(0);
8580   if (VT == MVT::i1) {
8581     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8582     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8583         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8584       SDValue Src = LHS.getOperand(0);
8585       if (Src != RHS.getOperand(0))
8586         return SDValue();
8587 
8588       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8589       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8590       if (!CLHS || !CRHS)
8591         return SDValue();
8592 
8593       // Only 10 bits are used.
8594       static const uint32_t MaxMask = 0x3ff;
8595 
8596       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8597       SDLoc DL(N);
8598       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8599                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8600     }
8601 
8602     return SDValue();
8603   }
8604 
8605   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8606   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8607       LHS.getOpcode() == AMDGPUISD::PERM &&
8608       isa<ConstantSDNode>(LHS.getOperand(2))) {
8609     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8610     if (!Sel)
8611       return SDValue();
8612 
8613     Sel |= LHS.getConstantOperandVal(2);
8614     SDLoc DL(N);
8615     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8616                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8617   }
8618 
8619   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8620   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8621   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8622       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8623     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8624     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8625     if (LHSMask != ~0u && RHSMask != ~0u) {
8626       // Canonicalize the expression in an attempt to have fewer unique masks
8627       // and therefore fewer registers used to hold the masks.
8628       if (LHSMask > RHSMask) {
8629         std::swap(LHSMask, RHSMask);
8630         std::swap(LHS, RHS);
8631       }
8632 
8633       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8634       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8635       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8636       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8637 
8638       // Check of we need to combine values from two sources within a byte.
8639       if (!(LHSUsedLanes & RHSUsedLanes) &&
8640           // If we select high and lower word keep it for SDWA.
8641           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8642           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8643         // Kill zero bytes selected by other mask. Zero value is 0xc.
8644         LHSMask &= ~RHSUsedLanes;
8645         RHSMask &= ~LHSUsedLanes;
8646         // Add 4 to each active LHS lane
8647         LHSMask |= LHSUsedLanes & 0x04040404;
8648         // Combine masks
8649         uint32_t Sel = LHSMask | RHSMask;
8650         SDLoc DL(N);
8651 
8652         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8653                            LHS.getOperand(0), RHS.getOperand(0),
8654                            DAG.getConstant(Sel, DL, MVT::i32));
8655       }
8656     }
8657   }
8658 
8659   if (VT != MVT::i64)
8660     return SDValue();
8661 
8662   // TODO: This could be a generic combine with a predicate for extracting the
8663   // high half of an integer being free.
8664 
8665   // (or i64:x, (zero_extend i32:y)) ->
8666   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8667   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8668       RHS.getOpcode() != ISD::ZERO_EXTEND)
8669     std::swap(LHS, RHS);
8670 
8671   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8672     SDValue ExtSrc = RHS.getOperand(0);
8673     EVT SrcVT = ExtSrc.getValueType();
8674     if (SrcVT == MVT::i32) {
8675       SDLoc SL(N);
8676       SDValue LowLHS, HiBits;
8677       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8678       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8679 
8680       DCI.AddToWorklist(LowOr.getNode());
8681       DCI.AddToWorklist(HiBits.getNode());
8682 
8683       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8684                                 LowOr, HiBits);
8685       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8686     }
8687   }
8688 
8689   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8690   if (CRHS) {
8691     if (SDValue Split
8692           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8693       return Split;
8694   }
8695 
8696   return SDValue();
8697 }
8698 
8699 SDValue SITargetLowering::performXorCombine(SDNode *N,
8700                                             DAGCombinerInfo &DCI) const {
8701   EVT VT = N->getValueType(0);
8702   if (VT != MVT::i64)
8703     return SDValue();
8704 
8705   SDValue LHS = N->getOperand(0);
8706   SDValue RHS = N->getOperand(1);
8707 
8708   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8709   if (CRHS) {
8710     if (SDValue Split
8711           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8712       return Split;
8713   }
8714 
8715   return SDValue();
8716 }
8717 
8718 // Instructions that will be lowered with a final instruction that zeros the
8719 // high result bits.
8720 // XXX - probably only need to list legal operations.
8721 static bool fp16SrcZerosHighBits(unsigned Opc) {
8722   switch (Opc) {
8723   case ISD::FADD:
8724   case ISD::FSUB:
8725   case ISD::FMUL:
8726   case ISD::FDIV:
8727   case ISD::FREM:
8728   case ISD::FMA:
8729   case ISD::FMAD:
8730   case ISD::FCANONICALIZE:
8731   case ISD::FP_ROUND:
8732   case ISD::UINT_TO_FP:
8733   case ISD::SINT_TO_FP:
8734   case ISD::FABS:
8735     // Fabs is lowered to a bit operation, but it's an and which will clear the
8736     // high bits anyway.
8737   case ISD::FSQRT:
8738   case ISD::FSIN:
8739   case ISD::FCOS:
8740   case ISD::FPOWI:
8741   case ISD::FPOW:
8742   case ISD::FLOG:
8743   case ISD::FLOG2:
8744   case ISD::FLOG10:
8745   case ISD::FEXP:
8746   case ISD::FEXP2:
8747   case ISD::FCEIL:
8748   case ISD::FTRUNC:
8749   case ISD::FRINT:
8750   case ISD::FNEARBYINT:
8751   case ISD::FROUND:
8752   case ISD::FFLOOR:
8753   case ISD::FMINNUM:
8754   case ISD::FMAXNUM:
8755   case AMDGPUISD::FRACT:
8756   case AMDGPUISD::CLAMP:
8757   case AMDGPUISD::COS_HW:
8758   case AMDGPUISD::SIN_HW:
8759   case AMDGPUISD::FMIN3:
8760   case AMDGPUISD::FMAX3:
8761   case AMDGPUISD::FMED3:
8762   case AMDGPUISD::FMAD_FTZ:
8763   case AMDGPUISD::RCP:
8764   case AMDGPUISD::RSQ:
8765   case AMDGPUISD::RCP_IFLAG:
8766   case AMDGPUISD::LDEXP:
8767     return true;
8768   default:
8769     // fcopysign, select and others may be lowered to 32-bit bit operations
8770     // which don't zero the high bits.
8771     return false;
8772   }
8773 }
8774 
8775 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8776                                                    DAGCombinerInfo &DCI) const {
8777   if (!Subtarget->has16BitInsts() ||
8778       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8779     return SDValue();
8780 
8781   EVT VT = N->getValueType(0);
8782   if (VT != MVT::i32)
8783     return SDValue();
8784 
8785   SDValue Src = N->getOperand(0);
8786   if (Src.getValueType() != MVT::i16)
8787     return SDValue();
8788 
8789   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8790   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8791   if (Src.getOpcode() == ISD::BITCAST) {
8792     SDValue BCSrc = Src.getOperand(0);
8793     if (BCSrc.getValueType() == MVT::f16 &&
8794         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8795       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8796   }
8797 
8798   return SDValue();
8799 }
8800 
8801 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8802                                                         DAGCombinerInfo &DCI)
8803                                                         const {
8804   SDValue Src = N->getOperand(0);
8805   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8806 
8807   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8808       VTSign->getVT() == MVT::i8) ||
8809       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8810       VTSign->getVT() == MVT::i16)) &&
8811       Src.hasOneUse()) {
8812     auto *M = cast<MemSDNode>(Src);
8813     SDValue Ops[] = {
8814       Src.getOperand(0), // Chain
8815       Src.getOperand(1), // rsrc
8816       Src.getOperand(2), // vindex
8817       Src.getOperand(3), // voffset
8818       Src.getOperand(4), // soffset
8819       Src.getOperand(5), // offset
8820       Src.getOperand(6),
8821       Src.getOperand(7)
8822     };
8823     // replace with BUFFER_LOAD_BYTE/SHORT
8824     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8825                                          Src.getOperand(0).getValueType());
8826     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8827                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8828     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8829                                                           ResList,
8830                                                           Ops, M->getMemoryVT(),
8831                                                           M->getMemOperand());
8832     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8833                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8834   }
8835   return SDValue();
8836 }
8837 
8838 SDValue SITargetLowering::performClassCombine(SDNode *N,
8839                                               DAGCombinerInfo &DCI) const {
8840   SelectionDAG &DAG = DCI.DAG;
8841   SDValue Mask = N->getOperand(1);
8842 
8843   // fp_class x, 0 -> false
8844   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8845     if (CMask->isNullValue())
8846       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8847   }
8848 
8849   if (N->getOperand(0).isUndef())
8850     return DAG.getUNDEF(MVT::i1);
8851 
8852   return SDValue();
8853 }
8854 
8855 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8856                                             DAGCombinerInfo &DCI) const {
8857   EVT VT = N->getValueType(0);
8858   SDValue N0 = N->getOperand(0);
8859 
8860   if (N0.isUndef())
8861     return N0;
8862 
8863   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8864                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8865     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8866                            N->getFlags());
8867   }
8868 
8869   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
8870     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
8871                            N0.getOperand(0), N->getFlags());
8872   }
8873 
8874   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8875 }
8876 
8877 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8878                                        unsigned MaxDepth) const {
8879   unsigned Opcode = Op.getOpcode();
8880   if (Opcode == ISD::FCANONICALIZE)
8881     return true;
8882 
8883   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8884     auto F = CFP->getValueAPF();
8885     if (F.isNaN() && F.isSignaling())
8886       return false;
8887     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
8888   }
8889 
8890   // If source is a result of another standard FP operation it is already in
8891   // canonical form.
8892   if (MaxDepth == 0)
8893     return false;
8894 
8895   switch (Opcode) {
8896   // These will flush denorms if required.
8897   case ISD::FADD:
8898   case ISD::FSUB:
8899   case ISD::FMUL:
8900   case ISD::FCEIL:
8901   case ISD::FFLOOR:
8902   case ISD::FMA:
8903   case ISD::FMAD:
8904   case ISD::FSQRT:
8905   case ISD::FDIV:
8906   case ISD::FREM:
8907   case ISD::FP_ROUND:
8908   case ISD::FP_EXTEND:
8909   case AMDGPUISD::FMUL_LEGACY:
8910   case AMDGPUISD::FMAD_FTZ:
8911   case AMDGPUISD::RCP:
8912   case AMDGPUISD::RSQ:
8913   case AMDGPUISD::RSQ_CLAMP:
8914   case AMDGPUISD::RCP_LEGACY:
8915   case AMDGPUISD::RCP_IFLAG:
8916   case AMDGPUISD::TRIG_PREOP:
8917   case AMDGPUISD::DIV_SCALE:
8918   case AMDGPUISD::DIV_FMAS:
8919   case AMDGPUISD::DIV_FIXUP:
8920   case AMDGPUISD::FRACT:
8921   case AMDGPUISD::LDEXP:
8922   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8923   case AMDGPUISD::CVT_F32_UBYTE0:
8924   case AMDGPUISD::CVT_F32_UBYTE1:
8925   case AMDGPUISD::CVT_F32_UBYTE2:
8926   case AMDGPUISD::CVT_F32_UBYTE3:
8927     return true;
8928 
8929   // It can/will be lowered or combined as a bit operation.
8930   // Need to check their input recursively to handle.
8931   case ISD::FNEG:
8932   case ISD::FABS:
8933   case ISD::FCOPYSIGN:
8934     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8935 
8936   case ISD::FSIN:
8937   case ISD::FCOS:
8938   case ISD::FSINCOS:
8939     return Op.getValueType().getScalarType() != MVT::f16;
8940 
8941   case ISD::FMINNUM:
8942   case ISD::FMAXNUM:
8943   case ISD::FMINNUM_IEEE:
8944   case ISD::FMAXNUM_IEEE:
8945   case AMDGPUISD::CLAMP:
8946   case AMDGPUISD::FMED3:
8947   case AMDGPUISD::FMAX3:
8948   case AMDGPUISD::FMIN3: {
8949     // FIXME: Shouldn't treat the generic operations different based these.
8950     // However, we aren't really required to flush the result from
8951     // minnum/maxnum..
8952 
8953     // snans will be quieted, so we only need to worry about denormals.
8954     if (Subtarget->supportsMinMaxDenormModes() ||
8955         denormalsEnabledForType(DAG, Op.getValueType()))
8956       return true;
8957 
8958     // Flushing may be required.
8959     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8960     // targets need to check their input recursively.
8961 
8962     // FIXME: Does this apply with clamp? It's implemented with max.
8963     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8964       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8965         return false;
8966     }
8967 
8968     return true;
8969   }
8970   case ISD::SELECT: {
8971     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8972            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8973   }
8974   case ISD::BUILD_VECTOR: {
8975     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8976       SDValue SrcOp = Op.getOperand(i);
8977       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8978         return false;
8979     }
8980 
8981     return true;
8982   }
8983   case ISD::EXTRACT_VECTOR_ELT:
8984   case ISD::EXTRACT_SUBVECTOR: {
8985     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8986   }
8987   case ISD::INSERT_VECTOR_ELT: {
8988     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8989            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8990   }
8991   case ISD::UNDEF:
8992     // Could be anything.
8993     return false;
8994 
8995   case ISD::BITCAST: {
8996     // Hack round the mess we make when legalizing extract_vector_elt
8997     SDValue Src = Op.getOperand(0);
8998     if (Src.getValueType() == MVT::i16 &&
8999         Src.getOpcode() == ISD::TRUNCATE) {
9000       SDValue TruncSrc = Src.getOperand(0);
9001       if (TruncSrc.getValueType() == MVT::i32 &&
9002           TruncSrc.getOpcode() == ISD::BITCAST &&
9003           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9004         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9005       }
9006     }
9007 
9008     return false;
9009   }
9010   case ISD::INTRINSIC_WO_CHAIN: {
9011     unsigned IntrinsicID
9012       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9013     // TODO: Handle more intrinsics
9014     switch (IntrinsicID) {
9015     case Intrinsic::amdgcn_cvt_pkrtz:
9016     case Intrinsic::amdgcn_cubeid:
9017     case Intrinsic::amdgcn_frexp_mant:
9018     case Intrinsic::amdgcn_fdot2:
9019     case Intrinsic::amdgcn_rcp:
9020     case Intrinsic::amdgcn_rsq:
9021     case Intrinsic::amdgcn_rsq_clamp:
9022     case Intrinsic::amdgcn_rcp_legacy:
9023     case Intrinsic::amdgcn_rsq_legacy:
9024       return true;
9025     default:
9026       break;
9027     }
9028 
9029     LLVM_FALLTHROUGH;
9030   }
9031   default:
9032     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9033            DAG.isKnownNeverSNaN(Op);
9034   }
9035 
9036   llvm_unreachable("invalid operation");
9037 }
9038 
9039 // Constant fold canonicalize.
9040 SDValue SITargetLowering::getCanonicalConstantFP(
9041   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9042   // Flush denormals to 0 if not enabled.
9043   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9044     return DAG.getConstantFP(0.0, SL, VT);
9045 
9046   if (C.isNaN()) {
9047     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9048     if (C.isSignaling()) {
9049       // Quiet a signaling NaN.
9050       // FIXME: Is this supposed to preserve payload bits?
9051       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9052     }
9053 
9054     // Make sure it is the canonical NaN bitpattern.
9055     //
9056     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9057     // immediate?
9058     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9059       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9060   }
9061 
9062   // Already canonical.
9063   return DAG.getConstantFP(C, SL, VT);
9064 }
9065 
9066 static bool vectorEltWillFoldAway(SDValue Op) {
9067   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9068 }
9069 
9070 SDValue SITargetLowering::performFCanonicalizeCombine(
9071   SDNode *N,
9072   DAGCombinerInfo &DCI) const {
9073   SelectionDAG &DAG = DCI.DAG;
9074   SDValue N0 = N->getOperand(0);
9075   EVT VT = N->getValueType(0);
9076 
9077   // fcanonicalize undef -> qnan
9078   if (N0.isUndef()) {
9079     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9080     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9081   }
9082 
9083   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9084     EVT VT = N->getValueType(0);
9085     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9086   }
9087 
9088   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9089   //                                                   (fcanonicalize k)
9090   //
9091   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9092 
9093   // TODO: This could be better with wider vectors that will be split to v2f16,
9094   // and to consider uses since there aren't that many packed operations.
9095   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9096       isTypeLegal(MVT::v2f16)) {
9097     SDLoc SL(N);
9098     SDValue NewElts[2];
9099     SDValue Lo = N0.getOperand(0);
9100     SDValue Hi = N0.getOperand(1);
9101     EVT EltVT = Lo.getValueType();
9102 
9103     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9104       for (unsigned I = 0; I != 2; ++I) {
9105         SDValue Op = N0.getOperand(I);
9106         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9107           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9108                                               CFP->getValueAPF());
9109         } else if (Op.isUndef()) {
9110           // Handled below based on what the other operand is.
9111           NewElts[I] = Op;
9112         } else {
9113           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9114         }
9115       }
9116 
9117       // If one half is undef, and one is constant, perfer a splat vector rather
9118       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9119       // cheaper to use and may be free with a packed operation.
9120       if (NewElts[0].isUndef()) {
9121         if (isa<ConstantFPSDNode>(NewElts[1]))
9122           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9123             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9124       }
9125 
9126       if (NewElts[1].isUndef()) {
9127         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9128           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9129       }
9130 
9131       return DAG.getBuildVector(VT, SL, NewElts);
9132     }
9133   }
9134 
9135   unsigned SrcOpc = N0.getOpcode();
9136 
9137   // If it's free to do so, push canonicalizes further up the source, which may
9138   // find a canonical source.
9139   //
9140   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9141   // sNaNs.
9142   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9143     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9144     if (CRHS && N0.hasOneUse()) {
9145       SDLoc SL(N);
9146       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9147                                    N0.getOperand(0));
9148       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9149       DCI.AddToWorklist(Canon0.getNode());
9150 
9151       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9152     }
9153   }
9154 
9155   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9156 }
9157 
9158 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9159   switch (Opc) {
9160   case ISD::FMAXNUM:
9161   case ISD::FMAXNUM_IEEE:
9162     return AMDGPUISD::FMAX3;
9163   case ISD::SMAX:
9164     return AMDGPUISD::SMAX3;
9165   case ISD::UMAX:
9166     return AMDGPUISD::UMAX3;
9167   case ISD::FMINNUM:
9168   case ISD::FMINNUM_IEEE:
9169     return AMDGPUISD::FMIN3;
9170   case ISD::SMIN:
9171     return AMDGPUISD::SMIN3;
9172   case ISD::UMIN:
9173     return AMDGPUISD::UMIN3;
9174   default:
9175     llvm_unreachable("Not a min/max opcode");
9176   }
9177 }
9178 
9179 SDValue SITargetLowering::performIntMed3ImmCombine(
9180   SelectionDAG &DAG, const SDLoc &SL,
9181   SDValue Op0, SDValue Op1, bool Signed) const {
9182   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9183   if (!K1)
9184     return SDValue();
9185 
9186   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9187   if (!K0)
9188     return SDValue();
9189 
9190   if (Signed) {
9191     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9192       return SDValue();
9193   } else {
9194     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9195       return SDValue();
9196   }
9197 
9198   EVT VT = K0->getValueType(0);
9199   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9200   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9201     return DAG.getNode(Med3Opc, SL, VT,
9202                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9203   }
9204 
9205   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9206   MVT NVT = MVT::i32;
9207   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9208 
9209   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9210   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9211   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9212 
9213   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9214   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9215 }
9216 
9217 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9218   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9219     return C;
9220 
9221   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9222     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9223       return C;
9224   }
9225 
9226   return nullptr;
9227 }
9228 
9229 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9230                                                   const SDLoc &SL,
9231                                                   SDValue Op0,
9232                                                   SDValue Op1) const {
9233   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9234   if (!K1)
9235     return SDValue();
9236 
9237   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9238   if (!K0)
9239     return SDValue();
9240 
9241   // Ordered >= (although NaN inputs should have folded away by now).
9242   if (K0->getValueAPF() > K1->getValueAPF())
9243     return SDValue();
9244 
9245   const MachineFunction &MF = DAG.getMachineFunction();
9246   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9247 
9248   // TODO: Check IEEE bit enabled?
9249   EVT VT = Op0.getValueType();
9250   if (Info->getMode().DX10Clamp) {
9251     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9252     // hardware fmed3 behavior converting to a min.
9253     // FIXME: Should this be allowing -0.0?
9254     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9255       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9256   }
9257 
9258   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9259   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9260     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9261     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9262     // then give the other result, which is different from med3 with a NaN
9263     // input.
9264     SDValue Var = Op0.getOperand(0);
9265     if (!DAG.isKnownNeverSNaN(Var))
9266       return SDValue();
9267 
9268     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9269 
9270     if ((!K0->hasOneUse() ||
9271          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9272         (!K1->hasOneUse() ||
9273          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9274       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9275                          Var, SDValue(K0, 0), SDValue(K1, 0));
9276     }
9277   }
9278 
9279   return SDValue();
9280 }
9281 
9282 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9283                                                DAGCombinerInfo &DCI) const {
9284   SelectionDAG &DAG = DCI.DAG;
9285 
9286   EVT VT = N->getValueType(0);
9287   unsigned Opc = N->getOpcode();
9288   SDValue Op0 = N->getOperand(0);
9289   SDValue Op1 = N->getOperand(1);
9290 
9291   // Only do this if the inner op has one use since this will just increases
9292   // register pressure for no benefit.
9293 
9294   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9295       !VT.isVector() &&
9296       (VT == MVT::i32 || VT == MVT::f32 ||
9297        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9298     // max(max(a, b), c) -> max3(a, b, c)
9299     // min(min(a, b), c) -> min3(a, b, c)
9300     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9301       SDLoc DL(N);
9302       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9303                          DL,
9304                          N->getValueType(0),
9305                          Op0.getOperand(0),
9306                          Op0.getOperand(1),
9307                          Op1);
9308     }
9309 
9310     // Try commuted.
9311     // max(a, max(b, c)) -> max3(a, b, c)
9312     // min(a, min(b, c)) -> min3(a, b, c)
9313     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9314       SDLoc DL(N);
9315       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9316                          DL,
9317                          N->getValueType(0),
9318                          Op0,
9319                          Op1.getOperand(0),
9320                          Op1.getOperand(1));
9321     }
9322   }
9323 
9324   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9325   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9326     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9327       return Med3;
9328   }
9329 
9330   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9331     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9332       return Med3;
9333   }
9334 
9335   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9336   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9337        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9338        (Opc == AMDGPUISD::FMIN_LEGACY &&
9339         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9340       (VT == MVT::f32 || VT == MVT::f64 ||
9341        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9342        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9343       Op0.hasOneUse()) {
9344     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9345       return Res;
9346   }
9347 
9348   return SDValue();
9349 }
9350 
9351 static bool isClampZeroToOne(SDValue A, SDValue B) {
9352   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9353     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9354       // FIXME: Should this be allowing -0.0?
9355       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9356              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9357     }
9358   }
9359 
9360   return false;
9361 }
9362 
9363 // FIXME: Should only worry about snans for version with chain.
9364 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9365                                               DAGCombinerInfo &DCI) const {
9366   EVT VT = N->getValueType(0);
9367   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9368   // NaNs. With a NaN input, the order of the operands may change the result.
9369 
9370   SelectionDAG &DAG = DCI.DAG;
9371   SDLoc SL(N);
9372 
9373   SDValue Src0 = N->getOperand(0);
9374   SDValue Src1 = N->getOperand(1);
9375   SDValue Src2 = N->getOperand(2);
9376 
9377   if (isClampZeroToOne(Src0, Src1)) {
9378     // const_a, const_b, x -> clamp is safe in all cases including signaling
9379     // nans.
9380     // FIXME: Should this be allowing -0.0?
9381     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9382   }
9383 
9384   const MachineFunction &MF = DAG.getMachineFunction();
9385   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9386 
9387   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9388   // handling no dx10-clamp?
9389   if (Info->getMode().DX10Clamp) {
9390     // If NaNs is clamped to 0, we are free to reorder the inputs.
9391 
9392     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9393       std::swap(Src0, Src1);
9394 
9395     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9396       std::swap(Src1, Src2);
9397 
9398     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9399       std::swap(Src0, Src1);
9400 
9401     if (isClampZeroToOne(Src1, Src2))
9402       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9403   }
9404 
9405   return SDValue();
9406 }
9407 
9408 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9409                                                  DAGCombinerInfo &DCI) const {
9410   SDValue Src0 = N->getOperand(0);
9411   SDValue Src1 = N->getOperand(1);
9412   if (Src0.isUndef() && Src1.isUndef())
9413     return DCI.DAG.getUNDEF(N->getValueType(0));
9414   return SDValue();
9415 }
9416 
9417 SDValue SITargetLowering::performExtractVectorEltCombine(
9418   SDNode *N, DAGCombinerInfo &DCI) const {
9419   SDValue Vec = N->getOperand(0);
9420   SelectionDAG &DAG = DCI.DAG;
9421 
9422   EVT VecVT = Vec.getValueType();
9423   EVT EltVT = VecVT.getVectorElementType();
9424 
9425   if ((Vec.getOpcode() == ISD::FNEG ||
9426        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9427     SDLoc SL(N);
9428     EVT EltVT = N->getValueType(0);
9429     SDValue Idx = N->getOperand(1);
9430     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9431                               Vec.getOperand(0), Idx);
9432     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9433   }
9434 
9435   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9436   //    =>
9437   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9438   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9439   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9440   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9441     SDLoc SL(N);
9442     EVT EltVT = N->getValueType(0);
9443     SDValue Idx = N->getOperand(1);
9444     unsigned Opc = Vec.getOpcode();
9445 
9446     switch(Opc) {
9447     default:
9448       break;
9449       // TODO: Support other binary operations.
9450     case ISD::FADD:
9451     case ISD::FSUB:
9452     case ISD::FMUL:
9453     case ISD::ADD:
9454     case ISD::UMIN:
9455     case ISD::UMAX:
9456     case ISD::SMIN:
9457     case ISD::SMAX:
9458     case ISD::FMAXNUM:
9459     case ISD::FMINNUM:
9460     case ISD::FMAXNUM_IEEE:
9461     case ISD::FMINNUM_IEEE: {
9462       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9463                                  Vec.getOperand(0), Idx);
9464       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9465                                  Vec.getOperand(1), Idx);
9466 
9467       DCI.AddToWorklist(Elt0.getNode());
9468       DCI.AddToWorklist(Elt1.getNode());
9469       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9470     }
9471     }
9472   }
9473 
9474   unsigned VecSize = VecVT.getSizeInBits();
9475   unsigned EltSize = EltVT.getSizeInBits();
9476 
9477   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9478   // This elminates non-constant index and subsequent movrel or scratch access.
9479   // Sub-dword vectors of size 2 dword or less have better implementation.
9480   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9481   // instructions.
9482   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9483       !isa<ConstantSDNode>(N->getOperand(1))) {
9484     SDLoc SL(N);
9485     SDValue Idx = N->getOperand(1);
9486     SDValue V;
9487     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9488       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9489       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9490       if (I == 0)
9491         V = Elt;
9492       else
9493         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9494     }
9495     return V;
9496   }
9497 
9498   if (!DCI.isBeforeLegalize())
9499     return SDValue();
9500 
9501   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9502   // elements. This exposes more load reduction opportunities by replacing
9503   // multiple small extract_vector_elements with a single 32-bit extract.
9504   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9505   if (isa<MemSDNode>(Vec) &&
9506       EltSize <= 16 &&
9507       EltVT.isByteSized() &&
9508       VecSize > 32 &&
9509       VecSize % 32 == 0 &&
9510       Idx) {
9511     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9512 
9513     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9514     unsigned EltIdx = BitIndex / 32;
9515     unsigned LeftoverBitIdx = BitIndex % 32;
9516     SDLoc SL(N);
9517 
9518     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9519     DCI.AddToWorklist(Cast.getNode());
9520 
9521     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9522                               DAG.getConstant(EltIdx, SL, MVT::i32));
9523     DCI.AddToWorklist(Elt.getNode());
9524     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9525                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9526     DCI.AddToWorklist(Srl.getNode());
9527 
9528     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9529     DCI.AddToWorklist(Trunc.getNode());
9530     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9531   }
9532 
9533   return SDValue();
9534 }
9535 
9536 SDValue
9537 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9538                                                 DAGCombinerInfo &DCI) const {
9539   SDValue Vec = N->getOperand(0);
9540   SDValue Idx = N->getOperand(2);
9541   EVT VecVT = Vec.getValueType();
9542   EVT EltVT = VecVT.getVectorElementType();
9543   unsigned VecSize = VecVT.getSizeInBits();
9544   unsigned EltSize = EltVT.getSizeInBits();
9545 
9546   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9547   // => BUILD_VECTOR n x select (e, const-idx)
9548   // This elminates non-constant index and subsequent movrel or scratch access.
9549   // Sub-dword vectors of size 2 dword or less have better implementation.
9550   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9551   // instructions.
9552   if (isa<ConstantSDNode>(Idx) ||
9553       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9554     return SDValue();
9555 
9556   SelectionDAG &DAG = DCI.DAG;
9557   SDLoc SL(N);
9558   SDValue Ins = N->getOperand(1);
9559   EVT IdxVT = Idx.getValueType();
9560 
9561   SmallVector<SDValue, 16> Ops;
9562   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9563     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9564     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9565     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9566     Ops.push_back(V);
9567   }
9568 
9569   return DAG.getBuildVector(VecVT, SL, Ops);
9570 }
9571 
9572 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9573                                           const SDNode *N0,
9574                                           const SDNode *N1) const {
9575   EVT VT = N0->getValueType(0);
9576 
9577   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9578   // support denormals ever.
9579   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9580        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9581         getSubtarget()->hasMadF16())) &&
9582        isOperationLegal(ISD::FMAD, VT))
9583     return ISD::FMAD;
9584 
9585   const TargetOptions &Options = DAG.getTarget().Options;
9586   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9587        (N0->getFlags().hasAllowContract() &&
9588         N1->getFlags().hasAllowContract())) &&
9589       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9590     return ISD::FMA;
9591   }
9592 
9593   return 0;
9594 }
9595 
9596 // For a reassociatable opcode perform:
9597 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9598 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9599                                                SelectionDAG &DAG) const {
9600   EVT VT = N->getValueType(0);
9601   if (VT != MVT::i32 && VT != MVT::i64)
9602     return SDValue();
9603 
9604   unsigned Opc = N->getOpcode();
9605   SDValue Op0 = N->getOperand(0);
9606   SDValue Op1 = N->getOperand(1);
9607 
9608   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9609     return SDValue();
9610 
9611   if (Op0->isDivergent())
9612     std::swap(Op0, Op1);
9613 
9614   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9615     return SDValue();
9616 
9617   SDValue Op2 = Op1.getOperand(1);
9618   Op1 = Op1.getOperand(0);
9619   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9620     return SDValue();
9621 
9622   if (Op1->isDivergent())
9623     std::swap(Op1, Op2);
9624 
9625   // If either operand is constant this will conflict with
9626   // DAGCombiner::ReassociateOps().
9627   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9628       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9629     return SDValue();
9630 
9631   SDLoc SL(N);
9632   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9633   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9634 }
9635 
9636 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9637                            EVT VT,
9638                            SDValue N0, SDValue N1, SDValue N2,
9639                            bool Signed) {
9640   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9641   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9642   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9643   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9644 }
9645 
9646 SDValue SITargetLowering::performAddCombine(SDNode *N,
9647                                             DAGCombinerInfo &DCI) const {
9648   SelectionDAG &DAG = DCI.DAG;
9649   EVT VT = N->getValueType(0);
9650   SDLoc SL(N);
9651   SDValue LHS = N->getOperand(0);
9652   SDValue RHS = N->getOperand(1);
9653 
9654   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9655       && Subtarget->hasMad64_32() &&
9656       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9657       VT.getScalarSizeInBits() <= 64) {
9658     if (LHS.getOpcode() != ISD::MUL)
9659       std::swap(LHS, RHS);
9660 
9661     SDValue MulLHS = LHS.getOperand(0);
9662     SDValue MulRHS = LHS.getOperand(1);
9663     SDValue AddRHS = RHS;
9664 
9665     // TODO: Maybe restrict if SGPR inputs.
9666     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9667         numBitsUnsigned(MulRHS, DAG) <= 32) {
9668       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9669       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9670       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9671       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9672     }
9673 
9674     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9675       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9676       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9677       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9678       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9679     }
9680 
9681     return SDValue();
9682   }
9683 
9684   if (SDValue V = reassociateScalarOps(N, DAG)) {
9685     return V;
9686   }
9687 
9688   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9689     return SDValue();
9690 
9691   // add x, zext (setcc) => addcarry x, 0, setcc
9692   // add x, sext (setcc) => subcarry x, 0, setcc
9693   unsigned Opc = LHS.getOpcode();
9694   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9695       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9696     std::swap(RHS, LHS);
9697 
9698   Opc = RHS.getOpcode();
9699   switch (Opc) {
9700   default: break;
9701   case ISD::ZERO_EXTEND:
9702   case ISD::SIGN_EXTEND:
9703   case ISD::ANY_EXTEND: {
9704     auto Cond = RHS.getOperand(0);
9705     // If this won't be a real VOPC output, we would still need to insert an
9706     // extra instruction anyway.
9707     if (!isBoolSGPR(Cond))
9708       break;
9709     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9710     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9711     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9712     return DAG.getNode(Opc, SL, VTList, Args);
9713   }
9714   case ISD::ADDCARRY: {
9715     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9716     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9717     if (!C || C->getZExtValue() != 0) break;
9718     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9719     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9720   }
9721   }
9722   return SDValue();
9723 }
9724 
9725 SDValue SITargetLowering::performSubCombine(SDNode *N,
9726                                             DAGCombinerInfo &DCI) const {
9727   SelectionDAG &DAG = DCI.DAG;
9728   EVT VT = N->getValueType(0);
9729 
9730   if (VT != MVT::i32)
9731     return SDValue();
9732 
9733   SDLoc SL(N);
9734   SDValue LHS = N->getOperand(0);
9735   SDValue RHS = N->getOperand(1);
9736 
9737   // sub x, zext (setcc) => subcarry x, 0, setcc
9738   // sub x, sext (setcc) => addcarry x, 0, setcc
9739   unsigned Opc = RHS.getOpcode();
9740   switch (Opc) {
9741   default: break;
9742   case ISD::ZERO_EXTEND:
9743   case ISD::SIGN_EXTEND:
9744   case ISD::ANY_EXTEND: {
9745     auto Cond = RHS.getOperand(0);
9746     // If this won't be a real VOPC output, we would still need to insert an
9747     // extra instruction anyway.
9748     if (!isBoolSGPR(Cond))
9749       break;
9750     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9751     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9752     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
9753     return DAG.getNode(Opc, SL, VTList, Args);
9754   }
9755   }
9756 
9757   if (LHS.getOpcode() == ISD::SUBCARRY) {
9758     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9759     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9760     if (!C || !C->isNullValue())
9761       return SDValue();
9762     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9763     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9764   }
9765   return SDValue();
9766 }
9767 
9768 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9769   DAGCombinerInfo &DCI) const {
9770 
9771   if (N->getValueType(0) != MVT::i32)
9772     return SDValue();
9773 
9774   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9775   if (!C || C->getZExtValue() != 0)
9776     return SDValue();
9777 
9778   SelectionDAG &DAG = DCI.DAG;
9779   SDValue LHS = N->getOperand(0);
9780 
9781   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9782   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9783   unsigned LHSOpc = LHS.getOpcode();
9784   unsigned Opc = N->getOpcode();
9785   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9786       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9787     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9788     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9789   }
9790   return SDValue();
9791 }
9792 
9793 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9794                                              DAGCombinerInfo &DCI) const {
9795   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9796     return SDValue();
9797 
9798   SelectionDAG &DAG = DCI.DAG;
9799   EVT VT = N->getValueType(0);
9800 
9801   SDLoc SL(N);
9802   SDValue LHS = N->getOperand(0);
9803   SDValue RHS = N->getOperand(1);
9804 
9805   // These should really be instruction patterns, but writing patterns with
9806   // source modiifiers is a pain.
9807 
9808   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9809   if (LHS.getOpcode() == ISD::FADD) {
9810     SDValue A = LHS.getOperand(0);
9811     if (A == LHS.getOperand(1)) {
9812       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9813       if (FusedOp != 0) {
9814         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9815         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9816       }
9817     }
9818   }
9819 
9820   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9821   if (RHS.getOpcode() == ISD::FADD) {
9822     SDValue A = RHS.getOperand(0);
9823     if (A == RHS.getOperand(1)) {
9824       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9825       if (FusedOp != 0) {
9826         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9827         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9828       }
9829     }
9830   }
9831 
9832   return SDValue();
9833 }
9834 
9835 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9836                                              DAGCombinerInfo &DCI) const {
9837   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9838     return SDValue();
9839 
9840   SelectionDAG &DAG = DCI.DAG;
9841   SDLoc SL(N);
9842   EVT VT = N->getValueType(0);
9843   assert(!VT.isVector());
9844 
9845   // Try to get the fneg to fold into the source modifier. This undoes generic
9846   // DAG combines and folds them into the mad.
9847   //
9848   // Only do this if we are not trying to support denormals. v_mad_f32 does
9849   // not support denormals ever.
9850   SDValue LHS = N->getOperand(0);
9851   SDValue RHS = N->getOperand(1);
9852   if (LHS.getOpcode() == ISD::FADD) {
9853     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9854     SDValue A = LHS.getOperand(0);
9855     if (A == LHS.getOperand(1)) {
9856       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9857       if (FusedOp != 0){
9858         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9859         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9860 
9861         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9862       }
9863     }
9864   }
9865 
9866   if (RHS.getOpcode() == ISD::FADD) {
9867     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9868 
9869     SDValue A = RHS.getOperand(0);
9870     if (A == RHS.getOperand(1)) {
9871       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9872       if (FusedOp != 0){
9873         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9874         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9875       }
9876     }
9877   }
9878 
9879   return SDValue();
9880 }
9881 
9882 SDValue SITargetLowering::performFMACombine(SDNode *N,
9883                                             DAGCombinerInfo &DCI) const {
9884   SelectionDAG &DAG = DCI.DAG;
9885   EVT VT = N->getValueType(0);
9886   SDLoc SL(N);
9887 
9888   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9889     return SDValue();
9890 
9891   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9892   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9893   SDValue Op1 = N->getOperand(0);
9894   SDValue Op2 = N->getOperand(1);
9895   SDValue FMA = N->getOperand(2);
9896 
9897   if (FMA.getOpcode() != ISD::FMA ||
9898       Op1.getOpcode() != ISD::FP_EXTEND ||
9899       Op2.getOpcode() != ISD::FP_EXTEND)
9900     return SDValue();
9901 
9902   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9903   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9904   // is sufficient to allow generaing fdot2.
9905   const TargetOptions &Options = DAG.getTarget().Options;
9906   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9907       (N->getFlags().hasAllowContract() &&
9908        FMA->getFlags().hasAllowContract())) {
9909     Op1 = Op1.getOperand(0);
9910     Op2 = Op2.getOperand(0);
9911     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9912         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9913       return SDValue();
9914 
9915     SDValue Vec1 = Op1.getOperand(0);
9916     SDValue Idx1 = Op1.getOperand(1);
9917     SDValue Vec2 = Op2.getOperand(0);
9918 
9919     SDValue FMAOp1 = FMA.getOperand(0);
9920     SDValue FMAOp2 = FMA.getOperand(1);
9921     SDValue FMAAcc = FMA.getOperand(2);
9922 
9923     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9924         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9925       return SDValue();
9926 
9927     FMAOp1 = FMAOp1.getOperand(0);
9928     FMAOp2 = FMAOp2.getOperand(0);
9929     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9930         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9931       return SDValue();
9932 
9933     SDValue Vec3 = FMAOp1.getOperand(0);
9934     SDValue Vec4 = FMAOp2.getOperand(0);
9935     SDValue Idx2 = FMAOp1.getOperand(1);
9936 
9937     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9938         // Idx1 and Idx2 cannot be the same.
9939         Idx1 == Idx2)
9940       return SDValue();
9941 
9942     if (Vec1 == Vec2 || Vec3 == Vec4)
9943       return SDValue();
9944 
9945     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9946       return SDValue();
9947 
9948     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9949         (Vec1 == Vec4 && Vec2 == Vec3)) {
9950       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9951                          DAG.getTargetConstant(0, SL, MVT::i1));
9952     }
9953   }
9954   return SDValue();
9955 }
9956 
9957 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9958                                               DAGCombinerInfo &DCI) const {
9959   SelectionDAG &DAG = DCI.DAG;
9960   SDLoc SL(N);
9961 
9962   SDValue LHS = N->getOperand(0);
9963   SDValue RHS = N->getOperand(1);
9964   EVT VT = LHS.getValueType();
9965   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9966 
9967   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9968   if (!CRHS) {
9969     CRHS = dyn_cast<ConstantSDNode>(LHS);
9970     if (CRHS) {
9971       std::swap(LHS, RHS);
9972       CC = getSetCCSwappedOperands(CC);
9973     }
9974   }
9975 
9976   if (CRHS) {
9977     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9978         isBoolSGPR(LHS.getOperand(0))) {
9979       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9980       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9981       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9982       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9983       if ((CRHS->isAllOnesValue() &&
9984            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9985           (CRHS->isNullValue() &&
9986            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9987         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9988                            DAG.getConstant(-1, SL, MVT::i1));
9989       if ((CRHS->isAllOnesValue() &&
9990            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9991           (CRHS->isNullValue() &&
9992            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9993         return LHS.getOperand(0);
9994     }
9995 
9996     uint64_t CRHSVal = CRHS->getZExtValue();
9997     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9998         LHS.getOpcode() == ISD::SELECT &&
9999         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10000         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10001         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10002         isBoolSGPR(LHS.getOperand(0))) {
10003       // Given CT != FT:
10004       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10005       // setcc (select cc, CT, CF), CF, ne => cc
10006       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10007       // setcc (select cc, CT, CF), CT, eq => cc
10008       uint64_t CT = LHS.getConstantOperandVal(1);
10009       uint64_t CF = LHS.getConstantOperandVal(2);
10010 
10011       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10012           (CT == CRHSVal && CC == ISD::SETNE))
10013         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10014                            DAG.getConstant(-1, SL, MVT::i1));
10015       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10016           (CT == CRHSVal && CC == ISD::SETEQ))
10017         return LHS.getOperand(0);
10018     }
10019   }
10020 
10021   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10022                                            VT != MVT::f16))
10023     return SDValue();
10024 
10025   // Match isinf/isfinite pattern
10026   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10027   // (fcmp one (fabs x), inf) -> (fp_class x,
10028   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10029   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10030     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10031     if (!CRHS)
10032       return SDValue();
10033 
10034     const APFloat &APF = CRHS->getValueAPF();
10035     if (APF.isInfinity() && !APF.isNegative()) {
10036       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10037                                  SIInstrFlags::N_INFINITY;
10038       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10039                                     SIInstrFlags::P_ZERO |
10040                                     SIInstrFlags::N_NORMAL |
10041                                     SIInstrFlags::P_NORMAL |
10042                                     SIInstrFlags::N_SUBNORMAL |
10043                                     SIInstrFlags::P_SUBNORMAL;
10044       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10045       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10046                          DAG.getConstant(Mask, SL, MVT::i32));
10047     }
10048   }
10049 
10050   return SDValue();
10051 }
10052 
10053 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10054                                                      DAGCombinerInfo &DCI) const {
10055   SelectionDAG &DAG = DCI.DAG;
10056   SDLoc SL(N);
10057   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10058 
10059   SDValue Src = N->getOperand(0);
10060   SDValue Shift = N->getOperand(0);
10061 
10062   // TODO: Extend type shouldn't matter (assuming legal types).
10063   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10064     Shift = Shift.getOperand(0);
10065 
10066   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10067     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10068     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10069     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10070     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10071     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10072     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10073       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10074                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10075 
10076       unsigned ShiftOffset = 8 * Offset;
10077       if (Shift.getOpcode() == ISD::SHL)
10078         ShiftOffset -= C->getZExtValue();
10079       else
10080         ShiftOffset += C->getZExtValue();
10081 
10082       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10083         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10084                            MVT::f32, Shift);
10085       }
10086     }
10087   }
10088 
10089   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10090   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10091   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10092     // We simplified Src. If this node is not dead, visit it again so it is
10093     // folded properly.
10094     if (N->getOpcode() != ISD::DELETED_NODE)
10095       DCI.AddToWorklist(N);
10096     return SDValue(N, 0);
10097   }
10098 
10099   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10100   if (SDValue DemandedSrc =
10101           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10102     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10103 
10104   return SDValue();
10105 }
10106 
10107 SDValue SITargetLowering::performClampCombine(SDNode *N,
10108                                               DAGCombinerInfo &DCI) const {
10109   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10110   if (!CSrc)
10111     return SDValue();
10112 
10113   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10114   const APFloat &F = CSrc->getValueAPF();
10115   APFloat Zero = APFloat::getZero(F.getSemantics());
10116   if (F < Zero ||
10117       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10118     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10119   }
10120 
10121   APFloat One(F.getSemantics(), "1.0");
10122   if (F > One)
10123     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10124 
10125   return SDValue(CSrc, 0);
10126 }
10127 
10128 
10129 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10130                                             DAGCombinerInfo &DCI) const {
10131   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10132     return SDValue();
10133   switch (N->getOpcode()) {
10134   default:
10135     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10136   case ISD::ADD:
10137     return performAddCombine(N, DCI);
10138   case ISD::SUB:
10139     return performSubCombine(N, DCI);
10140   case ISD::ADDCARRY:
10141   case ISD::SUBCARRY:
10142     return performAddCarrySubCarryCombine(N, DCI);
10143   case ISD::FADD:
10144     return performFAddCombine(N, DCI);
10145   case ISD::FSUB:
10146     return performFSubCombine(N, DCI);
10147   case ISD::SETCC:
10148     return performSetCCCombine(N, DCI);
10149   case ISD::FMAXNUM:
10150   case ISD::FMINNUM:
10151   case ISD::FMAXNUM_IEEE:
10152   case ISD::FMINNUM_IEEE:
10153   case ISD::SMAX:
10154   case ISD::SMIN:
10155   case ISD::UMAX:
10156   case ISD::UMIN:
10157   case AMDGPUISD::FMIN_LEGACY:
10158   case AMDGPUISD::FMAX_LEGACY:
10159     return performMinMaxCombine(N, DCI);
10160   case ISD::FMA:
10161     return performFMACombine(N, DCI);
10162   case ISD::LOAD: {
10163     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10164       return Widended;
10165     LLVM_FALLTHROUGH;
10166   }
10167   case ISD::STORE:
10168   case ISD::ATOMIC_LOAD:
10169   case ISD::ATOMIC_STORE:
10170   case ISD::ATOMIC_CMP_SWAP:
10171   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10172   case ISD::ATOMIC_SWAP:
10173   case ISD::ATOMIC_LOAD_ADD:
10174   case ISD::ATOMIC_LOAD_SUB:
10175   case ISD::ATOMIC_LOAD_AND:
10176   case ISD::ATOMIC_LOAD_OR:
10177   case ISD::ATOMIC_LOAD_XOR:
10178   case ISD::ATOMIC_LOAD_NAND:
10179   case ISD::ATOMIC_LOAD_MIN:
10180   case ISD::ATOMIC_LOAD_MAX:
10181   case ISD::ATOMIC_LOAD_UMIN:
10182   case ISD::ATOMIC_LOAD_UMAX:
10183   case ISD::ATOMIC_LOAD_FADD:
10184   case AMDGPUISD::ATOMIC_INC:
10185   case AMDGPUISD::ATOMIC_DEC:
10186   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10187   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10188     if (DCI.isBeforeLegalize())
10189       break;
10190     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10191   case ISD::AND:
10192     return performAndCombine(N, DCI);
10193   case ISD::OR:
10194     return performOrCombine(N, DCI);
10195   case ISD::XOR:
10196     return performXorCombine(N, DCI);
10197   case ISD::ZERO_EXTEND:
10198     return performZeroExtendCombine(N, DCI);
10199   case ISD::SIGN_EXTEND_INREG:
10200     return performSignExtendInRegCombine(N , DCI);
10201   case AMDGPUISD::FP_CLASS:
10202     return performClassCombine(N, DCI);
10203   case ISD::FCANONICALIZE:
10204     return performFCanonicalizeCombine(N, DCI);
10205   case AMDGPUISD::RCP:
10206     return performRcpCombine(N, DCI);
10207   case AMDGPUISD::FRACT:
10208   case AMDGPUISD::RSQ:
10209   case AMDGPUISD::RCP_LEGACY:
10210   case AMDGPUISD::RCP_IFLAG:
10211   case AMDGPUISD::RSQ_CLAMP:
10212   case AMDGPUISD::LDEXP: {
10213     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10214     SDValue Src = N->getOperand(0);
10215     if (Src.isUndef())
10216       return Src;
10217     break;
10218   }
10219   case ISD::SINT_TO_FP:
10220   case ISD::UINT_TO_FP:
10221     return performUCharToFloatCombine(N, DCI);
10222   case AMDGPUISD::CVT_F32_UBYTE0:
10223   case AMDGPUISD::CVT_F32_UBYTE1:
10224   case AMDGPUISD::CVT_F32_UBYTE2:
10225   case AMDGPUISD::CVT_F32_UBYTE3:
10226     return performCvtF32UByteNCombine(N, DCI);
10227   case AMDGPUISD::FMED3:
10228     return performFMed3Combine(N, DCI);
10229   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10230     return performCvtPkRTZCombine(N, DCI);
10231   case AMDGPUISD::CLAMP:
10232     return performClampCombine(N, DCI);
10233   case ISD::SCALAR_TO_VECTOR: {
10234     SelectionDAG &DAG = DCI.DAG;
10235     EVT VT = N->getValueType(0);
10236 
10237     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10238     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10239       SDLoc SL(N);
10240       SDValue Src = N->getOperand(0);
10241       EVT EltVT = Src.getValueType();
10242       if (EltVT == MVT::f16)
10243         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10244 
10245       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10246       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10247     }
10248 
10249     break;
10250   }
10251   case ISD::EXTRACT_VECTOR_ELT:
10252     return performExtractVectorEltCombine(N, DCI);
10253   case ISD::INSERT_VECTOR_ELT:
10254     return performInsertVectorEltCombine(N, DCI);
10255   }
10256   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10257 }
10258 
10259 /// Helper function for adjustWritemask
10260 static unsigned SubIdx2Lane(unsigned Idx) {
10261   switch (Idx) {
10262   default: return 0;
10263   case AMDGPU::sub0: return 0;
10264   case AMDGPU::sub1: return 1;
10265   case AMDGPU::sub2: return 2;
10266   case AMDGPU::sub3: return 3;
10267   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10268   }
10269 }
10270 
10271 /// Adjust the writemask of MIMG instructions
10272 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10273                                           SelectionDAG &DAG) const {
10274   unsigned Opcode = Node->getMachineOpcode();
10275 
10276   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10277   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10278   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10279     return Node; // not implemented for D16
10280 
10281   SDNode *Users[5] = { nullptr };
10282   unsigned Lane = 0;
10283   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10284   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10285   unsigned NewDmask = 0;
10286   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10287   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10288   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10289                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10290   unsigned TFCLane = 0;
10291   bool HasChain = Node->getNumValues() > 1;
10292 
10293   if (OldDmask == 0) {
10294     // These are folded out, but on the chance it happens don't assert.
10295     return Node;
10296   }
10297 
10298   unsigned OldBitsSet = countPopulation(OldDmask);
10299   // Work out which is the TFE/LWE lane if that is enabled.
10300   if (UsesTFC) {
10301     TFCLane = OldBitsSet;
10302   }
10303 
10304   // Try to figure out the used register components
10305   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10306        I != E; ++I) {
10307 
10308     // Don't look at users of the chain.
10309     if (I.getUse().getResNo() != 0)
10310       continue;
10311 
10312     // Abort if we can't understand the usage
10313     if (!I->isMachineOpcode() ||
10314         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10315       return Node;
10316 
10317     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10318     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10319     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10320     // set, etc.
10321     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10322 
10323     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10324     if (UsesTFC && Lane == TFCLane) {
10325       Users[Lane] = *I;
10326     } else {
10327       // Set which texture component corresponds to the lane.
10328       unsigned Comp;
10329       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10330         Comp = countTrailingZeros(Dmask);
10331         Dmask &= ~(1 << Comp);
10332       }
10333 
10334       // Abort if we have more than one user per component.
10335       if (Users[Lane])
10336         return Node;
10337 
10338       Users[Lane] = *I;
10339       NewDmask |= 1 << Comp;
10340     }
10341   }
10342 
10343   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10344   bool NoChannels = !NewDmask;
10345   if (NoChannels) {
10346     if (!UsesTFC) {
10347       // No uses of the result and not using TFC. Then do nothing.
10348       return Node;
10349     }
10350     // If the original dmask has one channel - then nothing to do
10351     if (OldBitsSet == 1)
10352       return Node;
10353     // Use an arbitrary dmask - required for the instruction to work
10354     NewDmask = 1;
10355   }
10356   // Abort if there's no change
10357   if (NewDmask == OldDmask)
10358     return Node;
10359 
10360   unsigned BitsSet = countPopulation(NewDmask);
10361 
10362   // Check for TFE or LWE - increase the number of channels by one to account
10363   // for the extra return value
10364   // This will need adjustment for D16 if this is also included in
10365   // adjustWriteMask (this function) but at present D16 are excluded.
10366   unsigned NewChannels = BitsSet + UsesTFC;
10367 
10368   int NewOpcode =
10369       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10370   assert(NewOpcode != -1 &&
10371          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10372          "failed to find equivalent MIMG op");
10373 
10374   // Adjust the writemask in the node
10375   SmallVector<SDValue, 12> Ops;
10376   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10377   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10378   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10379 
10380   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10381 
10382   MVT ResultVT = NewChannels == 1 ?
10383     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10384                            NewChannels == 5 ? 8 : NewChannels);
10385   SDVTList NewVTList = HasChain ?
10386     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10387 
10388 
10389   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10390                                               NewVTList, Ops);
10391 
10392   if (HasChain) {
10393     // Update chain.
10394     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10395     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10396   }
10397 
10398   if (NewChannels == 1) {
10399     assert(Node->hasNUsesOfValue(1, 0));
10400     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10401                                       SDLoc(Node), Users[Lane]->getValueType(0),
10402                                       SDValue(NewNode, 0));
10403     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10404     return nullptr;
10405   }
10406 
10407   // Update the users of the node with the new indices
10408   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10409     SDNode *User = Users[i];
10410     if (!User) {
10411       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10412       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10413       if (i || !NoChannels)
10414         continue;
10415     } else {
10416       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10417       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10418     }
10419 
10420     switch (Idx) {
10421     default: break;
10422     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10423     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10424     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10425     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10426     }
10427   }
10428 
10429   DAG.RemoveDeadNode(Node);
10430   return nullptr;
10431 }
10432 
10433 static bool isFrameIndexOp(SDValue Op) {
10434   if (Op.getOpcode() == ISD::AssertZext)
10435     Op = Op.getOperand(0);
10436 
10437   return isa<FrameIndexSDNode>(Op);
10438 }
10439 
10440 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10441 /// with frame index operands.
10442 /// LLVM assumes that inputs are to these instructions are registers.
10443 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10444                                                         SelectionDAG &DAG) const {
10445   if (Node->getOpcode() == ISD::CopyToReg) {
10446     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10447     SDValue SrcVal = Node->getOperand(2);
10448 
10449     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10450     // to try understanding copies to physical registers.
10451     if (SrcVal.getValueType() == MVT::i1 &&
10452         Register::isPhysicalRegister(DestReg->getReg())) {
10453       SDLoc SL(Node);
10454       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10455       SDValue VReg = DAG.getRegister(
10456         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10457 
10458       SDNode *Glued = Node->getGluedNode();
10459       SDValue ToVReg
10460         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10461                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10462       SDValue ToResultReg
10463         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10464                            VReg, ToVReg.getValue(1));
10465       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10466       DAG.RemoveDeadNode(Node);
10467       return ToResultReg.getNode();
10468     }
10469   }
10470 
10471   SmallVector<SDValue, 8> Ops;
10472   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10473     if (!isFrameIndexOp(Node->getOperand(i))) {
10474       Ops.push_back(Node->getOperand(i));
10475       continue;
10476     }
10477 
10478     SDLoc DL(Node);
10479     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10480                                      Node->getOperand(i).getValueType(),
10481                                      Node->getOperand(i)), 0));
10482   }
10483 
10484   return DAG.UpdateNodeOperands(Node, Ops);
10485 }
10486 
10487 /// Fold the instructions after selecting them.
10488 /// Returns null if users were already updated.
10489 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10490                                           SelectionDAG &DAG) const {
10491   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10492   unsigned Opcode = Node->getMachineOpcode();
10493 
10494   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10495       !TII->isGather4(Opcode)) {
10496     return adjustWritemask(Node, DAG);
10497   }
10498 
10499   if (Opcode == AMDGPU::INSERT_SUBREG ||
10500       Opcode == AMDGPU::REG_SEQUENCE) {
10501     legalizeTargetIndependentNode(Node, DAG);
10502     return Node;
10503   }
10504 
10505   switch (Opcode) {
10506   case AMDGPU::V_DIV_SCALE_F32:
10507   case AMDGPU::V_DIV_SCALE_F64: {
10508     // Satisfy the operand register constraint when one of the inputs is
10509     // undefined. Ordinarily each undef value will have its own implicit_def of
10510     // a vreg, so force these to use a single register.
10511     SDValue Src0 = Node->getOperand(0);
10512     SDValue Src1 = Node->getOperand(1);
10513     SDValue Src2 = Node->getOperand(2);
10514 
10515     if ((Src0.isMachineOpcode() &&
10516          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10517         (Src0 == Src1 || Src0 == Src2))
10518       break;
10519 
10520     MVT VT = Src0.getValueType().getSimpleVT();
10521     const TargetRegisterClass *RC =
10522         getRegClassFor(VT, Src0.getNode()->isDivergent());
10523 
10524     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10525     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10526 
10527     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10528                                       UndefReg, Src0, SDValue());
10529 
10530     // src0 must be the same register as src1 or src2, even if the value is
10531     // undefined, so make sure we don't violate this constraint.
10532     if (Src0.isMachineOpcode() &&
10533         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10534       if (Src1.isMachineOpcode() &&
10535           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10536         Src0 = Src1;
10537       else if (Src2.isMachineOpcode() &&
10538                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10539         Src0 = Src2;
10540       else {
10541         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10542         Src0 = UndefReg;
10543         Src1 = UndefReg;
10544       }
10545     } else
10546       break;
10547 
10548     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10549     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10550       Ops.push_back(Node->getOperand(I));
10551 
10552     Ops.push_back(ImpDef.getValue(1));
10553     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10554   }
10555   default:
10556     break;
10557   }
10558 
10559   return Node;
10560 }
10561 
10562 /// Assign the register class depending on the number of
10563 /// bits set in the writemask
10564 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10565                                                      SDNode *Node) const {
10566   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10567 
10568   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10569 
10570   if (TII->isVOP3(MI.getOpcode())) {
10571     // Make sure constant bus requirements are respected.
10572     TII->legalizeOperandsVOP3(MRI, MI);
10573 
10574     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10575     // This saves a chain-copy of registers and better ballance register
10576     // use between vgpr and agpr as agpr tuples tend to be big.
10577     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10578       unsigned Opc = MI.getOpcode();
10579       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10580       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10581                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10582         if (I == -1)
10583           break;
10584         MachineOperand &Op = MI.getOperand(I);
10585         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10586              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10587             !Register::isVirtualRegister(Op.getReg()) ||
10588             !TRI->isAGPR(MRI, Op.getReg()))
10589           continue;
10590         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10591         if (!Src || !Src->isCopy() ||
10592             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10593           continue;
10594         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10595         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10596         // All uses of agpr64 and agpr32 can also accept vgpr except for
10597         // v_accvgpr_read, but we do not produce agpr reads during selection,
10598         // so no use checks are needed.
10599         MRI.setRegClass(Op.getReg(), NewRC);
10600       }
10601     }
10602 
10603     return;
10604   }
10605 
10606   // Replace unused atomics with the no return version.
10607   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10608   if (NoRetAtomicOp != -1) {
10609     if (!Node->hasAnyUseOfValue(0)) {
10610       MI.setDesc(TII->get(NoRetAtomicOp));
10611       MI.RemoveOperand(0);
10612       return;
10613     }
10614 
10615     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10616     // instruction, because the return type of these instructions is a vec2 of
10617     // the memory type, so it can be tied to the input operand.
10618     // This means these instructions always have a use, so we need to add a
10619     // special case to check if the atomic has only one extract_subreg use,
10620     // which itself has no uses.
10621     if ((Node->hasNUsesOfValue(1, 0) &&
10622          Node->use_begin()->isMachineOpcode() &&
10623          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10624          !Node->use_begin()->hasAnyUseOfValue(0))) {
10625       Register Def = MI.getOperand(0).getReg();
10626 
10627       // Change this into a noret atomic.
10628       MI.setDesc(TII->get(NoRetAtomicOp));
10629       MI.RemoveOperand(0);
10630 
10631       // If we only remove the def operand from the atomic instruction, the
10632       // extract_subreg will be left with a use of a vreg without a def.
10633       // So we need to insert an implicit_def to avoid machine verifier
10634       // errors.
10635       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10636               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10637     }
10638     return;
10639   }
10640 }
10641 
10642 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10643                               uint64_t Val) {
10644   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10645   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10646 }
10647 
10648 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10649                                                 const SDLoc &DL,
10650                                                 SDValue Ptr) const {
10651   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10652 
10653   // Build the half of the subregister with the constants before building the
10654   // full 128-bit register. If we are building multiple resource descriptors,
10655   // this will allow CSEing of the 2-component register.
10656   const SDValue Ops0[] = {
10657     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10658     buildSMovImm32(DAG, DL, 0),
10659     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10660     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10661     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10662   };
10663 
10664   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10665                                                 MVT::v2i32, Ops0), 0);
10666 
10667   // Combine the constants and the pointer.
10668   const SDValue Ops1[] = {
10669     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10670     Ptr,
10671     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10672     SubRegHi,
10673     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10674   };
10675 
10676   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10677 }
10678 
10679 /// Return a resource descriptor with the 'Add TID' bit enabled
10680 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10681 ///        of the resource descriptor) to create an offset, which is added to
10682 ///        the resource pointer.
10683 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10684                                            SDValue Ptr, uint32_t RsrcDword1,
10685                                            uint64_t RsrcDword2And3) const {
10686   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10687   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10688   if (RsrcDword1) {
10689     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10690                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10691                     0);
10692   }
10693 
10694   SDValue DataLo = buildSMovImm32(DAG, DL,
10695                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10696   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10697 
10698   const SDValue Ops[] = {
10699     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10700     PtrLo,
10701     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10702     PtrHi,
10703     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10704     DataLo,
10705     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10706     DataHi,
10707     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10708   };
10709 
10710   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10711 }
10712 
10713 //===----------------------------------------------------------------------===//
10714 //                         SI Inline Assembly Support
10715 //===----------------------------------------------------------------------===//
10716 
10717 std::pair<unsigned, const TargetRegisterClass *>
10718 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10719                                                StringRef Constraint,
10720                                                MVT VT) const {
10721   const TargetRegisterClass *RC = nullptr;
10722   if (Constraint.size() == 1) {
10723     const unsigned BitWidth = VT.getSizeInBits();
10724     switch (Constraint[0]) {
10725     default:
10726       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10727     case 's':
10728     case 'r':
10729       switch (BitWidth) {
10730       case 16:
10731         RC = &AMDGPU::SReg_32RegClass;
10732         break;
10733       case 64:
10734         RC = &AMDGPU::SGPR_64RegClass;
10735         break;
10736       default:
10737         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
10738         if (!RC)
10739           return std::make_pair(0U, nullptr);
10740         break;
10741       }
10742       break;
10743     case 'v':
10744       switch (BitWidth) {
10745       case 16:
10746         RC = &AMDGPU::VGPR_32RegClass;
10747         break;
10748       default:
10749         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
10750         if (!RC)
10751           return std::make_pair(0U, nullptr);
10752         break;
10753       }
10754       break;
10755     case 'a':
10756       if (!Subtarget->hasMAIInsts())
10757         break;
10758       switch (BitWidth) {
10759       case 16:
10760         RC = &AMDGPU::AGPR_32RegClass;
10761         break;
10762       default:
10763         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
10764         if (!RC)
10765           return std::make_pair(0U, nullptr);
10766         break;
10767       }
10768       break;
10769     }
10770     // We actually support i128, i16 and f16 as inline parameters
10771     // even if they are not reported as legal
10772     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10773                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10774       return std::make_pair(0U, RC);
10775   }
10776 
10777   if (Constraint.size() > 1) {
10778     if (Constraint[1] == 'v') {
10779       RC = &AMDGPU::VGPR_32RegClass;
10780     } else if (Constraint[1] == 's') {
10781       RC = &AMDGPU::SGPR_32RegClass;
10782     } else if (Constraint[1] == 'a') {
10783       RC = &AMDGPU::AGPR_32RegClass;
10784     }
10785 
10786     if (RC) {
10787       uint32_t Idx;
10788       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10789       if (!Failed && Idx < RC->getNumRegs())
10790         return std::make_pair(RC->getRegister(Idx), RC);
10791     }
10792   }
10793 
10794   // FIXME: Returns VS_32 for physical SGPR constraints
10795   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10796 }
10797 
10798 SITargetLowering::ConstraintType
10799 SITargetLowering::getConstraintType(StringRef Constraint) const {
10800   if (Constraint.size() == 1) {
10801     switch (Constraint[0]) {
10802     default: break;
10803     case 's':
10804     case 'v':
10805     case 'a':
10806       return C_RegisterClass;
10807     }
10808   }
10809   return TargetLowering::getConstraintType(Constraint);
10810 }
10811 
10812 // Figure out which registers should be reserved for stack access. Only after
10813 // the function is legalized do we know all of the non-spill stack objects or if
10814 // calls are present.
10815 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10816   MachineRegisterInfo &MRI = MF.getRegInfo();
10817   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10818   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10819   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10820 
10821   if (Info->isEntryFunction()) {
10822     // Callable functions have fixed registers used for stack access.
10823     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10824   }
10825 
10826   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10827                              Info->getStackPtrOffsetReg()));
10828   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10829     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10830 
10831   // We need to worry about replacing the default register with itself in case
10832   // of MIR testcases missing the MFI.
10833   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10834     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10835 
10836   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10837     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10838 
10839   Info->limitOccupancy(MF);
10840 
10841   if (ST.isWave32() && !MF.empty()) {
10842     // Add VCC_HI def because many instructions marked as imp-use VCC where
10843     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10844     // having a use of undef.
10845 
10846     const SIInstrInfo *TII = ST.getInstrInfo();
10847     DebugLoc DL;
10848 
10849     MachineBasicBlock &MBB = MF.front();
10850     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10851     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10852 
10853     for (auto &MBB : MF) {
10854       for (auto &MI : MBB) {
10855         TII->fixImplicitOperands(MI);
10856       }
10857     }
10858   }
10859 
10860   TargetLoweringBase::finalizeLowering(MF);
10861 }
10862 
10863 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10864                                                      KnownBits &Known,
10865                                                      const APInt &DemandedElts,
10866                                                      const SelectionDAG &DAG,
10867                                                      unsigned Depth) const {
10868   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10869                                                 DAG, Depth);
10870 
10871   // Set the high bits to zero based on the maximum allowed scratch size per
10872   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10873   // calculation won't overflow, so assume the sign bit is never set.
10874   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10875 }
10876 
10877 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10878   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10879   const Align CacheLineAlign = Align(64);
10880 
10881   // Pre-GFX10 target did not benefit from loop alignment
10882   if (!ML || DisableLoopAlignment ||
10883       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10884       getSubtarget()->hasInstFwdPrefetchBug())
10885     return PrefAlign;
10886 
10887   // On GFX10 I$ is 4 x 64 bytes cache lines.
10888   // By default prefetcher keeps one cache line behind and reads two ahead.
10889   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10890   // behind and one ahead.
10891   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10892   // If loop fits 64 bytes it always spans no more than two cache lines and
10893   // does not need an alignment.
10894   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10895   // Else if loop is less or equal 192 bytes we need two lines behind.
10896 
10897   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10898   const MachineBasicBlock *Header = ML->getHeader();
10899   if (Header->getAlignment() != PrefAlign)
10900     return Header->getAlignment(); // Already processed.
10901 
10902   unsigned LoopSize = 0;
10903   for (const MachineBasicBlock *MBB : ML->blocks()) {
10904     // If inner loop block is aligned assume in average half of the alignment
10905     // size to be added as nops.
10906     if (MBB != Header)
10907       LoopSize += MBB->getAlignment().value() / 2;
10908 
10909     for (const MachineInstr &MI : *MBB) {
10910       LoopSize += TII->getInstSizeInBytes(MI);
10911       if (LoopSize > 192)
10912         return PrefAlign;
10913     }
10914   }
10915 
10916   if (LoopSize <= 64)
10917     return PrefAlign;
10918 
10919   if (LoopSize <= 128)
10920     return CacheLineAlign;
10921 
10922   // If any of parent loops is surrounded by prefetch instructions do not
10923   // insert new for inner loop, which would reset parent's settings.
10924   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10925     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10926       auto I = Exit->getFirstNonDebugInstr();
10927       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10928         return CacheLineAlign;
10929     }
10930   }
10931 
10932   MachineBasicBlock *Pre = ML->getLoopPreheader();
10933   MachineBasicBlock *Exit = ML->getExitBlock();
10934 
10935   if (Pre && Exit) {
10936     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10937             TII->get(AMDGPU::S_INST_PREFETCH))
10938       .addImm(1); // prefetch 2 lines behind PC
10939 
10940     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10941             TII->get(AMDGPU::S_INST_PREFETCH))
10942       .addImm(2); // prefetch 1 line behind PC
10943   }
10944 
10945   return CacheLineAlign;
10946 }
10947 
10948 LLVM_ATTRIBUTE_UNUSED
10949 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10950   assert(N->getOpcode() == ISD::CopyFromReg);
10951   do {
10952     // Follow the chain until we find an INLINEASM node.
10953     N = N->getOperand(0).getNode();
10954     if (N->getOpcode() == ISD::INLINEASM ||
10955         N->getOpcode() == ISD::INLINEASM_BR)
10956       return true;
10957   } while (N->getOpcode() == ISD::CopyFromReg);
10958   return false;
10959 }
10960 
10961 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10962   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10963 {
10964   switch (N->getOpcode()) {
10965     case ISD::CopyFromReg:
10966     {
10967       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10968       const MachineFunction * MF = FLI->MF;
10969       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10970       const MachineRegisterInfo &MRI = MF->getRegInfo();
10971       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10972       Register Reg = R->getReg();
10973       if (Reg.isPhysical())
10974         return !TRI.isSGPRReg(MRI, Reg);
10975 
10976       if (MRI.isLiveIn(Reg)) {
10977         // workitem.id.x workitem.id.y workitem.id.z
10978         // Any VGPR formal argument is also considered divergent
10979         if (!TRI.isSGPRReg(MRI, Reg))
10980           return true;
10981         // Formal arguments of non-entry functions
10982         // are conservatively considered divergent
10983         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10984           return true;
10985         return false;
10986       }
10987       const Value *V = FLI->getValueFromVirtualReg(Reg);
10988       if (V)
10989         return KDA->isDivergent(V);
10990       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10991       return !TRI.isSGPRReg(MRI, Reg);
10992     }
10993     break;
10994     case ISD::LOAD: {
10995       const LoadSDNode *L = cast<LoadSDNode>(N);
10996       unsigned AS = L->getAddressSpace();
10997       // A flat load may access private memory.
10998       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10999     } break;
11000     case ISD::CALLSEQ_END:
11001     return true;
11002     break;
11003     case ISD::INTRINSIC_WO_CHAIN:
11004     {
11005 
11006     }
11007       return AMDGPU::isIntrinsicSourceOfDivergence(
11008       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11009     case ISD::INTRINSIC_W_CHAIN:
11010       return AMDGPU::isIntrinsicSourceOfDivergence(
11011       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11012   }
11013   return false;
11014 }
11015 
11016 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11017                                                EVT VT) const {
11018   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11019   case MVT::f32:
11020     return hasFP32Denormals(DAG.getMachineFunction());
11021   case MVT::f64:
11022   case MVT::f16:
11023     return hasFP64FP16Denormals(DAG.getMachineFunction());
11024   default:
11025     return false;
11026   }
11027 }
11028 
11029 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11030                                                     const SelectionDAG &DAG,
11031                                                     bool SNaN,
11032                                                     unsigned Depth) const {
11033   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11034     const MachineFunction &MF = DAG.getMachineFunction();
11035     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11036 
11037     if (Info->getMode().DX10Clamp)
11038       return true; // Clamped to 0.
11039     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11040   }
11041 
11042   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11043                                                             SNaN, Depth);
11044 }
11045 
11046 TargetLowering::AtomicExpansionKind
11047 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11048   switch (RMW->getOperation()) {
11049   case AtomicRMWInst::FAdd: {
11050     Type *Ty = RMW->getType();
11051 
11052     // We don't have a way to support 16-bit atomics now, so just leave them
11053     // as-is.
11054     if (Ty->isHalfTy())
11055       return AtomicExpansionKind::None;
11056 
11057     if (!Ty->isFloatTy())
11058       return AtomicExpansionKind::CmpXChg;
11059 
11060     // TODO: Do have these for flat. Older targets also had them for buffers.
11061     unsigned AS = RMW->getPointerAddressSpace();
11062 
11063     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11064       return RMW->use_empty() ? AtomicExpansionKind::None :
11065                                 AtomicExpansionKind::CmpXChg;
11066     }
11067 
11068     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11069       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11070   }
11071   default:
11072     break;
11073   }
11074 
11075   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11076 }
11077 
11078 const TargetRegisterClass *
11079 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11080   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11081   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11082   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11083     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11084                                                : &AMDGPU::SReg_32RegClass;
11085   if (!TRI->isSGPRClass(RC) && !isDivergent)
11086     return TRI->getEquivalentSGPRClass(RC);
11087   else if (TRI->isSGPRClass(RC) && isDivergent)
11088     return TRI->getEquivalentVGPRClass(RC);
11089 
11090   return RC;
11091 }
11092 
11093 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11094 // uniform values (as produced by the mask results of control flow intrinsics)
11095 // used outside of divergent blocks. The phi users need to also be treated as
11096 // always uniform.
11097 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11098                       unsigned WaveSize) {
11099   // FIXME: We asssume we never cast the mask results of a control flow
11100   // intrinsic.
11101   // Early exit if the type won't be consistent as a compile time hack.
11102   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11103   if (!IT || IT->getBitWidth() != WaveSize)
11104     return false;
11105 
11106   if (!isa<Instruction>(V))
11107     return false;
11108   if (!Visited.insert(V).second)
11109     return false;
11110   bool Result = false;
11111   for (auto U : V->users()) {
11112     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11113       if (V == U->getOperand(1)) {
11114         switch (Intrinsic->getIntrinsicID()) {
11115         default:
11116           Result = false;
11117           break;
11118         case Intrinsic::amdgcn_if_break:
11119         case Intrinsic::amdgcn_if:
11120         case Intrinsic::amdgcn_else:
11121           Result = true;
11122           break;
11123         }
11124       }
11125       if (V == U->getOperand(0)) {
11126         switch (Intrinsic->getIntrinsicID()) {
11127         default:
11128           Result = false;
11129           break;
11130         case Intrinsic::amdgcn_end_cf:
11131         case Intrinsic::amdgcn_loop:
11132           Result = true;
11133           break;
11134         }
11135       }
11136     } else {
11137       Result = hasCFUser(U, Visited, WaveSize);
11138     }
11139     if (Result)
11140       break;
11141   }
11142   return Result;
11143 }
11144 
11145 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11146                                                const Value *V) const {
11147   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11148     if (CI->isInlineAsm()) {
11149       // FIXME: This cannot give a correct answer. This should only trigger in
11150       // the case where inline asm returns mixed SGPR and VGPR results, used
11151       // outside the defining block. We don't have a specific result to
11152       // consider, so this assumes if any value is SGPR, the overall register
11153       // also needs to be SGPR.
11154       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11155       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11156           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11157       for (auto &TC : TargetConstraints) {
11158         if (TC.Type == InlineAsm::isOutput) {
11159           ComputeConstraintToUse(TC, SDValue());
11160           unsigned AssignedReg;
11161           const TargetRegisterClass *RC;
11162           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11163               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11164           if (RC) {
11165             MachineRegisterInfo &MRI = MF.getRegInfo();
11166             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11167               return true;
11168             else if (SIRI->isSGPRClass(RC))
11169               return true;
11170           }
11171         }
11172       }
11173     }
11174   }
11175   SmallPtrSet<const Value *, 16> Visited;
11176   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11177 }
11178