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::SReg_256RegClass);
145   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
146 
147   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_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 
206   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
207   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
208 
209   setOperationAction(ISD::SELECT, MVT::i1, Promote);
210   setOperationAction(ISD::SELECT, MVT::i64, Custom);
211   setOperationAction(ISD::SELECT, MVT::f64, Promote);
212   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
213 
214   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
215   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
216   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
217   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
218   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
219 
220   setOperationAction(ISD::SETCC, MVT::i1, Promote);
221   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
222   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
223   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
224 
225   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
226   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
227 
228   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
229   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
230   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
231   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
232   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
233   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
234   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
235   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
236 
237   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
238   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
239   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
240   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
241   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
242   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
243 
244   setOperationAction(ISD::UADDO, MVT::i32, Legal);
245   setOperationAction(ISD::USUBO, MVT::i32, Legal);
246 
247   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
248   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
249 
250   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
251   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
252   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
253 
254 #if 0
255   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
256   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
257 #endif
258 
259   // We only support LOAD/STORE and vector manipulation ops for vectors
260   // with > 4 elements.
261   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
262                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
263                   MVT::v32i32, MVT::v32f32 }) {
264     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
265       switch (Op) {
266       case ISD::LOAD:
267       case ISD::STORE:
268       case ISD::BUILD_VECTOR:
269       case ISD::BITCAST:
270       case ISD::EXTRACT_VECTOR_ELT:
271       case ISD::INSERT_VECTOR_ELT:
272       case ISD::INSERT_SUBVECTOR:
273       case ISD::EXTRACT_SUBVECTOR:
274       case ISD::SCALAR_TO_VECTOR:
275         break;
276       case ISD::CONCAT_VECTORS:
277         setOperationAction(Op, VT, Custom);
278         break;
279       default:
280         setOperationAction(Op, VT, Expand);
281         break;
282       }
283     }
284   }
285 
286   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
287 
288   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
289   // is expanded to avoid having two separate loops in case the index is a VGPR.
290 
291   // Most operations are naturally 32-bit vector operations. We only support
292   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
293   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
294     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
295     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
296 
297     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
298     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
299 
300     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
301     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
302 
303     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
304     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
305   }
306 
307   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
308   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
309   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
310   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
311 
312   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
313   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
314 
315   // Avoid stack access for these.
316   // TODO: Generalize to more vector types.
317   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
318   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
319   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
320   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
321 
322   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
323   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
324   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
325   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
326   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
327 
328   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
329   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
330   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
331 
332   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
333   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
334   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
335   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
336 
337   // Deal with vec3 vector operations when widened to vec4.
338   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
339   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
340   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
341   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
342 
343   // Deal with vec5 vector operations when widened to vec8.
344   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
345   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
346   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
347   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
348 
349   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
350   // and output demarshalling
351   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
352   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
353 
354   // We can't return success/failure, only the old value,
355   // let LLVM add the comparison
356   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
357   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
358 
359   if (Subtarget->hasFlatAddressSpace()) {
360     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
361     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
362   }
363 
364   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
365 
366   // FIXME: This should be narrowed to i32, but that only happens if i64 is
367   // illegal.
368   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
369   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
370   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
371 
372   // On SI this is s_memtime and s_memrealtime on VI.
373   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
374   setOperationAction(ISD::TRAP, MVT::Other, Custom);
375   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
376 
377   if (Subtarget->has16BitInsts()) {
378     setOperationAction(ISD::FPOW, MVT::f16, Promote);
379     setOperationAction(ISD::FLOG, MVT::f16, Custom);
380     setOperationAction(ISD::FEXP, MVT::f16, Custom);
381     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
382   }
383 
384   // v_mad_f32 does not support denormals. We report it as unconditionally
385   // legal, and the context where it is formed will disallow it when fp32
386   // denormals are enabled.
387   setOperationAction(ISD::FMAD, MVT::f32, Legal);
388 
389   if (!Subtarget->hasBFI()) {
390     // fcopysign can be done in a single instruction with BFI.
391     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
392     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
393   }
394 
395   if (!Subtarget->hasBCNT(32))
396     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
397 
398   if (!Subtarget->hasBCNT(64))
399     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
400 
401   if (Subtarget->hasFFBH())
402     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
403 
404   if (Subtarget->hasFFBL())
405     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
406 
407   // We only really have 32-bit BFE instructions (and 16-bit on VI).
408   //
409   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
410   // effort to match them now. We want this to be false for i64 cases when the
411   // extraction isn't restricted to the upper or lower half. Ideally we would
412   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
413   // span the midpoint are probably relatively rare, so don't worry about them
414   // for now.
415   if (Subtarget->hasBFE())
416     setHasExtractBitsInsn(true);
417 
418   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
419   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
420   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
421   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
422 
423 
424   // These are really only legal for ieee_mode functions. We should be avoiding
425   // them for functions that don't have ieee_mode enabled, so just say they are
426   // legal.
427   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
428   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
429   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
430   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
431 
432 
433   if (Subtarget->haveRoundOpsF64()) {
434     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
435     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
436     setOperationAction(ISD::FRINT, MVT::f64, Legal);
437   } else {
438     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
439     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
440     setOperationAction(ISD::FRINT, MVT::f64, Custom);
441     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
442   }
443 
444   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
445 
446   setOperationAction(ISD::FSIN, MVT::f32, Custom);
447   setOperationAction(ISD::FCOS, MVT::f32, Custom);
448   setOperationAction(ISD::FDIV, MVT::f32, Custom);
449   setOperationAction(ISD::FDIV, MVT::f64, Custom);
450 
451   if (Subtarget->has16BitInsts()) {
452     setOperationAction(ISD::Constant, MVT::i16, Legal);
453 
454     setOperationAction(ISD::SMIN, MVT::i16, Legal);
455     setOperationAction(ISD::SMAX, MVT::i16, Legal);
456 
457     setOperationAction(ISD::UMIN, MVT::i16, Legal);
458     setOperationAction(ISD::UMAX, MVT::i16, Legal);
459 
460     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
461     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
462 
463     setOperationAction(ISD::ROTR, MVT::i16, Promote);
464     setOperationAction(ISD::ROTL, MVT::i16, Promote);
465 
466     setOperationAction(ISD::SDIV, MVT::i16, Promote);
467     setOperationAction(ISD::UDIV, MVT::i16, Promote);
468     setOperationAction(ISD::SREM, MVT::i16, Promote);
469     setOperationAction(ISD::UREM, MVT::i16, Promote);
470 
471     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
472 
473     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
474     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
475     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
476     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
477     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
478 
479     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
480 
481     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
482 
483     setOperationAction(ISD::LOAD, MVT::i16, Custom);
484 
485     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
486 
487     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
488     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
489     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
490     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
491 
492     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
493     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
494 
495     // F16 - Constant Actions.
496     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
497 
498     // F16 - Load/Store Actions.
499     setOperationAction(ISD::LOAD, MVT::f16, Promote);
500     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
501     setOperationAction(ISD::STORE, MVT::f16, Promote);
502     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
503 
504     // F16 - VOP1 Actions.
505     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
506     setOperationAction(ISD::FCOS, MVT::f16, Custom);
507     setOperationAction(ISD::FSIN, MVT::f16, Custom);
508 
509     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
510     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
511 
512     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
513     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
514     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
515     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
516     setOperationAction(ISD::FROUND, MVT::f16, Custom);
517 
518     // F16 - VOP2 Actions.
519     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
520     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
521 
522     setOperationAction(ISD::FDIV, MVT::f16, Custom);
523 
524     // F16 - VOP3 Actions.
525     setOperationAction(ISD::FMA, MVT::f16, Legal);
526     if (STI.hasMadF16())
527       setOperationAction(ISD::FMAD, MVT::f16, Legal);
528 
529     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
530       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
531         switch (Op) {
532         case ISD::LOAD:
533         case ISD::STORE:
534         case ISD::BUILD_VECTOR:
535         case ISD::BITCAST:
536         case ISD::EXTRACT_VECTOR_ELT:
537         case ISD::INSERT_VECTOR_ELT:
538         case ISD::INSERT_SUBVECTOR:
539         case ISD::EXTRACT_SUBVECTOR:
540         case ISD::SCALAR_TO_VECTOR:
541           break;
542         case ISD::CONCAT_VECTORS:
543           setOperationAction(Op, VT, Custom);
544           break;
545         default:
546           setOperationAction(Op, VT, Expand);
547           break;
548         }
549       }
550     }
551 
552     // v_perm_b32 can handle either of these.
553     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
554     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
555     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
556 
557     // XXX - Do these do anything? Vector constants turn into build_vector.
558     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
559     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
560 
561     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
562     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
563 
564     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
565     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
566     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
567     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
568 
569     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
570     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
571     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
572     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
573 
574     setOperationAction(ISD::AND, MVT::v2i16, Promote);
575     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
576     setOperationAction(ISD::OR, MVT::v2i16, Promote);
577     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
578     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
579     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
580 
581     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
582     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
583     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
584     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
585 
586     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
587     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
588     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
589     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
590 
591     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
592     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
593     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
594     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
595 
596     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
597     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
598     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
599 
600     if (!Subtarget->hasVOP3PInsts()) {
601       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
602       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
603     }
604 
605     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
606     // This isn't really legal, but this avoids the legalizer unrolling it (and
607     // allows matching fneg (fabs x) patterns)
608     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
609 
610     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
611     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
612     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
613     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
614 
615     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
616     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
617 
618     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
619     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
620   }
621 
622   if (Subtarget->hasVOP3PInsts()) {
623     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
624     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
625     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
626     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
627     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
628     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
629     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
630     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
631     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
632     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
633 
634     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
635     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
636     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
637 
638     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
639     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
640 
641     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
642 
643     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
644     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
645 
646     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
647     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
648 
649     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
650     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
651     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
652     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
653     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
654     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
655 
656     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
657     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
658     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
659     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
660 
661     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
662     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
663     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
664 
665     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
666     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
667 
668     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
669     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
670     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
671 
672     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
673     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
674     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
675   }
676 
677   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
678   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
679 
680   if (Subtarget->has16BitInsts()) {
681     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
682     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
683     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
684     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
685   } else {
686     // Legalization hack.
687     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
688     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
689 
690     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
691     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
692   }
693 
694   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
695     setOperationAction(ISD::SELECT, VT, Custom);
696   }
697 
698   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
699   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
700   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
701   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
702   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
703   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
704   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
705 
706   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
707   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
708   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
709   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
710   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
711   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
712   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
713   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
714   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
715 
716   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
717   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
718   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
719   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
720   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
721   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
722   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
723   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
724 
725   setTargetDAGCombine(ISD::ADD);
726   setTargetDAGCombine(ISD::ADDCARRY);
727   setTargetDAGCombine(ISD::SUB);
728   setTargetDAGCombine(ISD::SUBCARRY);
729   setTargetDAGCombine(ISD::FADD);
730   setTargetDAGCombine(ISD::FSUB);
731   setTargetDAGCombine(ISD::FMINNUM);
732   setTargetDAGCombine(ISD::FMAXNUM);
733   setTargetDAGCombine(ISD::FMINNUM_IEEE);
734   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
735   setTargetDAGCombine(ISD::FMA);
736   setTargetDAGCombine(ISD::SMIN);
737   setTargetDAGCombine(ISD::SMAX);
738   setTargetDAGCombine(ISD::UMIN);
739   setTargetDAGCombine(ISD::UMAX);
740   setTargetDAGCombine(ISD::SETCC);
741   setTargetDAGCombine(ISD::AND);
742   setTargetDAGCombine(ISD::OR);
743   setTargetDAGCombine(ISD::XOR);
744   setTargetDAGCombine(ISD::SINT_TO_FP);
745   setTargetDAGCombine(ISD::UINT_TO_FP);
746   setTargetDAGCombine(ISD::FCANONICALIZE);
747   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
748   setTargetDAGCombine(ISD::ZERO_EXTEND);
749   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
750   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
751   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
752 
753   // All memory operations. Some folding on the pointer operand is done to help
754   // matching the constant offsets in the addressing modes.
755   setTargetDAGCombine(ISD::LOAD);
756   setTargetDAGCombine(ISD::STORE);
757   setTargetDAGCombine(ISD::ATOMIC_LOAD);
758   setTargetDAGCombine(ISD::ATOMIC_STORE);
759   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
760   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
761   setTargetDAGCombine(ISD::ATOMIC_SWAP);
762   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
763   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
764   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
765   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
766   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
767   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
768   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
769   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
770   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
771   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
772   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
773 
774   setSchedulingPreference(Sched::RegPressure);
775 }
776 
777 const GCNSubtarget *SITargetLowering::getSubtarget() const {
778   return Subtarget;
779 }
780 
781 //===----------------------------------------------------------------------===//
782 // TargetLowering queries
783 //===----------------------------------------------------------------------===//
784 
785 // v_mad_mix* support a conversion from f16 to f32.
786 //
787 // There is only one special case when denormals are enabled we don't currently,
788 // where this is OK to use.
789 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
790                                        EVT DestVT, EVT SrcVT) const {
791   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
792           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
793     DestVT.getScalarType() == MVT::f32 &&
794     SrcVT.getScalarType() == MVT::f16 &&
795     // TODO: This probably only requires no input flushing?
796     !hasFP32Denormals(DAG.getMachineFunction());
797 }
798 
799 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
800   // SI has some legal vector types, but no legal vector operations. Say no
801   // shuffles are legal in order to prefer scalarizing some vector operations.
802   return false;
803 }
804 
805 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
806                                                     CallingConv::ID CC,
807                                                     EVT VT) const {
808   if (CC == CallingConv::AMDGPU_KERNEL)
809     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
810 
811   if (VT.isVector()) {
812     EVT ScalarVT = VT.getScalarType();
813     unsigned Size = ScalarVT.getSizeInBits();
814     if (Size == 32)
815       return ScalarVT.getSimpleVT();
816 
817     if (Size > 32)
818       return MVT::i32;
819 
820     if (Size == 16 && Subtarget->has16BitInsts())
821       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
822   } else if (VT.getSizeInBits() > 32)
823     return MVT::i32;
824 
825   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
826 }
827 
828 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
829                                                          CallingConv::ID CC,
830                                                          EVT VT) const {
831   if (CC == CallingConv::AMDGPU_KERNEL)
832     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
833 
834   if (VT.isVector()) {
835     unsigned NumElts = VT.getVectorNumElements();
836     EVT ScalarVT = VT.getScalarType();
837     unsigned Size = ScalarVT.getSizeInBits();
838 
839     if (Size == 32)
840       return NumElts;
841 
842     if (Size > 32)
843       return NumElts * ((Size + 31) / 32);
844 
845     if (Size == 16 && Subtarget->has16BitInsts())
846       return (NumElts + 1) / 2;
847   } else if (VT.getSizeInBits() > 32)
848     return (VT.getSizeInBits() + 31) / 32;
849 
850   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
851 }
852 
853 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
854   LLVMContext &Context, CallingConv::ID CC,
855   EVT VT, EVT &IntermediateVT,
856   unsigned &NumIntermediates, MVT &RegisterVT) const {
857   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
858     unsigned NumElts = VT.getVectorNumElements();
859     EVT ScalarVT = VT.getScalarType();
860     unsigned Size = ScalarVT.getSizeInBits();
861     if (Size == 32) {
862       RegisterVT = ScalarVT.getSimpleVT();
863       IntermediateVT = RegisterVT;
864       NumIntermediates = NumElts;
865       return NumIntermediates;
866     }
867 
868     if (Size > 32) {
869       RegisterVT = MVT::i32;
870       IntermediateVT = RegisterVT;
871       NumIntermediates = NumElts * ((Size + 31) / 32);
872       return NumIntermediates;
873     }
874 
875     // FIXME: We should fix the ABI to be the same on targets without 16-bit
876     // support, but unless we can properly handle 3-vectors, it will be still be
877     // inconsistent.
878     if (Size == 16 && Subtarget->has16BitInsts()) {
879       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
880       IntermediateVT = RegisterVT;
881       NumIntermediates = (NumElts + 1) / 2;
882       return NumIntermediates;
883     }
884   }
885 
886   return TargetLowering::getVectorTypeBreakdownForCallingConv(
887     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
888 }
889 
890 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
891   assert(DMaskLanes != 0);
892 
893   if (auto *VT = dyn_cast<VectorType>(Ty)) {
894     unsigned NumElts = std::min(DMaskLanes,
895                                 static_cast<unsigned>(VT->getNumElements()));
896     return EVT::getVectorVT(Ty->getContext(),
897                             EVT::getEVT(VT->getElementType()),
898                             NumElts);
899   }
900 
901   return EVT::getEVT(Ty);
902 }
903 
904 // Peek through TFE struct returns to only use the data size.
905 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
906   auto *ST = dyn_cast<StructType>(Ty);
907   if (!ST)
908     return memVTFromImageData(Ty, DMaskLanes);
909 
910   // Some intrinsics return an aggregate type - special case to work out the
911   // correct memVT.
912   //
913   // Only limited forms of aggregate type currently expected.
914   if (ST->getNumContainedTypes() != 2 ||
915       !ST->getContainedType(1)->isIntegerTy(32))
916     return EVT();
917   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
918 }
919 
920 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
921                                           const CallInst &CI,
922                                           MachineFunction &MF,
923                                           unsigned IntrID) const {
924   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
925           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
926     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
927                                                   (Intrinsic::ID)IntrID);
928     if (Attr.hasFnAttribute(Attribute::ReadNone))
929       return false;
930 
931     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
932 
933     if (RsrcIntr->IsImage) {
934       Info.ptrVal = MFI->getImagePSV(
935         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
936         CI.getArgOperand(RsrcIntr->RsrcArg));
937       Info.align.reset();
938     } else {
939       Info.ptrVal = MFI->getBufferPSV(
940         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
941         CI.getArgOperand(RsrcIntr->RsrcArg));
942     }
943 
944     Info.flags = MachineMemOperand::MODereferenceable;
945     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
946       unsigned DMaskLanes = 4;
947 
948       if (RsrcIntr->IsImage) {
949         const AMDGPU::ImageDimIntrinsicInfo *Intr
950           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
951         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
952           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
953 
954         if (!BaseOpcode->Gather4) {
955           // If this isn't a gather, we may have excess loaded elements in the
956           // IR type. Check the dmask for the real number of elements loaded.
957           unsigned DMask
958             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
959           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
960         }
961 
962         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
963       } else
964         Info.memVT = EVT::getEVT(CI.getType());
965 
966       // FIXME: What does alignment mean for an image?
967       Info.opc = ISD::INTRINSIC_W_CHAIN;
968       Info.flags |= MachineMemOperand::MOLoad;
969     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
970       Info.opc = ISD::INTRINSIC_VOID;
971 
972       Type *DataTy = CI.getArgOperand(0)->getType();
973       if (RsrcIntr->IsImage) {
974         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
975         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
976         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
977       } else
978         Info.memVT = EVT::getEVT(DataTy);
979 
980       Info.flags |= MachineMemOperand::MOStore;
981     } else {
982       // Atomic
983       Info.opc = ISD::INTRINSIC_W_CHAIN;
984       Info.memVT = MVT::getVT(CI.getType());
985       Info.flags = MachineMemOperand::MOLoad |
986                    MachineMemOperand::MOStore |
987                    MachineMemOperand::MODereferenceable;
988 
989       // XXX - Should this be volatile without known ordering?
990       Info.flags |= MachineMemOperand::MOVolatile;
991     }
992     return true;
993   }
994 
995   switch (IntrID) {
996   case Intrinsic::amdgcn_atomic_inc:
997   case Intrinsic::amdgcn_atomic_dec:
998   case Intrinsic::amdgcn_ds_ordered_add:
999   case Intrinsic::amdgcn_ds_ordered_swap:
1000   case Intrinsic::amdgcn_ds_fadd:
1001   case Intrinsic::amdgcn_ds_fmin:
1002   case Intrinsic::amdgcn_ds_fmax: {
1003     Info.opc = ISD::INTRINSIC_W_CHAIN;
1004     Info.memVT = MVT::getVT(CI.getType());
1005     Info.ptrVal = CI.getOperand(0);
1006     Info.align.reset();
1007     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1008 
1009     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1010     if (!Vol->isZero())
1011       Info.flags |= MachineMemOperand::MOVolatile;
1012 
1013     return true;
1014   }
1015   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1016     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1017 
1018     Info.opc = ISD::INTRINSIC_VOID;
1019     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1020     Info.ptrVal = MFI->getBufferPSV(
1021       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1022       CI.getArgOperand(1));
1023     Info.align.reset();
1024     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1025 
1026     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1027     if (!Vol || !Vol->isZero())
1028       Info.flags |= MachineMemOperand::MOVolatile;
1029 
1030     return true;
1031   }
1032   case Intrinsic::amdgcn_global_atomic_fadd: {
1033     Info.opc = ISD::INTRINSIC_VOID;
1034     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1035                             ->getPointerElementType());
1036     Info.ptrVal = CI.getOperand(0);
1037     Info.align.reset();
1038     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1039 
1040     return true;
1041   }
1042   case Intrinsic::amdgcn_ds_append:
1043   case Intrinsic::amdgcn_ds_consume: {
1044     Info.opc = ISD::INTRINSIC_W_CHAIN;
1045     Info.memVT = MVT::getVT(CI.getType());
1046     Info.ptrVal = CI.getOperand(0);
1047     Info.align.reset();
1048     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1049 
1050     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1051     if (!Vol->isZero())
1052       Info.flags |= MachineMemOperand::MOVolatile;
1053 
1054     return true;
1055   }
1056   case Intrinsic::amdgcn_ds_gws_init:
1057   case Intrinsic::amdgcn_ds_gws_barrier:
1058   case Intrinsic::amdgcn_ds_gws_sema_v:
1059   case Intrinsic::amdgcn_ds_gws_sema_br:
1060   case Intrinsic::amdgcn_ds_gws_sema_p:
1061   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1062     Info.opc = ISD::INTRINSIC_VOID;
1063 
1064     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1065     Info.ptrVal =
1066         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1067 
1068     // This is an abstract access, but we need to specify a type and size.
1069     Info.memVT = MVT::i32;
1070     Info.size = 4;
1071     Info.align = Align(4);
1072 
1073     Info.flags = MachineMemOperand::MOStore;
1074     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1075       Info.flags = MachineMemOperand::MOLoad;
1076     return true;
1077   }
1078   default:
1079     return false;
1080   }
1081 }
1082 
1083 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1084                                             SmallVectorImpl<Value*> &Ops,
1085                                             Type *&AccessTy) const {
1086   switch (II->getIntrinsicID()) {
1087   case Intrinsic::amdgcn_atomic_inc:
1088   case Intrinsic::amdgcn_atomic_dec:
1089   case Intrinsic::amdgcn_ds_ordered_add:
1090   case Intrinsic::amdgcn_ds_ordered_swap:
1091   case Intrinsic::amdgcn_ds_fadd:
1092   case Intrinsic::amdgcn_ds_fmin:
1093   case Intrinsic::amdgcn_ds_fmax: {
1094     Value *Ptr = II->getArgOperand(0);
1095     AccessTy = II->getType();
1096     Ops.push_back(Ptr);
1097     return true;
1098   }
1099   default:
1100     return false;
1101   }
1102 }
1103 
1104 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1105   if (!Subtarget->hasFlatInstOffsets()) {
1106     // Flat instructions do not have offsets, and only have the register
1107     // address.
1108     return AM.BaseOffs == 0 && AM.Scale == 0;
1109   }
1110 
1111   return AM.Scale == 0 &&
1112          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1113                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1114                                   /*Signed=*/false));
1115 }
1116 
1117 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1118   if (Subtarget->hasFlatGlobalInsts())
1119     return AM.Scale == 0 &&
1120            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1121                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1122                                     /*Signed=*/true));
1123 
1124   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1125       // Assume the we will use FLAT for all global memory accesses
1126       // on VI.
1127       // FIXME: This assumption is currently wrong.  On VI we still use
1128       // MUBUF instructions for the r + i addressing mode.  As currently
1129       // implemented, the MUBUF instructions only work on buffer < 4GB.
1130       // It may be possible to support > 4GB buffers with MUBUF instructions,
1131       // by setting the stride value in the resource descriptor which would
1132       // increase the size limit to (stride * 4GB).  However, this is risky,
1133       // because it has never been validated.
1134     return isLegalFlatAddressingMode(AM);
1135   }
1136 
1137   return isLegalMUBUFAddressingMode(AM);
1138 }
1139 
1140 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1141   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1142   // additionally can do r + r + i with addr64. 32-bit has more addressing
1143   // mode options. Depending on the resource constant, it can also do
1144   // (i64 r0) + (i32 r1) * (i14 i).
1145   //
1146   // Private arrays end up using a scratch buffer most of the time, so also
1147   // assume those use MUBUF instructions. Scratch loads / stores are currently
1148   // implemented as mubuf instructions with offen bit set, so slightly
1149   // different than the normal addr64.
1150   if (!isUInt<12>(AM.BaseOffs))
1151     return false;
1152 
1153   // FIXME: Since we can split immediate into soffset and immediate offset,
1154   // would it make sense to allow any immediate?
1155 
1156   switch (AM.Scale) {
1157   case 0: // r + i or just i, depending on HasBaseReg.
1158     return true;
1159   case 1:
1160     return true; // We have r + r or r + i.
1161   case 2:
1162     if (AM.HasBaseReg) {
1163       // Reject 2 * r + r.
1164       return false;
1165     }
1166 
1167     // Allow 2 * r as r + r
1168     // Or  2 * r + i is allowed as r + r + i.
1169     return true;
1170   default: // Don't allow n * r
1171     return false;
1172   }
1173 }
1174 
1175 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1176                                              const AddrMode &AM, Type *Ty,
1177                                              unsigned AS, Instruction *I) const {
1178   // No global is ever allowed as a base.
1179   if (AM.BaseGV)
1180     return false;
1181 
1182   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1183     return isLegalGlobalAddressingMode(AM);
1184 
1185   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1186       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1187       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1188     // If the offset isn't a multiple of 4, it probably isn't going to be
1189     // correctly aligned.
1190     // FIXME: Can we get the real alignment here?
1191     if (AM.BaseOffs % 4 != 0)
1192       return isLegalMUBUFAddressingMode(AM);
1193 
1194     // There are no SMRD extloads, so if we have to do a small type access we
1195     // will use a MUBUF load.
1196     // FIXME?: We also need to do this if unaligned, but we don't know the
1197     // alignment here.
1198     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1199       return isLegalGlobalAddressingMode(AM);
1200 
1201     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1202       // SMRD instructions have an 8-bit, dword offset on SI.
1203       if (!isUInt<8>(AM.BaseOffs / 4))
1204         return false;
1205     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1206       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1207       // in 8-bits, it can use a smaller encoding.
1208       if (!isUInt<32>(AM.BaseOffs / 4))
1209         return false;
1210     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1211       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1212       if (!isUInt<20>(AM.BaseOffs))
1213         return false;
1214     } else
1215       llvm_unreachable("unhandled generation");
1216 
1217     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1218       return true;
1219 
1220     if (AM.Scale == 1 && AM.HasBaseReg)
1221       return true;
1222 
1223     return false;
1224 
1225   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1226     return isLegalMUBUFAddressingMode(AM);
1227   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1228              AS == AMDGPUAS::REGION_ADDRESS) {
1229     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1230     // field.
1231     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1232     // an 8-bit dword offset but we don't know the alignment here.
1233     if (!isUInt<16>(AM.BaseOffs))
1234       return false;
1235 
1236     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1237       return true;
1238 
1239     if (AM.Scale == 1 && AM.HasBaseReg)
1240       return true;
1241 
1242     return false;
1243   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1244              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1245     // For an unknown address space, this usually means that this is for some
1246     // reason being used for pure arithmetic, and not based on some addressing
1247     // computation. We don't have instructions that compute pointers with any
1248     // addressing modes, so treat them as having no offset like flat
1249     // instructions.
1250     return isLegalFlatAddressingMode(AM);
1251   } else {
1252     llvm_unreachable("unhandled address space");
1253   }
1254 }
1255 
1256 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1257                                         const SelectionDAG &DAG) const {
1258   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1259     return (MemVT.getSizeInBits() <= 4 * 32);
1260   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1261     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1262     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1263   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1264     return (MemVT.getSizeInBits() <= 2 * 32);
1265   }
1266   return true;
1267 }
1268 
1269 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1270     unsigned Size, unsigned AddrSpace, unsigned Align,
1271     MachineMemOperand::Flags Flags, bool *IsFast) const {
1272   if (IsFast)
1273     *IsFast = false;
1274 
1275   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1276       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1277     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1278     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1279     // with adjacent offsets.
1280     bool AlignedBy4 = (Align % 4 == 0);
1281     if (IsFast)
1282       *IsFast = AlignedBy4;
1283 
1284     return AlignedBy4;
1285   }
1286 
1287   // FIXME: We have to be conservative here and assume that flat operations
1288   // will access scratch.  If we had access to the IR function, then we
1289   // could determine if any private memory was used in the function.
1290   if (!Subtarget->hasUnalignedScratchAccess() &&
1291       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1292        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1293     bool AlignedBy4 = Align >= 4;
1294     if (IsFast)
1295       *IsFast = AlignedBy4;
1296 
1297     return AlignedBy4;
1298   }
1299 
1300   if (Subtarget->hasUnalignedBufferAccess()) {
1301     // If we have an uniform constant load, it still requires using a slow
1302     // buffer instruction if unaligned.
1303     if (IsFast) {
1304       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1305       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1306       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1307                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1308         Align >= 4 : Align != 2;
1309     }
1310 
1311     return true;
1312   }
1313 
1314   // Smaller than dword value must be aligned.
1315   if (Size < 32)
1316     return false;
1317 
1318   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1319   // byte-address are ignored, thus forcing Dword alignment.
1320   // This applies to private, global, and constant memory.
1321   if (IsFast)
1322     *IsFast = true;
1323 
1324   return Size >= 32 && Align >= 4;
1325 }
1326 
1327 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1328     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1329     bool *IsFast) const {
1330   if (IsFast)
1331     *IsFast = false;
1332 
1333   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1334   // which isn't a simple VT.
1335   // Until MVT is extended to handle this, simply check for the size and
1336   // rely on the condition below: allow accesses if the size is a multiple of 4.
1337   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1338                            VT.getStoreSize() > 16)) {
1339     return false;
1340   }
1341 
1342   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1343                                             Align, Flags, IsFast);
1344 }
1345 
1346 EVT SITargetLowering::getOptimalMemOpType(
1347     const MemOp &Op, const AttributeList &FuncAttributes) const {
1348   // FIXME: Should account for address space here.
1349 
1350   // The default fallback uses the private pointer size as a guess for a type to
1351   // use. Make sure we switch these to 64-bit accesses.
1352 
1353   if (Op.size() >= 16 &&
1354       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1355     return MVT::v4i32;
1356 
1357   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1358     return MVT::v2i32;
1359 
1360   // Use the default.
1361   return MVT::Other;
1362 }
1363 
1364 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1365                                            unsigned DestAS) const {
1366   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1367 }
1368 
1369 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1370   const MemSDNode *MemNode = cast<MemSDNode>(N);
1371   const Value *Ptr = MemNode->getMemOperand()->getValue();
1372   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1373   return I && I->getMetadata("amdgpu.noclobber");
1374 }
1375 
1376 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1377                                            unsigned DestAS) const {
1378   // Flat -> private/local is a simple truncate.
1379   // Flat -> global is no-op
1380   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1381     return true;
1382 
1383   return isNoopAddrSpaceCast(SrcAS, DestAS);
1384 }
1385 
1386 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1387   const MemSDNode *MemNode = cast<MemSDNode>(N);
1388 
1389   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1390 }
1391 
1392 TargetLoweringBase::LegalizeTypeAction
1393 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1394   int NumElts = VT.getVectorNumElements();
1395   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1396     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1397   return TargetLoweringBase::getPreferredVectorAction(VT);
1398 }
1399 
1400 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1401                                                          Type *Ty) const {
1402   // FIXME: Could be smarter if called for vector constants.
1403   return true;
1404 }
1405 
1406 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1407   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1408     switch (Op) {
1409     case ISD::LOAD:
1410     case ISD::STORE:
1411 
1412     // These operations are done with 32-bit instructions anyway.
1413     case ISD::AND:
1414     case ISD::OR:
1415     case ISD::XOR:
1416     case ISD::SELECT:
1417       // TODO: Extensions?
1418       return true;
1419     default:
1420       return false;
1421     }
1422   }
1423 
1424   // SimplifySetCC uses this function to determine whether or not it should
1425   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1426   if (VT == MVT::i1 && Op == ISD::SETCC)
1427     return false;
1428 
1429   return TargetLowering::isTypeDesirableForOp(Op, VT);
1430 }
1431 
1432 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1433                                                    const SDLoc &SL,
1434                                                    SDValue Chain,
1435                                                    uint64_t Offset) const {
1436   const DataLayout &DL = DAG.getDataLayout();
1437   MachineFunction &MF = DAG.getMachineFunction();
1438   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1439 
1440   const ArgDescriptor *InputPtrReg;
1441   const TargetRegisterClass *RC;
1442 
1443   std::tie(InputPtrReg, RC)
1444     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1445 
1446   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1447   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1448   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1449     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1450 
1451   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1452 }
1453 
1454 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1455                                             const SDLoc &SL) const {
1456   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1457                                                FIRST_IMPLICIT);
1458   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1459 }
1460 
1461 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1462                                          const SDLoc &SL, SDValue Val,
1463                                          bool Signed,
1464                                          const ISD::InputArg *Arg) const {
1465   // First, if it is a widened vector, narrow it.
1466   if (VT.isVector() &&
1467       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1468     EVT NarrowedVT =
1469         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1470                          VT.getVectorNumElements());
1471     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1472                       DAG.getConstant(0, SL, MVT::i32));
1473   }
1474 
1475   // Then convert the vector elements or scalar value.
1476   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1477       VT.bitsLT(MemVT)) {
1478     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1479     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1480   }
1481 
1482   if (MemVT.isFloatingPoint())
1483     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1484   else if (Signed)
1485     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1486   else
1487     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1488 
1489   return Val;
1490 }
1491 
1492 SDValue SITargetLowering::lowerKernargMemParameter(
1493   SelectionDAG &DAG, EVT VT, EVT MemVT,
1494   const SDLoc &SL, SDValue Chain,
1495   uint64_t Offset, unsigned Align, bool Signed,
1496   const ISD::InputArg *Arg) const {
1497   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1498 
1499   // Try to avoid using an extload by loading earlier than the argument address,
1500   // and extracting the relevant bits. The load should hopefully be merged with
1501   // the previous argument.
1502   if (MemVT.getStoreSize() < 4 && Align < 4) {
1503     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1504     int64_t AlignDownOffset = alignDown(Offset, 4);
1505     int64_t OffsetDiff = Offset - AlignDownOffset;
1506 
1507     EVT IntVT = MemVT.changeTypeToInteger();
1508 
1509     // TODO: If we passed in the base kernel offset we could have a better
1510     // alignment than 4, but we don't really need it.
1511     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1512     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1513                                MachineMemOperand::MODereferenceable |
1514                                MachineMemOperand::MOInvariant);
1515 
1516     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1517     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1518 
1519     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1520     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1521     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1522 
1523 
1524     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1525   }
1526 
1527   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1528   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1529                              MachineMemOperand::MODereferenceable |
1530                              MachineMemOperand::MOInvariant);
1531 
1532   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1533   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1534 }
1535 
1536 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1537                                               const SDLoc &SL, SDValue Chain,
1538                                               const ISD::InputArg &Arg) const {
1539   MachineFunction &MF = DAG.getMachineFunction();
1540   MachineFrameInfo &MFI = MF.getFrameInfo();
1541 
1542   if (Arg.Flags.isByVal()) {
1543     unsigned Size = Arg.Flags.getByValSize();
1544     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1545     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1546   }
1547 
1548   unsigned ArgOffset = VA.getLocMemOffset();
1549   unsigned ArgSize = VA.getValVT().getStoreSize();
1550 
1551   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1552 
1553   // Create load nodes to retrieve arguments from the stack.
1554   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1555   SDValue ArgValue;
1556 
1557   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1558   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1559   MVT MemVT = VA.getValVT();
1560 
1561   switch (VA.getLocInfo()) {
1562   default:
1563     break;
1564   case CCValAssign::BCvt:
1565     MemVT = VA.getLocVT();
1566     break;
1567   case CCValAssign::SExt:
1568     ExtType = ISD::SEXTLOAD;
1569     break;
1570   case CCValAssign::ZExt:
1571     ExtType = ISD::ZEXTLOAD;
1572     break;
1573   case CCValAssign::AExt:
1574     ExtType = ISD::EXTLOAD;
1575     break;
1576   }
1577 
1578   ArgValue = DAG.getExtLoad(
1579     ExtType, SL, VA.getLocVT(), Chain, FIN,
1580     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1581     MemVT);
1582   return ArgValue;
1583 }
1584 
1585 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1586   const SIMachineFunctionInfo &MFI,
1587   EVT VT,
1588   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1589   const ArgDescriptor *Reg;
1590   const TargetRegisterClass *RC;
1591 
1592   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1593   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1594 }
1595 
1596 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1597                                    CallingConv::ID CallConv,
1598                                    ArrayRef<ISD::InputArg> Ins,
1599                                    BitVector &Skipped,
1600                                    FunctionType *FType,
1601                                    SIMachineFunctionInfo *Info) {
1602   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1603     const ISD::InputArg *Arg = &Ins[I];
1604 
1605     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1606            "vector type argument should have been split");
1607 
1608     // First check if it's a PS input addr.
1609     if (CallConv == CallingConv::AMDGPU_PS &&
1610         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1611       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1612 
1613       // Inconveniently only the first part of the split is marked as isSplit,
1614       // so skip to the end. We only want to increment PSInputNum once for the
1615       // entire split argument.
1616       if (Arg->Flags.isSplit()) {
1617         while (!Arg->Flags.isSplitEnd()) {
1618           assert((!Arg->VT.isVector() ||
1619                   Arg->VT.getScalarSizeInBits() == 16) &&
1620                  "unexpected vector split in ps argument type");
1621           if (!SkipArg)
1622             Splits.push_back(*Arg);
1623           Arg = &Ins[++I];
1624         }
1625       }
1626 
1627       if (SkipArg) {
1628         // We can safely skip PS inputs.
1629         Skipped.set(Arg->getOrigArgIndex());
1630         ++PSInputNum;
1631         continue;
1632       }
1633 
1634       Info->markPSInputAllocated(PSInputNum);
1635       if (Arg->Used)
1636         Info->markPSInputEnabled(PSInputNum);
1637 
1638       ++PSInputNum;
1639     }
1640 
1641     Splits.push_back(*Arg);
1642   }
1643 }
1644 
1645 // Allocate special inputs passed in VGPRs.
1646 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1647                                                       MachineFunction &MF,
1648                                                       const SIRegisterInfo &TRI,
1649                                                       SIMachineFunctionInfo &Info) const {
1650   const LLT S32 = LLT::scalar(32);
1651   MachineRegisterInfo &MRI = MF.getRegInfo();
1652 
1653   if (Info.hasWorkItemIDX()) {
1654     Register Reg = AMDGPU::VGPR0;
1655     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1656 
1657     CCInfo.AllocateReg(Reg);
1658     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1659   }
1660 
1661   if (Info.hasWorkItemIDY()) {
1662     Register Reg = AMDGPU::VGPR1;
1663     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1664 
1665     CCInfo.AllocateReg(Reg);
1666     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1667   }
1668 
1669   if (Info.hasWorkItemIDZ()) {
1670     Register Reg = AMDGPU::VGPR2;
1671     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1672 
1673     CCInfo.AllocateReg(Reg);
1674     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1675   }
1676 }
1677 
1678 // Try to allocate a VGPR at the end of the argument list, or if no argument
1679 // VGPRs are left allocating a stack slot.
1680 // If \p Mask is is given it indicates bitfield position in the register.
1681 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1682 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1683                                          ArgDescriptor Arg = ArgDescriptor()) {
1684   if (Arg.isSet())
1685     return ArgDescriptor::createArg(Arg, Mask);
1686 
1687   ArrayRef<MCPhysReg> ArgVGPRs
1688     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1689   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1690   if (RegIdx == ArgVGPRs.size()) {
1691     // Spill to stack required.
1692     int64_t Offset = CCInfo.AllocateStack(4, 4);
1693 
1694     return ArgDescriptor::createStack(Offset, Mask);
1695   }
1696 
1697   unsigned Reg = ArgVGPRs[RegIdx];
1698   Reg = CCInfo.AllocateReg(Reg);
1699   assert(Reg != AMDGPU::NoRegister);
1700 
1701   MachineFunction &MF = CCInfo.getMachineFunction();
1702   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1703   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1704   return ArgDescriptor::createRegister(Reg, Mask);
1705 }
1706 
1707 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1708                                              const TargetRegisterClass *RC,
1709                                              unsigned NumArgRegs) {
1710   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1711   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1712   if (RegIdx == ArgSGPRs.size())
1713     report_fatal_error("ran out of SGPRs for arguments");
1714 
1715   unsigned Reg = ArgSGPRs[RegIdx];
1716   Reg = CCInfo.AllocateReg(Reg);
1717   assert(Reg != AMDGPU::NoRegister);
1718 
1719   MachineFunction &MF = CCInfo.getMachineFunction();
1720   MF.addLiveIn(Reg, RC);
1721   return ArgDescriptor::createRegister(Reg);
1722 }
1723 
1724 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1725   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1726 }
1727 
1728 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1729   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1730 }
1731 
1732 /// Allocate implicit function VGPR arguments at the end of allocated user
1733 /// arguments.
1734 void SITargetLowering::allocateSpecialInputVGPRs(
1735   CCState &CCInfo, MachineFunction &MF,
1736   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1737   const unsigned Mask = 0x3ff;
1738   ArgDescriptor Arg;
1739 
1740   if (Info.hasWorkItemIDX()) {
1741     Arg = allocateVGPR32Input(CCInfo, Mask);
1742     Info.setWorkItemIDX(Arg);
1743   }
1744 
1745   if (Info.hasWorkItemIDY()) {
1746     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1747     Info.setWorkItemIDY(Arg);
1748   }
1749 
1750   if (Info.hasWorkItemIDZ())
1751     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1752 }
1753 
1754 /// Allocate implicit function VGPR arguments in fixed registers.
1755 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1756   CCState &CCInfo, MachineFunction &MF,
1757   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1758   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1759   if (!Reg)
1760     report_fatal_error("failed to allocated VGPR for implicit arguments");
1761 
1762   const unsigned Mask = 0x3ff;
1763   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1764   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1765   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1766 }
1767 
1768 void SITargetLowering::allocateSpecialInputSGPRs(
1769   CCState &CCInfo,
1770   MachineFunction &MF,
1771   const SIRegisterInfo &TRI,
1772   SIMachineFunctionInfo &Info) const {
1773   auto &ArgInfo = Info.getArgInfo();
1774 
1775   // TODO: Unify handling with private memory pointers.
1776 
1777   if (Info.hasDispatchPtr())
1778     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1779 
1780   if (Info.hasQueuePtr())
1781     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1782 
1783   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1784   // constant offset from the kernarg segment.
1785   if (Info.hasImplicitArgPtr())
1786     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1787 
1788   if (Info.hasDispatchID())
1789     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1790 
1791   // flat_scratch_init is not applicable for non-kernel functions.
1792 
1793   if (Info.hasWorkGroupIDX())
1794     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1795 
1796   if (Info.hasWorkGroupIDY())
1797     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1798 
1799   if (Info.hasWorkGroupIDZ())
1800     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1801 }
1802 
1803 // Allocate special inputs passed in user SGPRs.
1804 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1805                                             MachineFunction &MF,
1806                                             const SIRegisterInfo &TRI,
1807                                             SIMachineFunctionInfo &Info) const {
1808   if (Info.hasImplicitBufferPtr()) {
1809     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1810     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1811     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1812   }
1813 
1814   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1815   if (Info.hasPrivateSegmentBuffer()) {
1816     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1817     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1818     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1819   }
1820 
1821   if (Info.hasDispatchPtr()) {
1822     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1823     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1824     CCInfo.AllocateReg(DispatchPtrReg);
1825   }
1826 
1827   if (Info.hasQueuePtr()) {
1828     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1829     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1830     CCInfo.AllocateReg(QueuePtrReg);
1831   }
1832 
1833   if (Info.hasKernargSegmentPtr()) {
1834     MachineRegisterInfo &MRI = MF.getRegInfo();
1835     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1836     CCInfo.AllocateReg(InputPtrReg);
1837 
1838     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1839     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1840   }
1841 
1842   if (Info.hasDispatchID()) {
1843     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1844     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1845     CCInfo.AllocateReg(DispatchIDReg);
1846   }
1847 
1848   if (Info.hasFlatScratchInit()) {
1849     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1850     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1851     CCInfo.AllocateReg(FlatScratchInitReg);
1852   }
1853 
1854   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1855   // these from the dispatch pointer.
1856 }
1857 
1858 // Allocate special input registers that are initialized per-wave.
1859 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1860                                            MachineFunction &MF,
1861                                            SIMachineFunctionInfo &Info,
1862                                            CallingConv::ID CallConv,
1863                                            bool IsShader) const {
1864   if (Info.hasWorkGroupIDX()) {
1865     unsigned Reg = Info.addWorkGroupIDX();
1866     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1867     CCInfo.AllocateReg(Reg);
1868   }
1869 
1870   if (Info.hasWorkGroupIDY()) {
1871     unsigned Reg = Info.addWorkGroupIDY();
1872     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1873     CCInfo.AllocateReg(Reg);
1874   }
1875 
1876   if (Info.hasWorkGroupIDZ()) {
1877     unsigned Reg = Info.addWorkGroupIDZ();
1878     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1879     CCInfo.AllocateReg(Reg);
1880   }
1881 
1882   if (Info.hasWorkGroupInfo()) {
1883     unsigned Reg = Info.addWorkGroupInfo();
1884     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1885     CCInfo.AllocateReg(Reg);
1886   }
1887 
1888   if (Info.hasPrivateSegmentWaveByteOffset()) {
1889     // Scratch wave offset passed in system SGPR.
1890     unsigned PrivateSegmentWaveByteOffsetReg;
1891 
1892     if (IsShader) {
1893       PrivateSegmentWaveByteOffsetReg =
1894         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1895 
1896       // This is true if the scratch wave byte offset doesn't have a fixed
1897       // location.
1898       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1899         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1900         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1901       }
1902     } else
1903       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1904 
1905     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1906     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1907   }
1908 }
1909 
1910 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1911                                      MachineFunction &MF,
1912                                      const SIRegisterInfo &TRI,
1913                                      SIMachineFunctionInfo &Info) {
1914   // Now that we've figured out where the scratch register inputs are, see if
1915   // should reserve the arguments and use them directly.
1916   MachineFrameInfo &MFI = MF.getFrameInfo();
1917   bool HasStackObjects = MFI.hasStackObjects();
1918   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1919 
1920   // Record that we know we have non-spill stack objects so we don't need to
1921   // check all stack objects later.
1922   if (HasStackObjects)
1923     Info.setHasNonSpillStackObjects(true);
1924 
1925   // Everything live out of a block is spilled with fast regalloc, so it's
1926   // almost certain that spilling will be required.
1927   if (TM.getOptLevel() == CodeGenOpt::None)
1928     HasStackObjects = true;
1929 
1930   // For now assume stack access is needed in any callee functions, so we need
1931   // the scratch registers to pass in.
1932   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1933 
1934   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1935     // If we have stack objects, we unquestionably need the private buffer
1936     // resource. For the Code Object V2 ABI, this will be the first 4 user
1937     // SGPR inputs. We can reserve those and use them directly.
1938 
1939     Register PrivateSegmentBufferReg =
1940         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1941     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1942   } else {
1943     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1944     // We tentatively reserve the last registers (skipping the last registers
1945     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1946     // we'll replace these with the ones immediately after those which were
1947     // really allocated. In the prologue copies will be inserted from the
1948     // argument to these reserved registers.
1949 
1950     // Without HSA, relocations are used for the scratch pointer and the
1951     // buffer resource setup is always inserted in the prologue. Scratch wave
1952     // offset is still in an input SGPR.
1953     Info.setScratchRSrcReg(ReservedBufferReg);
1954   }
1955 
1956   MachineRegisterInfo &MRI = MF.getRegInfo();
1957 
1958   // For entry functions we have to set up the stack pointer if we use it,
1959   // whereas non-entry functions get this "for free". This means there is no
1960   // intrinsic advantage to using S32 over S34 in cases where we do not have
1961   // calls but do need a frame pointer (i.e. if we are requested to have one
1962   // because frame pointer elimination is disabled). To keep things simple we
1963   // only ever use S32 as the call ABI stack pointer, and so using it does not
1964   // imply we need a separate frame pointer.
1965   //
1966   // Try to use s32 as the SP, but move it if it would interfere with input
1967   // arguments. This won't work with calls though.
1968   //
1969   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1970   // registers.
1971   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1972     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1973   } else {
1974     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1975 
1976     if (MFI.hasCalls())
1977       report_fatal_error("call in graphics shader with too many input SGPRs");
1978 
1979     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1980       if (!MRI.isLiveIn(Reg)) {
1981         Info.setStackPtrOffsetReg(Reg);
1982         break;
1983       }
1984     }
1985 
1986     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1987       report_fatal_error("failed to find register for SP");
1988   }
1989 
1990   // hasFP should be accurate for entry functions even before the frame is
1991   // finalized, because it does not rely on the known stack size, only
1992   // properties like whether variable sized objects are present.
1993   if (ST.getFrameLowering()->hasFP(MF)) {
1994     Info.setFrameOffsetReg(AMDGPU::SGPR33);
1995   }
1996 }
1997 
1998 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1999   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2000   return !Info->isEntryFunction();
2001 }
2002 
2003 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2004 
2005 }
2006 
2007 void SITargetLowering::insertCopiesSplitCSR(
2008   MachineBasicBlock *Entry,
2009   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2010   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2011 
2012   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2013   if (!IStart)
2014     return;
2015 
2016   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2017   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2018   MachineBasicBlock::iterator MBBI = Entry->begin();
2019   for (const MCPhysReg *I = IStart; *I; ++I) {
2020     const TargetRegisterClass *RC = nullptr;
2021     if (AMDGPU::SReg_64RegClass.contains(*I))
2022       RC = &AMDGPU::SGPR_64RegClass;
2023     else if (AMDGPU::SReg_32RegClass.contains(*I))
2024       RC = &AMDGPU::SGPR_32RegClass;
2025     else
2026       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2027 
2028     Register NewVR = MRI->createVirtualRegister(RC);
2029     // Create copy from CSR to a virtual register.
2030     Entry->addLiveIn(*I);
2031     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2032       .addReg(*I);
2033 
2034     // Insert the copy-back instructions right before the terminator.
2035     for (auto *Exit : Exits)
2036       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2037               TII->get(TargetOpcode::COPY), *I)
2038         .addReg(NewVR);
2039   }
2040 }
2041 
2042 SDValue SITargetLowering::LowerFormalArguments(
2043     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2044     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2045     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2046   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2047 
2048   MachineFunction &MF = DAG.getMachineFunction();
2049   const Function &Fn = MF.getFunction();
2050   FunctionType *FType = MF.getFunction().getFunctionType();
2051   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2052 
2053   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2054     DiagnosticInfoUnsupported NoGraphicsHSA(
2055         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2056     DAG.getContext()->diagnose(NoGraphicsHSA);
2057     return DAG.getEntryNode();
2058   }
2059 
2060   SmallVector<ISD::InputArg, 16> Splits;
2061   SmallVector<CCValAssign, 16> ArgLocs;
2062   BitVector Skipped(Ins.size());
2063   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2064                  *DAG.getContext());
2065 
2066   bool IsShader = AMDGPU::isShader(CallConv);
2067   bool IsKernel = AMDGPU::isKernel(CallConv);
2068   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2069 
2070   if (IsShader) {
2071     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2072 
2073     // At least one interpolation mode must be enabled or else the GPU will
2074     // hang.
2075     //
2076     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2077     // set PSInputAddr, the user wants to enable some bits after the compilation
2078     // based on run-time states. Since we can't know what the final PSInputEna
2079     // will look like, so we shouldn't do anything here and the user should take
2080     // responsibility for the correct programming.
2081     //
2082     // Otherwise, the following restrictions apply:
2083     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2084     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2085     //   enabled too.
2086     if (CallConv == CallingConv::AMDGPU_PS) {
2087       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2088            ((Info->getPSInputAddr() & 0xF) == 0 &&
2089             Info->isPSInputAllocated(11))) {
2090         CCInfo.AllocateReg(AMDGPU::VGPR0);
2091         CCInfo.AllocateReg(AMDGPU::VGPR1);
2092         Info->markPSInputAllocated(0);
2093         Info->markPSInputEnabled(0);
2094       }
2095       if (Subtarget->isAmdPalOS()) {
2096         // For isAmdPalOS, the user does not enable some bits after compilation
2097         // based on run-time states; the register values being generated here are
2098         // the final ones set in hardware. Therefore we need to apply the
2099         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2100         // a bit is set in PSInputAddr but not PSInputEnable is where the
2101         // frontend set up an input arg for a particular interpolation mode, but
2102         // nothing uses that input arg. Really we should have an earlier pass
2103         // that removes such an arg.)
2104         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2105         if ((PsInputBits & 0x7F) == 0 ||
2106             ((PsInputBits & 0xF) == 0 &&
2107              (PsInputBits >> 11 & 1)))
2108           Info->markPSInputEnabled(
2109               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2110       }
2111     }
2112 
2113     assert(!Info->hasDispatchPtr() &&
2114            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2115            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2116            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2117            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2118            !Info->hasWorkItemIDZ());
2119   } else if (IsKernel) {
2120     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2121   } else {
2122     Splits.append(Ins.begin(), Ins.end());
2123   }
2124 
2125   if (IsEntryFunc) {
2126     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2127     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2128   } else {
2129     // For the fixed ABI, pass workitem IDs in the last argument register.
2130     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2131       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2132   }
2133 
2134   if (IsKernel) {
2135     analyzeFormalArgumentsCompute(CCInfo, Ins);
2136   } else {
2137     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2138     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2139   }
2140 
2141   SmallVector<SDValue, 16> Chains;
2142 
2143   // FIXME: This is the minimum kernel argument alignment. We should improve
2144   // this to the maximum alignment of the arguments.
2145   //
2146   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2147   // kern arg offset.
2148   const unsigned KernelArgBaseAlign = 16;
2149 
2150    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2151     const ISD::InputArg &Arg = Ins[i];
2152     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2153       InVals.push_back(DAG.getUNDEF(Arg.VT));
2154       continue;
2155     }
2156 
2157     CCValAssign &VA = ArgLocs[ArgIdx++];
2158     MVT VT = VA.getLocVT();
2159 
2160     if (IsEntryFunc && VA.isMemLoc()) {
2161       VT = Ins[i].VT;
2162       EVT MemVT = VA.getLocVT();
2163 
2164       const uint64_t Offset = VA.getLocMemOffset();
2165       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2166 
2167       SDValue Arg = lowerKernargMemParameter(
2168         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2169       Chains.push_back(Arg.getValue(1));
2170 
2171       auto *ParamTy =
2172         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2173       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2174           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2175                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2176         // On SI local pointers are just offsets into LDS, so they are always
2177         // less than 16-bits.  On CI and newer they could potentially be
2178         // real pointers, so we can't guarantee their size.
2179         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2180                           DAG.getValueType(MVT::i16));
2181       }
2182 
2183       InVals.push_back(Arg);
2184       continue;
2185     } else if (!IsEntryFunc && VA.isMemLoc()) {
2186       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2187       InVals.push_back(Val);
2188       if (!Arg.Flags.isByVal())
2189         Chains.push_back(Val.getValue(1));
2190       continue;
2191     }
2192 
2193     assert(VA.isRegLoc() && "Parameter must be in a register!");
2194 
2195     Register Reg = VA.getLocReg();
2196     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2197     EVT ValVT = VA.getValVT();
2198 
2199     Reg = MF.addLiveIn(Reg, RC);
2200     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2201 
2202     if (Arg.Flags.isSRet()) {
2203       // The return object should be reasonably addressable.
2204 
2205       // FIXME: This helps when the return is a real sret. If it is a
2206       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2207       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2208       unsigned NumBits
2209         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2210       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2211         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2212     }
2213 
2214     // If this is an 8 or 16-bit value, it is really passed promoted
2215     // to 32 bits. Insert an assert[sz]ext to capture this, then
2216     // truncate to the right size.
2217     switch (VA.getLocInfo()) {
2218     case CCValAssign::Full:
2219       break;
2220     case CCValAssign::BCvt:
2221       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2222       break;
2223     case CCValAssign::SExt:
2224       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2225                         DAG.getValueType(ValVT));
2226       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2227       break;
2228     case CCValAssign::ZExt:
2229       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2230                         DAG.getValueType(ValVT));
2231       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2232       break;
2233     case CCValAssign::AExt:
2234       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2235       break;
2236     default:
2237       llvm_unreachable("Unknown loc info!");
2238     }
2239 
2240     InVals.push_back(Val);
2241   }
2242 
2243   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2244     // Special inputs come after user arguments.
2245     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2246   }
2247 
2248   // Start adding system SGPRs.
2249   if (IsEntryFunc) {
2250     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2251   } else {
2252     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2253     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2254   }
2255 
2256   auto &ArgUsageInfo =
2257     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2258   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2259 
2260   unsigned StackArgSize = CCInfo.getNextStackOffset();
2261   Info->setBytesInStackArgArea(StackArgSize);
2262 
2263   return Chains.empty() ? Chain :
2264     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2265 }
2266 
2267 // TODO: If return values can't fit in registers, we should return as many as
2268 // possible in registers before passing on stack.
2269 bool SITargetLowering::CanLowerReturn(
2270   CallingConv::ID CallConv,
2271   MachineFunction &MF, bool IsVarArg,
2272   const SmallVectorImpl<ISD::OutputArg> &Outs,
2273   LLVMContext &Context) const {
2274   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2275   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2276   // for shaders. Vector types should be explicitly handled by CC.
2277   if (AMDGPU::isEntryFunctionCC(CallConv))
2278     return true;
2279 
2280   SmallVector<CCValAssign, 16> RVLocs;
2281   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2282   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2283 }
2284 
2285 SDValue
2286 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2287                               bool isVarArg,
2288                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2289                               const SmallVectorImpl<SDValue> &OutVals,
2290                               const SDLoc &DL, SelectionDAG &DAG) const {
2291   MachineFunction &MF = DAG.getMachineFunction();
2292   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2293 
2294   if (AMDGPU::isKernel(CallConv)) {
2295     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2296                                              OutVals, DL, DAG);
2297   }
2298 
2299   bool IsShader = AMDGPU::isShader(CallConv);
2300 
2301   Info->setIfReturnsVoid(Outs.empty());
2302   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2303 
2304   // CCValAssign - represent the assignment of the return value to a location.
2305   SmallVector<CCValAssign, 48> RVLocs;
2306   SmallVector<ISD::OutputArg, 48> Splits;
2307 
2308   // CCState - Info about the registers and stack slots.
2309   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2310                  *DAG.getContext());
2311 
2312   // Analyze outgoing return values.
2313   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2314 
2315   SDValue Flag;
2316   SmallVector<SDValue, 48> RetOps;
2317   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2318 
2319   // Add return address for callable functions.
2320   if (!Info->isEntryFunction()) {
2321     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2322     SDValue ReturnAddrReg = CreateLiveInRegister(
2323       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2324 
2325     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2326         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2327         MVT::i64);
2328     Chain =
2329         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2330     Flag = Chain.getValue(1);
2331     RetOps.push_back(ReturnAddrVirtualReg);
2332   }
2333 
2334   // Copy the result values into the output registers.
2335   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2336        ++I, ++RealRVLocIdx) {
2337     CCValAssign &VA = RVLocs[I];
2338     assert(VA.isRegLoc() && "Can only return in registers!");
2339     // TODO: Partially return in registers if return values don't fit.
2340     SDValue Arg = OutVals[RealRVLocIdx];
2341 
2342     // Copied from other backends.
2343     switch (VA.getLocInfo()) {
2344     case CCValAssign::Full:
2345       break;
2346     case CCValAssign::BCvt:
2347       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2348       break;
2349     case CCValAssign::SExt:
2350       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2351       break;
2352     case CCValAssign::ZExt:
2353       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2354       break;
2355     case CCValAssign::AExt:
2356       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2357       break;
2358     default:
2359       llvm_unreachable("Unknown loc info!");
2360     }
2361 
2362     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2363     Flag = Chain.getValue(1);
2364     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2365   }
2366 
2367   // FIXME: Does sret work properly?
2368   if (!Info->isEntryFunction()) {
2369     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2370     const MCPhysReg *I =
2371       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2372     if (I) {
2373       for (; *I; ++I) {
2374         if (AMDGPU::SReg_64RegClass.contains(*I))
2375           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2376         else if (AMDGPU::SReg_32RegClass.contains(*I))
2377           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2378         else
2379           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2380       }
2381     }
2382   }
2383 
2384   // Update chain and glue.
2385   RetOps[0] = Chain;
2386   if (Flag.getNode())
2387     RetOps.push_back(Flag);
2388 
2389   unsigned Opc = AMDGPUISD::ENDPGM;
2390   if (!IsWaveEnd)
2391     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2392   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2393 }
2394 
2395 SDValue SITargetLowering::LowerCallResult(
2396     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2397     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2398     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2399     SDValue ThisVal) const {
2400   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2401 
2402   // Assign locations to each value returned by this call.
2403   SmallVector<CCValAssign, 16> RVLocs;
2404   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2405                  *DAG.getContext());
2406   CCInfo.AnalyzeCallResult(Ins, RetCC);
2407 
2408   // Copy all of the result registers out of their specified physreg.
2409   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2410     CCValAssign VA = RVLocs[i];
2411     SDValue Val;
2412 
2413     if (VA.isRegLoc()) {
2414       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2415       Chain = Val.getValue(1);
2416       InFlag = Val.getValue(2);
2417     } else if (VA.isMemLoc()) {
2418       report_fatal_error("TODO: return values in memory");
2419     } else
2420       llvm_unreachable("unknown argument location type");
2421 
2422     switch (VA.getLocInfo()) {
2423     case CCValAssign::Full:
2424       break;
2425     case CCValAssign::BCvt:
2426       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2427       break;
2428     case CCValAssign::ZExt:
2429       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2430                         DAG.getValueType(VA.getValVT()));
2431       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2432       break;
2433     case CCValAssign::SExt:
2434       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2435                         DAG.getValueType(VA.getValVT()));
2436       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2437       break;
2438     case CCValAssign::AExt:
2439       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2440       break;
2441     default:
2442       llvm_unreachable("Unknown loc info!");
2443     }
2444 
2445     InVals.push_back(Val);
2446   }
2447 
2448   return Chain;
2449 }
2450 
2451 // Add code to pass special inputs required depending on used features separate
2452 // from the explicit user arguments present in the IR.
2453 void SITargetLowering::passSpecialInputs(
2454     CallLoweringInfo &CLI,
2455     CCState &CCInfo,
2456     const SIMachineFunctionInfo &Info,
2457     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2458     SmallVectorImpl<SDValue> &MemOpChains,
2459     SDValue Chain) const {
2460   // If we don't have a call site, this was a call inserted by
2461   // legalization. These can never use special inputs.
2462   if (!CLI.CS)
2463     return;
2464 
2465   SelectionDAG &DAG = CLI.DAG;
2466   const SDLoc &DL = CLI.DL;
2467 
2468   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2469   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2470 
2471   const AMDGPUFunctionArgInfo *CalleeArgInfo
2472     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2473   if (const Function *CalleeFunc = CLI.CS.getCalledFunction()) {
2474     auto &ArgUsageInfo =
2475       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2476     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2477   }
2478 
2479   // TODO: Unify with private memory register handling. This is complicated by
2480   // the fact that at least in kernels, the input argument is not necessarily
2481   // in the same location as the input.
2482   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2483     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2484     AMDGPUFunctionArgInfo::QUEUE_PTR,
2485     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2486     AMDGPUFunctionArgInfo::DISPATCH_ID,
2487     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2488     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2489     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2490   };
2491 
2492   for (auto InputID : InputRegs) {
2493     const ArgDescriptor *OutgoingArg;
2494     const TargetRegisterClass *ArgRC;
2495 
2496     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID);
2497     if (!OutgoingArg)
2498       continue;
2499 
2500     const ArgDescriptor *IncomingArg;
2501     const TargetRegisterClass *IncomingArgRC;
2502     std::tie(IncomingArg, IncomingArgRC)
2503       = CallerArgInfo.getPreloadedValue(InputID);
2504     assert(IncomingArgRC == ArgRC);
2505 
2506     // All special arguments are ints for now.
2507     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2508     SDValue InputReg;
2509 
2510     if (IncomingArg) {
2511       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2512     } else {
2513       // The implicit arg ptr is special because it doesn't have a corresponding
2514       // input for kernels, and is computed from the kernarg segment pointer.
2515       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2516       InputReg = getImplicitArgPtr(DAG, DL);
2517     }
2518 
2519     if (OutgoingArg->isRegister()) {
2520       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2521       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2522         report_fatal_error("failed to allocate implicit input argument");
2523     } else {
2524       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2525       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2526                                               SpecialArgOffset);
2527       MemOpChains.push_back(ArgStore);
2528     }
2529   }
2530 
2531   // Pack workitem IDs into a single register or pass it as is if already
2532   // packed.
2533   const ArgDescriptor *OutgoingArg;
2534   const TargetRegisterClass *ArgRC;
2535 
2536   std::tie(OutgoingArg, ArgRC) =
2537     CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2538   if (!OutgoingArg)
2539     std::tie(OutgoingArg, ArgRC) =
2540       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2541   if (!OutgoingArg)
2542     std::tie(OutgoingArg, ArgRC) =
2543       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2544   if (!OutgoingArg)
2545     return;
2546 
2547   const ArgDescriptor *IncomingArgX
2548     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2549   const ArgDescriptor *IncomingArgY
2550     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2551   const ArgDescriptor *IncomingArgZ
2552     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2553 
2554   SDValue InputReg;
2555   SDLoc SL;
2556 
2557   // If incoming ids are not packed we need to pack them.
2558   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2559     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2560 
2561   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2562     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2563     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2564                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2565     InputReg = InputReg.getNode() ?
2566                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2567   }
2568 
2569   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2570     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2571     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2572                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2573     InputReg = InputReg.getNode() ?
2574                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2575   }
2576 
2577   if (!InputReg.getNode()) {
2578     // Workitem ids are already packed, any of present incoming arguments
2579     // will carry all required fields.
2580     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2581       IncomingArgX ? *IncomingArgX :
2582       IncomingArgY ? *IncomingArgY :
2583                      *IncomingArgZ, ~0u);
2584     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2585   }
2586 
2587   if (OutgoingArg->isRegister()) {
2588     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2589     CCInfo.AllocateReg(OutgoingArg->getRegister());
2590   } else {
2591     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2592     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2593                                             SpecialArgOffset);
2594     MemOpChains.push_back(ArgStore);
2595   }
2596 }
2597 
2598 static bool canGuaranteeTCO(CallingConv::ID CC) {
2599   return CC == CallingConv::Fast;
2600 }
2601 
2602 /// Return true if we might ever do TCO for calls with this calling convention.
2603 static bool mayTailCallThisCC(CallingConv::ID CC) {
2604   switch (CC) {
2605   case CallingConv::C:
2606     return true;
2607   default:
2608     return canGuaranteeTCO(CC);
2609   }
2610 }
2611 
2612 bool SITargetLowering::isEligibleForTailCallOptimization(
2613     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2614     const SmallVectorImpl<ISD::OutputArg> &Outs,
2615     const SmallVectorImpl<SDValue> &OutVals,
2616     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2617   if (!mayTailCallThisCC(CalleeCC))
2618     return false;
2619 
2620   MachineFunction &MF = DAG.getMachineFunction();
2621   const Function &CallerF = MF.getFunction();
2622   CallingConv::ID CallerCC = CallerF.getCallingConv();
2623   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2624   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2625 
2626   // Kernels aren't callable, and don't have a live in return address so it
2627   // doesn't make sense to do a tail call with entry functions.
2628   if (!CallerPreserved)
2629     return false;
2630 
2631   bool CCMatch = CallerCC == CalleeCC;
2632 
2633   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2634     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2635       return true;
2636     return false;
2637   }
2638 
2639   // TODO: Can we handle var args?
2640   if (IsVarArg)
2641     return false;
2642 
2643   for (const Argument &Arg : CallerF.args()) {
2644     if (Arg.hasByValAttr())
2645       return false;
2646   }
2647 
2648   LLVMContext &Ctx = *DAG.getContext();
2649 
2650   // Check that the call results are passed in the same way.
2651   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2652                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2653                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2654     return false;
2655 
2656   // The callee has to preserve all registers the caller needs to preserve.
2657   if (!CCMatch) {
2658     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2659     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2660       return false;
2661   }
2662 
2663   // Nothing more to check if the callee is taking no arguments.
2664   if (Outs.empty())
2665     return true;
2666 
2667   SmallVector<CCValAssign, 16> ArgLocs;
2668   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2669 
2670   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2671 
2672   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2673   // If the stack arguments for this call do not fit into our own save area then
2674   // the call cannot be made tail.
2675   // TODO: Is this really necessary?
2676   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2677     return false;
2678 
2679   const MachineRegisterInfo &MRI = MF.getRegInfo();
2680   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2681 }
2682 
2683 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2684   if (!CI->isTailCall())
2685     return false;
2686 
2687   const Function *ParentFn = CI->getParent()->getParent();
2688   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2689     return false;
2690   return true;
2691 }
2692 
2693 // The wave scratch offset register is used as the global base pointer.
2694 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2695                                     SmallVectorImpl<SDValue> &InVals) const {
2696   SelectionDAG &DAG = CLI.DAG;
2697   const SDLoc &DL = CLI.DL;
2698   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2699   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2700   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2701   SDValue Chain = CLI.Chain;
2702   SDValue Callee = CLI.Callee;
2703   bool &IsTailCall = CLI.IsTailCall;
2704   CallingConv::ID CallConv = CLI.CallConv;
2705   bool IsVarArg = CLI.IsVarArg;
2706   bool IsSibCall = false;
2707   bool IsThisReturn = false;
2708   MachineFunction &MF = DAG.getMachineFunction();
2709 
2710   if (Callee.isUndef() || isNullConstant(Callee)) {
2711     if (!CLI.IsTailCall) {
2712       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2713         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2714     }
2715 
2716     return Chain;
2717   }
2718 
2719   if (IsVarArg) {
2720     return lowerUnhandledCall(CLI, InVals,
2721                               "unsupported call to variadic function ");
2722   }
2723 
2724   if (!CLI.CS.getInstruction())
2725     report_fatal_error("unsupported libcall legalization");
2726 
2727   if (!AMDGPUTargetMachine::EnableFixedFunctionABI && !CLI.CS.getCalledFunction()) {
2728     return lowerUnhandledCall(CLI, InVals,
2729                               "unsupported indirect call to function ");
2730   }
2731 
2732   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2733     return lowerUnhandledCall(CLI, InVals,
2734                               "unsupported required tail call to function ");
2735   }
2736 
2737   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2738     // Note the issue is with the CC of the calling function, not of the call
2739     // itself.
2740     return lowerUnhandledCall(CLI, InVals,
2741                           "unsupported call from graphics shader of function ");
2742   }
2743 
2744   if (IsTailCall) {
2745     IsTailCall = isEligibleForTailCallOptimization(
2746       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2747     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2748       report_fatal_error("failed to perform tail call elimination on a call "
2749                          "site marked musttail");
2750     }
2751 
2752     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2753 
2754     // A sibling call is one where we're under the usual C ABI and not planning
2755     // to change that but can still do a tail call:
2756     if (!TailCallOpt && IsTailCall)
2757       IsSibCall = true;
2758 
2759     if (IsTailCall)
2760       ++NumTailCalls;
2761   }
2762 
2763   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2764   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2765   SmallVector<SDValue, 8> MemOpChains;
2766 
2767   // Analyze operands of the call, assigning locations to each operand.
2768   SmallVector<CCValAssign, 16> ArgLocs;
2769   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2770   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2771 
2772   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2773     // With a fixed ABI, allocate fixed registers before user arguments.
2774     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2775   }
2776 
2777   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2778 
2779   // Get a count of how many bytes are to be pushed on the stack.
2780   unsigned NumBytes = CCInfo.getNextStackOffset();
2781 
2782   if (IsSibCall) {
2783     // Since we're not changing the ABI to make this a tail call, the memory
2784     // operands are already available in the caller's incoming argument space.
2785     NumBytes = 0;
2786   }
2787 
2788   // FPDiff is the byte offset of the call's argument area from the callee's.
2789   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2790   // by this amount for a tail call. In a sibling call it must be 0 because the
2791   // caller will deallocate the entire stack and the callee still expects its
2792   // arguments to begin at SP+0. Completely unused for non-tail calls.
2793   int32_t FPDiff = 0;
2794   MachineFrameInfo &MFI = MF.getFrameInfo();
2795 
2796   // Adjust the stack pointer for the new arguments...
2797   // These operations are automatically eliminated by the prolog/epilog pass
2798   if (!IsSibCall) {
2799     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2800 
2801     SmallVector<SDValue, 4> CopyFromChains;
2802 
2803     // In the HSA case, this should be an identity copy.
2804     SDValue ScratchRSrcReg
2805       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2806     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2807     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2808     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2809   }
2810 
2811   MVT PtrVT = MVT::i32;
2812 
2813   // Walk the register/memloc assignments, inserting copies/loads.
2814   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2815     CCValAssign &VA = ArgLocs[i];
2816     SDValue Arg = OutVals[i];
2817 
2818     // Promote the value if needed.
2819     switch (VA.getLocInfo()) {
2820     case CCValAssign::Full:
2821       break;
2822     case CCValAssign::BCvt:
2823       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2824       break;
2825     case CCValAssign::ZExt:
2826       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2827       break;
2828     case CCValAssign::SExt:
2829       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2830       break;
2831     case CCValAssign::AExt:
2832       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2833       break;
2834     case CCValAssign::FPExt:
2835       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2836       break;
2837     default:
2838       llvm_unreachable("Unknown loc info!");
2839     }
2840 
2841     if (VA.isRegLoc()) {
2842       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2843     } else {
2844       assert(VA.isMemLoc());
2845 
2846       SDValue DstAddr;
2847       MachinePointerInfo DstInfo;
2848 
2849       unsigned LocMemOffset = VA.getLocMemOffset();
2850       int32_t Offset = LocMemOffset;
2851 
2852       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2853       MaybeAlign Alignment;
2854 
2855       if (IsTailCall) {
2856         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2857         unsigned OpSize = Flags.isByVal() ?
2858           Flags.getByValSize() : VA.getValVT().getStoreSize();
2859 
2860         // FIXME: We can have better than the minimum byval required alignment.
2861         Alignment =
2862             Flags.isByVal()
2863                 ? Flags.getNonZeroByValAlign()
2864                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2865 
2866         Offset = Offset + FPDiff;
2867         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2868 
2869         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2870         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2871 
2872         // Make sure any stack arguments overlapping with where we're storing
2873         // are loaded before this eventual operation. Otherwise they'll be
2874         // clobbered.
2875 
2876         // FIXME: Why is this really necessary? This seems to just result in a
2877         // lot of code to copy the stack and write them back to the same
2878         // locations, which are supposed to be immutable?
2879         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2880       } else {
2881         DstAddr = PtrOff;
2882         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2883         Alignment =
2884             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2885       }
2886 
2887       if (Outs[i].Flags.isByVal()) {
2888         SDValue SizeNode =
2889             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2890         SDValue Cpy =
2891             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2892                           Outs[i].Flags.getNonZeroByValAlign(),
2893                           /*isVol = */ false, /*AlwaysInline = */ true,
2894                           /*isTailCall = */ false, DstInfo,
2895                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2896 
2897         MemOpChains.push_back(Cpy);
2898       } else {
2899         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2900                                      Alignment ? Alignment->value() : 0);
2901         MemOpChains.push_back(Store);
2902       }
2903     }
2904   }
2905 
2906   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
2907     // Copy special input registers after user input arguments.
2908     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2909   }
2910 
2911   if (!MemOpChains.empty())
2912     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2913 
2914   // Build a sequence of copy-to-reg nodes chained together with token chain
2915   // and flag operands which copy the outgoing args into the appropriate regs.
2916   SDValue InFlag;
2917   for (auto &RegToPass : RegsToPass) {
2918     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2919                              RegToPass.second, InFlag);
2920     InFlag = Chain.getValue(1);
2921   }
2922 
2923 
2924   SDValue PhysReturnAddrReg;
2925   if (IsTailCall) {
2926     // Since the return is being combined with the call, we need to pass on the
2927     // return address.
2928 
2929     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2930     SDValue ReturnAddrReg = CreateLiveInRegister(
2931       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2932 
2933     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2934                                         MVT::i64);
2935     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2936     InFlag = Chain.getValue(1);
2937   }
2938 
2939   // We don't usually want to end the call-sequence here because we would tidy
2940   // the frame up *after* the call, however in the ABI-changing tail-call case
2941   // we've carefully laid out the parameters so that when sp is reset they'll be
2942   // in the correct location.
2943   if (IsTailCall && !IsSibCall) {
2944     Chain = DAG.getCALLSEQ_END(Chain,
2945                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2946                                DAG.getTargetConstant(0, DL, MVT::i32),
2947                                InFlag, DL);
2948     InFlag = Chain.getValue(1);
2949   }
2950 
2951   std::vector<SDValue> Ops;
2952   Ops.push_back(Chain);
2953   Ops.push_back(Callee);
2954   // Add a redundant copy of the callee global which will not be legalized, as
2955   // we need direct access to the callee later.
2956   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
2957     const GlobalValue *GV = GSD->getGlobal();
2958     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2959   } else {
2960     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
2961   }
2962 
2963   if (IsTailCall) {
2964     // Each tail call may have to adjust the stack by a different amount, so
2965     // this information must travel along with the operation for eventual
2966     // consumption by emitEpilogue.
2967     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2968 
2969     Ops.push_back(PhysReturnAddrReg);
2970   }
2971 
2972   // Add argument registers to the end of the list so that they are known live
2973   // into the call.
2974   for (auto &RegToPass : RegsToPass) {
2975     Ops.push_back(DAG.getRegister(RegToPass.first,
2976                                   RegToPass.second.getValueType()));
2977   }
2978 
2979   // Add a register mask operand representing the call-preserved registers.
2980 
2981   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2982   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2983   assert(Mask && "Missing call preserved mask for calling convention");
2984   Ops.push_back(DAG.getRegisterMask(Mask));
2985 
2986   if (InFlag.getNode())
2987     Ops.push_back(InFlag);
2988 
2989   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2990 
2991   // If we're doing a tall call, use a TC_RETURN here rather than an
2992   // actual call instruction.
2993   if (IsTailCall) {
2994     MFI.setHasTailCall();
2995     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2996   }
2997 
2998   // Returns a chain and a flag for retval copy to use.
2999   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3000   Chain = Call.getValue(0);
3001   InFlag = Call.getValue(1);
3002 
3003   uint64_t CalleePopBytes = NumBytes;
3004   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3005                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3006                              InFlag, DL);
3007   if (!Ins.empty())
3008     InFlag = Chain.getValue(1);
3009 
3010   // Handle result values, copying them out of physregs into vregs that we
3011   // return.
3012   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3013                          InVals, IsThisReturn,
3014                          IsThisReturn ? OutVals[0] : SDValue());
3015 }
3016 
3017 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3018                                              const MachineFunction &MF) const {
3019   Register Reg = StringSwitch<Register>(RegName)
3020     .Case("m0", AMDGPU::M0)
3021     .Case("exec", AMDGPU::EXEC)
3022     .Case("exec_lo", AMDGPU::EXEC_LO)
3023     .Case("exec_hi", AMDGPU::EXEC_HI)
3024     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3025     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3026     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3027     .Default(Register());
3028 
3029   if (Reg == AMDGPU::NoRegister) {
3030     report_fatal_error(Twine("invalid register name \""
3031                              + StringRef(RegName)  + "\"."));
3032 
3033   }
3034 
3035   if (!Subtarget->hasFlatScrRegister() &&
3036        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3037     report_fatal_error(Twine("invalid register \""
3038                              + StringRef(RegName)  + "\" for subtarget."));
3039   }
3040 
3041   switch (Reg) {
3042   case AMDGPU::M0:
3043   case AMDGPU::EXEC_LO:
3044   case AMDGPU::EXEC_HI:
3045   case AMDGPU::FLAT_SCR_LO:
3046   case AMDGPU::FLAT_SCR_HI:
3047     if (VT.getSizeInBits() == 32)
3048       return Reg;
3049     break;
3050   case AMDGPU::EXEC:
3051   case AMDGPU::FLAT_SCR:
3052     if (VT.getSizeInBits() == 64)
3053       return Reg;
3054     break;
3055   default:
3056     llvm_unreachable("missing register type checking");
3057   }
3058 
3059   report_fatal_error(Twine("invalid type for register \""
3060                            + StringRef(RegName) + "\"."));
3061 }
3062 
3063 // If kill is not the last instruction, split the block so kill is always a
3064 // proper terminator.
3065 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3066                                                     MachineBasicBlock *BB) const {
3067   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3068 
3069   MachineBasicBlock::iterator SplitPoint(&MI);
3070   ++SplitPoint;
3071 
3072   if (SplitPoint == BB->end()) {
3073     // Don't bother with a new block.
3074     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3075     return BB;
3076   }
3077 
3078   MachineFunction *MF = BB->getParent();
3079   MachineBasicBlock *SplitBB
3080     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3081 
3082   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3083   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3084 
3085   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3086   BB->addSuccessor(SplitBB);
3087 
3088   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3089   return SplitBB;
3090 }
3091 
3092 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3093 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3094 // be the first instruction in the remainder block.
3095 //
3096 /// \returns { LoopBody, Remainder }
3097 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3098 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3099   MachineFunction *MF = MBB.getParent();
3100   MachineBasicBlock::iterator I(&MI);
3101 
3102   // To insert the loop we need to split the block. Move everything after this
3103   // point to a new block, and insert a new empty block between the two.
3104   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3105   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3106   MachineFunction::iterator MBBI(MBB);
3107   ++MBBI;
3108 
3109   MF->insert(MBBI, LoopBB);
3110   MF->insert(MBBI, RemainderBB);
3111 
3112   LoopBB->addSuccessor(LoopBB);
3113   LoopBB->addSuccessor(RemainderBB);
3114 
3115   // Move the rest of the block into a new block.
3116   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3117 
3118   if (InstInLoop) {
3119     auto Next = std::next(I);
3120 
3121     // Move instruction to loop body.
3122     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3123 
3124     // Move the rest of the block.
3125     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3126   } else {
3127     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3128   }
3129 
3130   MBB.addSuccessor(LoopBB);
3131 
3132   return std::make_pair(LoopBB, RemainderBB);
3133 }
3134 
3135 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3136 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3137   MachineBasicBlock *MBB = MI.getParent();
3138   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3139   auto I = MI.getIterator();
3140   auto E = std::next(I);
3141 
3142   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3143     .addImm(0);
3144 
3145   MIBundleBuilder Bundler(*MBB, I, E);
3146   finalizeBundle(*MBB, Bundler.begin());
3147 }
3148 
3149 MachineBasicBlock *
3150 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3151                                          MachineBasicBlock *BB) const {
3152   const DebugLoc &DL = MI.getDebugLoc();
3153 
3154   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3155 
3156   MachineBasicBlock *LoopBB;
3157   MachineBasicBlock *RemainderBB;
3158   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3159 
3160   // Apparently kill flags are only valid if the def is in the same block?
3161   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3162     Src->setIsKill(false);
3163 
3164   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3165 
3166   MachineBasicBlock::iterator I = LoopBB->end();
3167 
3168   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3169     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3170 
3171   // Clear TRAP_STS.MEM_VIOL
3172   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3173     .addImm(0)
3174     .addImm(EncodedReg);
3175 
3176   bundleInstWithWaitcnt(MI);
3177 
3178   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3179 
3180   // Load and check TRAP_STS.MEM_VIOL
3181   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3182     .addImm(EncodedReg);
3183 
3184   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3185   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3186     .addReg(Reg, RegState::Kill)
3187     .addImm(0);
3188   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3189     .addMBB(LoopBB);
3190 
3191   return RemainderBB;
3192 }
3193 
3194 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3195 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3196 // will only do one iteration. In the worst case, this will loop 64 times.
3197 //
3198 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3199 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3200   const SIInstrInfo *TII,
3201   MachineRegisterInfo &MRI,
3202   MachineBasicBlock &OrigBB,
3203   MachineBasicBlock &LoopBB,
3204   const DebugLoc &DL,
3205   const MachineOperand &IdxReg,
3206   unsigned InitReg,
3207   unsigned ResultReg,
3208   unsigned PhiReg,
3209   unsigned InitSaveExecReg,
3210   int Offset,
3211   bool UseGPRIdxMode,
3212   bool IsIndirectSrc) {
3213   MachineFunction *MF = OrigBB.getParent();
3214   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3215   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3216   MachineBasicBlock::iterator I = LoopBB.begin();
3217 
3218   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3219   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3220   Register NewExec = MRI.createVirtualRegister(BoolRC);
3221   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3222   Register CondReg = MRI.createVirtualRegister(BoolRC);
3223 
3224   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3225     .addReg(InitReg)
3226     .addMBB(&OrigBB)
3227     .addReg(ResultReg)
3228     .addMBB(&LoopBB);
3229 
3230   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3231     .addReg(InitSaveExecReg)
3232     .addMBB(&OrigBB)
3233     .addReg(NewExec)
3234     .addMBB(&LoopBB);
3235 
3236   // Read the next variant <- also loop target.
3237   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3238     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3239 
3240   // Compare the just read M0 value to all possible Idx values.
3241   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3242     .addReg(CurrentIdxReg)
3243     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3244 
3245   // Update EXEC, save the original EXEC value to VCC.
3246   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3247                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3248           NewExec)
3249     .addReg(CondReg, RegState::Kill);
3250 
3251   MRI.setSimpleHint(NewExec, CondReg);
3252 
3253   if (UseGPRIdxMode) {
3254     unsigned IdxReg;
3255     if (Offset == 0) {
3256       IdxReg = CurrentIdxReg;
3257     } else {
3258       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3259       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3260         .addReg(CurrentIdxReg, RegState::Kill)
3261         .addImm(Offset);
3262     }
3263     unsigned IdxMode = IsIndirectSrc ?
3264       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3265     MachineInstr *SetOn =
3266       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3267       .addReg(IdxReg, RegState::Kill)
3268       .addImm(IdxMode);
3269     SetOn->getOperand(3).setIsUndef();
3270   } else {
3271     // Move index from VCC into M0
3272     if (Offset == 0) {
3273       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3274         .addReg(CurrentIdxReg, RegState::Kill);
3275     } else {
3276       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3277         .addReg(CurrentIdxReg, RegState::Kill)
3278         .addImm(Offset);
3279     }
3280   }
3281 
3282   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3283   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3284   MachineInstr *InsertPt =
3285     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3286                                                   : AMDGPU::S_XOR_B64_term), Exec)
3287       .addReg(Exec)
3288       .addReg(NewExec);
3289 
3290   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3291   // s_cbranch_scc0?
3292 
3293   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3294   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3295     .addMBB(&LoopBB);
3296 
3297   return InsertPt->getIterator();
3298 }
3299 
3300 // This has slightly sub-optimal regalloc when the source vector is killed by
3301 // the read. The register allocator does not understand that the kill is
3302 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3303 // subregister from it, using 1 more VGPR than necessary. This was saved when
3304 // this was expanded after register allocation.
3305 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3306                                                   MachineBasicBlock &MBB,
3307                                                   MachineInstr &MI,
3308                                                   unsigned InitResultReg,
3309                                                   unsigned PhiReg,
3310                                                   int Offset,
3311                                                   bool UseGPRIdxMode,
3312                                                   bool IsIndirectSrc) {
3313   MachineFunction *MF = MBB.getParent();
3314   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3315   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3316   MachineRegisterInfo &MRI = MF->getRegInfo();
3317   const DebugLoc &DL = MI.getDebugLoc();
3318   MachineBasicBlock::iterator I(&MI);
3319 
3320   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3321   Register DstReg = MI.getOperand(0).getReg();
3322   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3323   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3324   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3325   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3326 
3327   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3328 
3329   // Save the EXEC mask
3330   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3331     .addReg(Exec);
3332 
3333   MachineBasicBlock *LoopBB;
3334   MachineBasicBlock *RemainderBB;
3335   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3336 
3337   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3338 
3339   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3340                                       InitResultReg, DstReg, PhiReg, TmpExec,
3341                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3342   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3343   MachineFunction::iterator MBBI(LoopBB);
3344   ++MBBI;
3345   MF->insert(MBBI, LandingPad);
3346   LoopBB->removeSuccessor(RemainderBB);
3347   LandingPad->addSuccessor(RemainderBB);
3348   LoopBB->addSuccessor(LandingPad);
3349   MachineBasicBlock::iterator First = LandingPad->begin();
3350   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3351     .addReg(SaveExec);
3352 
3353   return InsPt;
3354 }
3355 
3356 // Returns subreg index, offset
3357 static std::pair<unsigned, int>
3358 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3359                             const TargetRegisterClass *SuperRC,
3360                             unsigned VecReg,
3361                             int Offset) {
3362   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3363 
3364   // Skip out of bounds offsets, or else we would end up using an undefined
3365   // register.
3366   if (Offset >= NumElts || Offset < 0)
3367     return std::make_pair(AMDGPU::sub0, Offset);
3368 
3369   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3370 }
3371 
3372 // Return true if the index is an SGPR and was set.
3373 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3374                                  MachineRegisterInfo &MRI,
3375                                  MachineInstr &MI,
3376                                  int Offset,
3377                                  bool UseGPRIdxMode,
3378                                  bool IsIndirectSrc) {
3379   MachineBasicBlock *MBB = MI.getParent();
3380   const DebugLoc &DL = MI.getDebugLoc();
3381   MachineBasicBlock::iterator I(&MI);
3382 
3383   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3384   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3385 
3386   assert(Idx->getReg() != AMDGPU::NoRegister);
3387 
3388   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3389     return false;
3390 
3391   if (UseGPRIdxMode) {
3392     unsigned IdxMode = IsIndirectSrc ?
3393       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3394     if (Offset == 0) {
3395       MachineInstr *SetOn =
3396           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3397               .add(*Idx)
3398               .addImm(IdxMode);
3399 
3400       SetOn->getOperand(3).setIsUndef();
3401     } else {
3402       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3403       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3404           .add(*Idx)
3405           .addImm(Offset);
3406       MachineInstr *SetOn =
3407         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3408         .addReg(Tmp, RegState::Kill)
3409         .addImm(IdxMode);
3410 
3411       SetOn->getOperand(3).setIsUndef();
3412     }
3413 
3414     return true;
3415   }
3416 
3417   if (Offset == 0) {
3418     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3419       .add(*Idx);
3420   } else {
3421     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3422       .add(*Idx)
3423       .addImm(Offset);
3424   }
3425 
3426   return true;
3427 }
3428 
3429 // Control flow needs to be inserted if indexing with a VGPR.
3430 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3431                                           MachineBasicBlock &MBB,
3432                                           const GCNSubtarget &ST) {
3433   const SIInstrInfo *TII = ST.getInstrInfo();
3434   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3435   MachineFunction *MF = MBB.getParent();
3436   MachineRegisterInfo &MRI = MF->getRegInfo();
3437 
3438   Register Dst = MI.getOperand(0).getReg();
3439   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3440   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3441 
3442   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3443 
3444   unsigned SubReg;
3445   std::tie(SubReg, Offset)
3446     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3447 
3448   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3449 
3450   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3451     MachineBasicBlock::iterator I(&MI);
3452     const DebugLoc &DL = MI.getDebugLoc();
3453 
3454     if (UseGPRIdxMode) {
3455       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3456       // to avoid interfering with other uses, so probably requires a new
3457       // optimization pass.
3458       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3459         .addReg(SrcReg, RegState::Undef, SubReg)
3460         .addReg(SrcReg, RegState::Implicit)
3461         .addReg(AMDGPU::M0, RegState::Implicit);
3462       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3463     } else {
3464       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3465         .addReg(SrcReg, RegState::Undef, SubReg)
3466         .addReg(SrcReg, RegState::Implicit);
3467     }
3468 
3469     MI.eraseFromParent();
3470 
3471     return &MBB;
3472   }
3473 
3474   const DebugLoc &DL = MI.getDebugLoc();
3475   MachineBasicBlock::iterator I(&MI);
3476 
3477   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3478   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3479 
3480   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3481 
3482   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3483                               Offset, UseGPRIdxMode, true);
3484   MachineBasicBlock *LoopBB = InsPt->getParent();
3485 
3486   if (UseGPRIdxMode) {
3487     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3488       .addReg(SrcReg, RegState::Undef, SubReg)
3489       .addReg(SrcReg, RegState::Implicit)
3490       .addReg(AMDGPU::M0, RegState::Implicit);
3491     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3492   } else {
3493     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3494       .addReg(SrcReg, RegState::Undef, SubReg)
3495       .addReg(SrcReg, RegState::Implicit);
3496   }
3497 
3498   MI.eraseFromParent();
3499 
3500   return LoopBB;
3501 }
3502 
3503 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3504                                           MachineBasicBlock &MBB,
3505                                           const GCNSubtarget &ST) {
3506   const SIInstrInfo *TII = ST.getInstrInfo();
3507   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3508   MachineFunction *MF = MBB.getParent();
3509   MachineRegisterInfo &MRI = MF->getRegInfo();
3510 
3511   Register Dst = MI.getOperand(0).getReg();
3512   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3513   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3514   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3515   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3516   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3517 
3518   // This can be an immediate, but will be folded later.
3519   assert(Val->getReg());
3520 
3521   unsigned SubReg;
3522   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3523                                                          SrcVec->getReg(),
3524                                                          Offset);
3525   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3526 
3527   if (Idx->getReg() == AMDGPU::NoRegister) {
3528     MachineBasicBlock::iterator I(&MI);
3529     const DebugLoc &DL = MI.getDebugLoc();
3530 
3531     assert(Offset == 0);
3532 
3533     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3534         .add(*SrcVec)
3535         .add(*Val)
3536         .addImm(SubReg);
3537 
3538     MI.eraseFromParent();
3539     return &MBB;
3540   }
3541 
3542   const MCInstrDesc &MovRelDesc
3543     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3544 
3545   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3546     MachineBasicBlock::iterator I(&MI);
3547     const DebugLoc &DL = MI.getDebugLoc();
3548     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3549       .addReg(SrcVec->getReg())
3550       .add(*Val)
3551       .addImm(SubReg);
3552     if (UseGPRIdxMode)
3553       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3554 
3555     MI.eraseFromParent();
3556     return &MBB;
3557   }
3558 
3559   if (Val->isReg())
3560     MRI.clearKillFlags(Val->getReg());
3561 
3562   const DebugLoc &DL = MI.getDebugLoc();
3563 
3564   Register PhiReg = MRI.createVirtualRegister(VecRC);
3565 
3566   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3567                               Offset, UseGPRIdxMode, false);
3568   MachineBasicBlock *LoopBB = InsPt->getParent();
3569 
3570   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3571     .addReg(PhiReg)
3572     .add(*Val)
3573     .addImm(AMDGPU::sub0);
3574   if (UseGPRIdxMode)
3575     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3576 
3577   MI.eraseFromParent();
3578   return LoopBB;
3579 }
3580 
3581 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3582   MachineInstr &MI, MachineBasicBlock *BB) const {
3583 
3584   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3585   MachineFunction *MF = BB->getParent();
3586   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3587 
3588   if (TII->isMIMG(MI)) {
3589     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3590       report_fatal_error("missing mem operand from MIMG instruction");
3591     }
3592     // Add a memoperand for mimg instructions so that they aren't assumed to
3593     // be ordered memory instuctions.
3594 
3595     return BB;
3596   }
3597 
3598   switch (MI.getOpcode()) {
3599   case AMDGPU::S_ADD_U64_PSEUDO:
3600   case AMDGPU::S_SUB_U64_PSEUDO: {
3601     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3602     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3603     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3604     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3605     const DebugLoc &DL = MI.getDebugLoc();
3606 
3607     MachineOperand &Dest = MI.getOperand(0);
3608     MachineOperand &Src0 = MI.getOperand(1);
3609     MachineOperand &Src1 = MI.getOperand(2);
3610 
3611     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3612     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3613 
3614     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3615      Src0, BoolRC, AMDGPU::sub0,
3616      &AMDGPU::SReg_32RegClass);
3617     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3618       Src0, BoolRC, AMDGPU::sub1,
3619       &AMDGPU::SReg_32RegClass);
3620 
3621     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3622       Src1, BoolRC, AMDGPU::sub0,
3623       &AMDGPU::SReg_32RegClass);
3624     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3625       Src1, BoolRC, AMDGPU::sub1,
3626       &AMDGPU::SReg_32RegClass);
3627 
3628     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3629 
3630     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3631     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3632     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3633       .add(Src0Sub0)
3634       .add(Src1Sub0);
3635     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3636       .add(Src0Sub1)
3637       .add(Src1Sub1);
3638     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3639       .addReg(DestSub0)
3640       .addImm(AMDGPU::sub0)
3641       .addReg(DestSub1)
3642       .addImm(AMDGPU::sub1);
3643     MI.eraseFromParent();
3644     return BB;
3645   }
3646   case AMDGPU::SI_INIT_M0: {
3647     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3648             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3649         .add(MI.getOperand(0));
3650     MI.eraseFromParent();
3651     return BB;
3652   }
3653   case AMDGPU::SI_INIT_EXEC:
3654     // This should be before all vector instructions.
3655     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3656             AMDGPU::EXEC)
3657         .addImm(MI.getOperand(0).getImm());
3658     MI.eraseFromParent();
3659     return BB;
3660 
3661   case AMDGPU::SI_INIT_EXEC_LO:
3662     // This should be before all vector instructions.
3663     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3664             AMDGPU::EXEC_LO)
3665         .addImm(MI.getOperand(0).getImm());
3666     MI.eraseFromParent();
3667     return BB;
3668 
3669   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3670     // Extract the thread count from an SGPR input and set EXEC accordingly.
3671     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3672     //
3673     // S_BFE_U32 count, input, {shift, 7}
3674     // S_BFM_B64 exec, count, 0
3675     // S_CMP_EQ_U32 count, 64
3676     // S_CMOV_B64 exec, -1
3677     MachineInstr *FirstMI = &*BB->begin();
3678     MachineRegisterInfo &MRI = MF->getRegInfo();
3679     Register InputReg = MI.getOperand(0).getReg();
3680     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3681     bool Found = false;
3682 
3683     // Move the COPY of the input reg to the beginning, so that we can use it.
3684     for (auto I = BB->begin(); I != &MI; I++) {
3685       if (I->getOpcode() != TargetOpcode::COPY ||
3686           I->getOperand(0).getReg() != InputReg)
3687         continue;
3688 
3689       if (I == FirstMI) {
3690         FirstMI = &*++BB->begin();
3691       } else {
3692         I->removeFromParent();
3693         BB->insert(FirstMI, &*I);
3694       }
3695       Found = true;
3696       break;
3697     }
3698     assert(Found);
3699     (void)Found;
3700 
3701     // This should be before all vector instructions.
3702     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3703     bool isWave32 = getSubtarget()->isWave32();
3704     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3705     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3706         .addReg(InputReg)
3707         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3708     BuildMI(*BB, FirstMI, DebugLoc(),
3709             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3710             Exec)
3711         .addReg(CountReg)
3712         .addImm(0);
3713     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3714         .addReg(CountReg, RegState::Kill)
3715         .addImm(getSubtarget()->getWavefrontSize());
3716     BuildMI(*BB, FirstMI, DebugLoc(),
3717             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3718             Exec)
3719         .addImm(-1);
3720     MI.eraseFromParent();
3721     return BB;
3722   }
3723 
3724   case AMDGPU::GET_GROUPSTATICSIZE: {
3725     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3726            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3727     DebugLoc DL = MI.getDebugLoc();
3728     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3729         .add(MI.getOperand(0))
3730         .addImm(MFI->getLDSSize());
3731     MI.eraseFromParent();
3732     return BB;
3733   }
3734   case AMDGPU::SI_INDIRECT_SRC_V1:
3735   case AMDGPU::SI_INDIRECT_SRC_V2:
3736   case AMDGPU::SI_INDIRECT_SRC_V4:
3737   case AMDGPU::SI_INDIRECT_SRC_V8:
3738   case AMDGPU::SI_INDIRECT_SRC_V16:
3739     return emitIndirectSrc(MI, *BB, *getSubtarget());
3740   case AMDGPU::SI_INDIRECT_DST_V1:
3741   case AMDGPU::SI_INDIRECT_DST_V2:
3742   case AMDGPU::SI_INDIRECT_DST_V4:
3743   case AMDGPU::SI_INDIRECT_DST_V8:
3744   case AMDGPU::SI_INDIRECT_DST_V16:
3745     return emitIndirectDst(MI, *BB, *getSubtarget());
3746   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3747   case AMDGPU::SI_KILL_I1_PSEUDO:
3748     return splitKillBlock(MI, BB);
3749   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3750     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3751     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3752     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3753 
3754     Register Dst = MI.getOperand(0).getReg();
3755     Register Src0 = MI.getOperand(1).getReg();
3756     Register Src1 = MI.getOperand(2).getReg();
3757     const DebugLoc &DL = MI.getDebugLoc();
3758     Register SrcCond = MI.getOperand(3).getReg();
3759 
3760     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3761     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3762     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3763     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3764 
3765     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3766       .addReg(SrcCond);
3767     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3768       .addImm(0)
3769       .addReg(Src0, 0, AMDGPU::sub0)
3770       .addImm(0)
3771       .addReg(Src1, 0, AMDGPU::sub0)
3772       .addReg(SrcCondCopy);
3773     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3774       .addImm(0)
3775       .addReg(Src0, 0, AMDGPU::sub1)
3776       .addImm(0)
3777       .addReg(Src1, 0, AMDGPU::sub1)
3778       .addReg(SrcCondCopy);
3779 
3780     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3781       .addReg(DstLo)
3782       .addImm(AMDGPU::sub0)
3783       .addReg(DstHi)
3784       .addImm(AMDGPU::sub1);
3785     MI.eraseFromParent();
3786     return BB;
3787   }
3788   case AMDGPU::SI_BR_UNDEF: {
3789     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3790     const DebugLoc &DL = MI.getDebugLoc();
3791     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3792                            .add(MI.getOperand(0));
3793     Br->getOperand(1).setIsUndef(true); // read undef SCC
3794     MI.eraseFromParent();
3795     return BB;
3796   }
3797   case AMDGPU::ADJCALLSTACKUP:
3798   case AMDGPU::ADJCALLSTACKDOWN: {
3799     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3800     MachineInstrBuilder MIB(*MF, &MI);
3801 
3802     // Add an implicit use of the frame offset reg to prevent the restore copy
3803     // inserted after the call from being reorderd after stack operations in the
3804     // the caller's frame.
3805     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3806         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3807         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3808     return BB;
3809   }
3810   case AMDGPU::SI_CALL_ISEL: {
3811     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3812     const DebugLoc &DL = MI.getDebugLoc();
3813 
3814     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3815 
3816     MachineInstrBuilder MIB;
3817     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3818 
3819     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3820       MIB.add(MI.getOperand(I));
3821 
3822     MIB.cloneMemRefs(MI);
3823     MI.eraseFromParent();
3824     return BB;
3825   }
3826   case AMDGPU::V_ADD_I32_e32:
3827   case AMDGPU::V_SUB_I32_e32:
3828   case AMDGPU::V_SUBREV_I32_e32: {
3829     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3830     const DebugLoc &DL = MI.getDebugLoc();
3831     unsigned Opc = MI.getOpcode();
3832 
3833     bool NeedClampOperand = false;
3834     if (TII->pseudoToMCOpcode(Opc) == -1) {
3835       Opc = AMDGPU::getVOPe64(Opc);
3836       NeedClampOperand = true;
3837     }
3838 
3839     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3840     if (TII->isVOP3(*I)) {
3841       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3842       const SIRegisterInfo *TRI = ST.getRegisterInfo();
3843       I.addReg(TRI->getVCC(), RegState::Define);
3844     }
3845     I.add(MI.getOperand(1))
3846      .add(MI.getOperand(2));
3847     if (NeedClampOperand)
3848       I.addImm(0); // clamp bit for e64 encoding
3849 
3850     TII->legalizeOperands(*I);
3851 
3852     MI.eraseFromParent();
3853     return BB;
3854   }
3855   case AMDGPU::DS_GWS_INIT:
3856   case AMDGPU::DS_GWS_SEMA_V:
3857   case AMDGPU::DS_GWS_SEMA_BR:
3858   case AMDGPU::DS_GWS_SEMA_P:
3859   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
3860   case AMDGPU::DS_GWS_BARRIER:
3861     // A s_waitcnt 0 is required to be the instruction immediately following.
3862     if (getSubtarget()->hasGWSAutoReplay()) {
3863       bundleInstWithWaitcnt(MI);
3864       return BB;
3865     }
3866 
3867     return emitGWSMemViolTestLoop(MI, BB);
3868   default:
3869     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3870   }
3871 }
3872 
3873 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3874   return isTypeLegal(VT.getScalarType());
3875 }
3876 
3877 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3878   // This currently forces unfolding various combinations of fsub into fma with
3879   // free fneg'd operands. As long as we have fast FMA (controlled by
3880   // isFMAFasterThanFMulAndFAdd), we should perform these.
3881 
3882   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3883   // most of these combines appear to be cycle neutral but save on instruction
3884   // count / code size.
3885   return true;
3886 }
3887 
3888 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3889                                          EVT VT) const {
3890   if (!VT.isVector()) {
3891     return MVT::i1;
3892   }
3893   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3894 }
3895 
3896 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3897   // TODO: Should i16 be used always if legal? For now it would force VALU
3898   // shifts.
3899   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3900 }
3901 
3902 // Answering this is somewhat tricky and depends on the specific device which
3903 // have different rates for fma or all f64 operations.
3904 //
3905 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3906 // regardless of which device (although the number of cycles differs between
3907 // devices), so it is always profitable for f64.
3908 //
3909 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3910 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3911 // which we can always do even without fused FP ops since it returns the same
3912 // result as the separate operations and since it is always full
3913 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3914 // however does not support denormals, so we do report fma as faster if we have
3915 // a fast fma device and require denormals.
3916 //
3917 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
3918                                                   EVT VT) const {
3919   VT = VT.getScalarType();
3920 
3921   switch (VT.getSimpleVT().SimpleTy) {
3922   case MVT::f32: {
3923     // This is as fast on some subtargets. However, we always have full rate f32
3924     // mad available which returns the same result as the separate operations
3925     // which we should prefer over fma. We can't use this if we want to support
3926     // denormals, so only report this in these cases.
3927     if (hasFP32Denormals(MF))
3928       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3929 
3930     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3931     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3932   }
3933   case MVT::f64:
3934     return true;
3935   case MVT::f16:
3936     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
3937   default:
3938     break;
3939   }
3940 
3941   return false;
3942 }
3943 
3944 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG,
3945                                               const SDNode *N) const {
3946   // TODO: Check future ftz flag
3947   // v_mad_f32/v_mac_f32 do not support denormals.
3948   EVT VT = N->getValueType(0);
3949   if (VT == MVT::f32)
3950     return !hasFP32Denormals(DAG.getMachineFunction());
3951   if (VT == MVT::f16) {
3952     return Subtarget->hasMadF16() &&
3953            !hasFP64FP16Denormals(DAG.getMachineFunction());
3954   }
3955 
3956   return false;
3957 }
3958 
3959 //===----------------------------------------------------------------------===//
3960 // Custom DAG Lowering Operations
3961 //===----------------------------------------------------------------------===//
3962 
3963 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3964 // wider vector type is legal.
3965 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3966                                              SelectionDAG &DAG) const {
3967   unsigned Opc = Op.getOpcode();
3968   EVT VT = Op.getValueType();
3969   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
3970 
3971   SDValue Lo, Hi;
3972   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3973 
3974   SDLoc SL(Op);
3975   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3976                              Op->getFlags());
3977   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3978                              Op->getFlags());
3979 
3980   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3981 }
3982 
3983 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3984 // wider vector type is legal.
3985 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3986                                               SelectionDAG &DAG) const {
3987   unsigned Opc = Op.getOpcode();
3988   EVT VT = Op.getValueType();
3989   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3990 
3991   SDValue Lo0, Hi0;
3992   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3993   SDValue Lo1, Hi1;
3994   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3995 
3996   SDLoc SL(Op);
3997 
3998   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3999                              Op->getFlags());
4000   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4001                              Op->getFlags());
4002 
4003   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4004 }
4005 
4006 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4007                                               SelectionDAG &DAG) const {
4008   unsigned Opc = Op.getOpcode();
4009   EVT VT = Op.getValueType();
4010   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4011 
4012   SDValue Lo0, Hi0;
4013   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4014   SDValue Lo1, Hi1;
4015   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4016   SDValue Lo2, Hi2;
4017   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4018 
4019   SDLoc SL(Op);
4020 
4021   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4022                              Op->getFlags());
4023   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4024                              Op->getFlags());
4025 
4026   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4027 }
4028 
4029 
4030 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4031   switch (Op.getOpcode()) {
4032   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4033   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4034   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4035   case ISD::LOAD: {
4036     SDValue Result = LowerLOAD(Op, DAG);
4037     assert((!Result.getNode() ||
4038             Result.getNode()->getNumValues() == 2) &&
4039            "Load should return a value and a chain");
4040     return Result;
4041   }
4042 
4043   case ISD::FSIN:
4044   case ISD::FCOS:
4045     return LowerTrig(Op, DAG);
4046   case ISD::SELECT: return LowerSELECT(Op, DAG);
4047   case ISD::FDIV: return LowerFDIV(Op, DAG);
4048   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4049   case ISD::STORE: return LowerSTORE(Op, DAG);
4050   case ISD::GlobalAddress: {
4051     MachineFunction &MF = DAG.getMachineFunction();
4052     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4053     return LowerGlobalAddress(MFI, Op, DAG);
4054   }
4055   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4056   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4057   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4058   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4059   case ISD::INSERT_SUBVECTOR:
4060     return lowerINSERT_SUBVECTOR(Op, DAG);
4061   case ISD::INSERT_VECTOR_ELT:
4062     return lowerINSERT_VECTOR_ELT(Op, DAG);
4063   case ISD::EXTRACT_VECTOR_ELT:
4064     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4065   case ISD::VECTOR_SHUFFLE:
4066     return lowerVECTOR_SHUFFLE(Op, DAG);
4067   case ISD::BUILD_VECTOR:
4068     return lowerBUILD_VECTOR(Op, DAG);
4069   case ISD::FP_ROUND:
4070     return lowerFP_ROUND(Op, DAG);
4071   case ISD::TRAP:
4072     return lowerTRAP(Op, DAG);
4073   case ISD::DEBUGTRAP:
4074     return lowerDEBUGTRAP(Op, DAG);
4075   case ISD::FABS:
4076   case ISD::FNEG:
4077   case ISD::FCANONICALIZE:
4078   case ISD::BSWAP:
4079     return splitUnaryVectorOp(Op, DAG);
4080   case ISD::FMINNUM:
4081   case ISD::FMAXNUM:
4082     return lowerFMINNUM_FMAXNUM(Op, DAG);
4083   case ISD::FMA:
4084     return splitTernaryVectorOp(Op, DAG);
4085   case ISD::SHL:
4086   case ISD::SRA:
4087   case ISD::SRL:
4088   case ISD::ADD:
4089   case ISD::SUB:
4090   case ISD::MUL:
4091   case ISD::SMIN:
4092   case ISD::SMAX:
4093   case ISD::UMIN:
4094   case ISD::UMAX:
4095   case ISD::FADD:
4096   case ISD::FMUL:
4097   case ISD::FMINNUM_IEEE:
4098   case ISD::FMAXNUM_IEEE:
4099     return splitBinaryVectorOp(Op, DAG);
4100   }
4101   return SDValue();
4102 }
4103 
4104 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4105                                        const SDLoc &DL,
4106                                        SelectionDAG &DAG, bool Unpacked) {
4107   if (!LoadVT.isVector())
4108     return Result;
4109 
4110   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4111     // Truncate to v2i16/v4i16.
4112     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4113 
4114     // Workaround legalizer not scalarizing truncate after vector op
4115     // legalization byt not creating intermediate vector trunc.
4116     SmallVector<SDValue, 4> Elts;
4117     DAG.ExtractVectorElements(Result, Elts);
4118     for (SDValue &Elt : Elts)
4119       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4120 
4121     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4122 
4123     // Bitcast to original type (v2f16/v4f16).
4124     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4125   }
4126 
4127   // Cast back to the original packed type.
4128   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4129 }
4130 
4131 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4132                                               MemSDNode *M,
4133                                               SelectionDAG &DAG,
4134                                               ArrayRef<SDValue> Ops,
4135                                               bool IsIntrinsic) const {
4136   SDLoc DL(M);
4137 
4138   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4139   EVT LoadVT = M->getValueType(0);
4140 
4141   EVT EquivLoadVT = LoadVT;
4142   if (Unpacked && LoadVT.isVector()) {
4143     EquivLoadVT = LoadVT.isVector() ?
4144       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4145                        LoadVT.getVectorNumElements()) : LoadVT;
4146   }
4147 
4148   // Change from v4f16/v2f16 to EquivLoadVT.
4149   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4150 
4151   SDValue Load
4152     = DAG.getMemIntrinsicNode(
4153       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4154       VTList, Ops, M->getMemoryVT(),
4155       M->getMemOperand());
4156   if (!Unpacked) // Just adjusted the opcode.
4157     return Load;
4158 
4159   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4160 
4161   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4162 }
4163 
4164 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4165                                              SelectionDAG &DAG,
4166                                              ArrayRef<SDValue> Ops) const {
4167   SDLoc DL(M);
4168   EVT LoadVT = M->getValueType(0);
4169   EVT EltType = LoadVT.getScalarType();
4170   EVT IntVT = LoadVT.changeTypeToInteger();
4171 
4172   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4173 
4174   unsigned Opc =
4175       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4176 
4177   if (IsD16) {
4178     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4179   }
4180 
4181   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4182   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4183     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4184 
4185   if (isTypeLegal(LoadVT)) {
4186     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4187                                M->getMemOperand(), DAG);
4188   }
4189 
4190   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4191   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4192   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4193                                         M->getMemOperand(), DAG);
4194   return DAG.getMergeValues(
4195       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4196       DL);
4197 }
4198 
4199 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4200                                   SDNode *N, SelectionDAG &DAG) {
4201   EVT VT = N->getValueType(0);
4202   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4203   int CondCode = CD->getSExtValue();
4204   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4205       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4206     return DAG.getUNDEF(VT);
4207 
4208   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4209 
4210   SDValue LHS = N->getOperand(1);
4211   SDValue RHS = N->getOperand(2);
4212 
4213   SDLoc DL(N);
4214 
4215   EVT CmpVT = LHS.getValueType();
4216   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4217     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4218       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4219     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4220     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4221   }
4222 
4223   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4224 
4225   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4226   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4227 
4228   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4229                               DAG.getCondCode(CCOpcode));
4230   if (VT.bitsEq(CCVT))
4231     return SetCC;
4232   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4233 }
4234 
4235 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4236                                   SDNode *N, SelectionDAG &DAG) {
4237   EVT VT = N->getValueType(0);
4238   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4239 
4240   int CondCode = CD->getSExtValue();
4241   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4242       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4243     return DAG.getUNDEF(VT);
4244   }
4245 
4246   SDValue Src0 = N->getOperand(1);
4247   SDValue Src1 = N->getOperand(2);
4248   EVT CmpVT = Src0.getValueType();
4249   SDLoc SL(N);
4250 
4251   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4252     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4253     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4254   }
4255 
4256   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4257   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4258   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4259   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4260   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4261                               Src1, DAG.getCondCode(CCOpcode));
4262   if (VT.bitsEq(CCVT))
4263     return SetCC;
4264   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4265 }
4266 
4267 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4268                                     SelectionDAG &DAG) {
4269   EVT VT = N->getValueType(0);
4270   SDValue Src = N->getOperand(1);
4271   SDLoc SL(N);
4272 
4273   if (Src.getOpcode() == ISD::SETCC) {
4274     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4275     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4276                        Src.getOperand(1), Src.getOperand(2));
4277   }
4278   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4279     // (ballot 0) -> 0
4280     if (Arg->isNullValue())
4281       return DAG.getConstant(0, SL, VT);
4282 
4283     // (ballot 1) -> EXEC/EXEC_LO
4284     if (Arg->isOne()) {
4285       Register Exec;
4286       if (VT.getScalarSizeInBits() == 32)
4287         Exec = AMDGPU::EXEC_LO;
4288       else if (VT.getScalarSizeInBits() == 64)
4289         Exec = AMDGPU::EXEC;
4290       else
4291         return SDValue();
4292 
4293       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4294     }
4295   }
4296 
4297   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4298   // ISD::SETNE)
4299   return DAG.getNode(
4300       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4301       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4302 }
4303 
4304 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4305                                           SmallVectorImpl<SDValue> &Results,
4306                                           SelectionDAG &DAG) const {
4307   switch (N->getOpcode()) {
4308   case ISD::INSERT_VECTOR_ELT: {
4309     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4310       Results.push_back(Res);
4311     return;
4312   }
4313   case ISD::EXTRACT_VECTOR_ELT: {
4314     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4315       Results.push_back(Res);
4316     return;
4317   }
4318   case ISD::INTRINSIC_WO_CHAIN: {
4319     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4320     switch (IID) {
4321     case Intrinsic::amdgcn_cvt_pkrtz: {
4322       SDValue Src0 = N->getOperand(1);
4323       SDValue Src1 = N->getOperand(2);
4324       SDLoc SL(N);
4325       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4326                                 Src0, Src1);
4327       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4328       return;
4329     }
4330     case Intrinsic::amdgcn_cvt_pknorm_i16:
4331     case Intrinsic::amdgcn_cvt_pknorm_u16:
4332     case Intrinsic::amdgcn_cvt_pk_i16:
4333     case Intrinsic::amdgcn_cvt_pk_u16: {
4334       SDValue Src0 = N->getOperand(1);
4335       SDValue Src1 = N->getOperand(2);
4336       SDLoc SL(N);
4337       unsigned Opcode;
4338 
4339       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4340         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4341       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4342         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4343       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4344         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4345       else
4346         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4347 
4348       EVT VT = N->getValueType(0);
4349       if (isTypeLegal(VT))
4350         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4351       else {
4352         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4353         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4354       }
4355       return;
4356     }
4357     }
4358     break;
4359   }
4360   case ISD::INTRINSIC_W_CHAIN: {
4361     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4362       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4363         // FIXME: Hacky
4364         Results.push_back(Res.getOperand(0));
4365         Results.push_back(Res.getOperand(1));
4366       } else {
4367         Results.push_back(Res);
4368         Results.push_back(Res.getValue(1));
4369       }
4370       return;
4371     }
4372 
4373     break;
4374   }
4375   case ISD::SELECT: {
4376     SDLoc SL(N);
4377     EVT VT = N->getValueType(0);
4378     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4379     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4380     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4381 
4382     EVT SelectVT = NewVT;
4383     if (NewVT.bitsLT(MVT::i32)) {
4384       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4385       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4386       SelectVT = MVT::i32;
4387     }
4388 
4389     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4390                                     N->getOperand(0), LHS, RHS);
4391 
4392     if (NewVT != SelectVT)
4393       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4394     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4395     return;
4396   }
4397   case ISD::FNEG: {
4398     if (N->getValueType(0) != MVT::v2f16)
4399       break;
4400 
4401     SDLoc SL(N);
4402     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4403 
4404     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4405                              BC,
4406                              DAG.getConstant(0x80008000, SL, MVT::i32));
4407     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4408     return;
4409   }
4410   case ISD::FABS: {
4411     if (N->getValueType(0) != MVT::v2f16)
4412       break;
4413 
4414     SDLoc SL(N);
4415     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4416 
4417     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4418                              BC,
4419                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4420     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4421     return;
4422   }
4423   default:
4424     break;
4425   }
4426 }
4427 
4428 /// Helper function for LowerBRCOND
4429 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4430 
4431   SDNode *Parent = Value.getNode();
4432   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4433        I != E; ++I) {
4434 
4435     if (I.getUse().get() != Value)
4436       continue;
4437 
4438     if (I->getOpcode() == Opcode)
4439       return *I;
4440   }
4441   return nullptr;
4442 }
4443 
4444 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4445   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4446     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4447     case Intrinsic::amdgcn_if:
4448       return AMDGPUISD::IF;
4449     case Intrinsic::amdgcn_else:
4450       return AMDGPUISD::ELSE;
4451     case Intrinsic::amdgcn_loop:
4452       return AMDGPUISD::LOOP;
4453     case Intrinsic::amdgcn_end_cf:
4454       llvm_unreachable("should not occur");
4455     default:
4456       return 0;
4457     }
4458   }
4459 
4460   // break, if_break, else_break are all only used as inputs to loop, not
4461   // directly as branch conditions.
4462   return 0;
4463 }
4464 
4465 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4466   const Triple &TT = getTargetMachine().getTargetTriple();
4467   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4468           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4469          AMDGPU::shouldEmitConstantsToTextSection(TT);
4470 }
4471 
4472 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4473   // FIXME: Either avoid relying on address space here or change the default
4474   // address space for functions to avoid the explicit check.
4475   return (GV->getValueType()->isFunctionTy() ||
4476           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4477          !shouldEmitFixup(GV) &&
4478          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4479 }
4480 
4481 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4482   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4483 }
4484 
4485 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4486   if (!GV->hasExternalLinkage())
4487     return true;
4488 
4489   const auto OS = getTargetMachine().getTargetTriple().getOS();
4490   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4491 }
4492 
4493 /// This transforms the control flow intrinsics to get the branch destination as
4494 /// last parameter, also switches branch target with BR if the need arise
4495 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4496                                       SelectionDAG &DAG) const {
4497   SDLoc DL(BRCOND);
4498 
4499   SDNode *Intr = BRCOND.getOperand(1).getNode();
4500   SDValue Target = BRCOND.getOperand(2);
4501   SDNode *BR = nullptr;
4502   SDNode *SetCC = nullptr;
4503 
4504   if (Intr->getOpcode() == ISD::SETCC) {
4505     // As long as we negate the condition everything is fine
4506     SetCC = Intr;
4507     Intr = SetCC->getOperand(0).getNode();
4508 
4509   } else {
4510     // Get the target from BR if we don't negate the condition
4511     BR = findUser(BRCOND, ISD::BR);
4512     Target = BR->getOperand(1);
4513   }
4514 
4515   // FIXME: This changes the types of the intrinsics instead of introducing new
4516   // nodes with the correct types.
4517   // e.g. llvm.amdgcn.loop
4518 
4519   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4520   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4521 
4522   unsigned CFNode = isCFIntrinsic(Intr);
4523   if (CFNode == 0) {
4524     // This is a uniform branch so we don't need to legalize.
4525     return BRCOND;
4526   }
4527 
4528   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4529                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4530 
4531   assert(!SetCC ||
4532         (SetCC->getConstantOperandVal(1) == 1 &&
4533          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4534                                                              ISD::SETNE));
4535 
4536   // operands of the new intrinsic call
4537   SmallVector<SDValue, 4> Ops;
4538   if (HaveChain)
4539     Ops.push_back(BRCOND.getOperand(0));
4540 
4541   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4542   Ops.push_back(Target);
4543 
4544   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4545 
4546   // build the new intrinsic call
4547   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4548 
4549   if (!HaveChain) {
4550     SDValue Ops[] =  {
4551       SDValue(Result, 0),
4552       BRCOND.getOperand(0)
4553     };
4554 
4555     Result = DAG.getMergeValues(Ops, DL).getNode();
4556   }
4557 
4558   if (BR) {
4559     // Give the branch instruction our target
4560     SDValue Ops[] = {
4561       BR->getOperand(0),
4562       BRCOND.getOperand(2)
4563     };
4564     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4565     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4566   }
4567 
4568   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4569 
4570   // Copy the intrinsic results to registers
4571   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4572     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4573     if (!CopyToReg)
4574       continue;
4575 
4576     Chain = DAG.getCopyToReg(
4577       Chain, DL,
4578       CopyToReg->getOperand(1),
4579       SDValue(Result, i - 1),
4580       SDValue());
4581 
4582     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4583   }
4584 
4585   // Remove the old intrinsic from the chain
4586   DAG.ReplaceAllUsesOfValueWith(
4587     SDValue(Intr, Intr->getNumValues() - 1),
4588     Intr->getOperand(0));
4589 
4590   return Chain;
4591 }
4592 
4593 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4594                                           SelectionDAG &DAG) const {
4595   MVT VT = Op.getSimpleValueType();
4596   SDLoc DL(Op);
4597   // Checking the depth
4598   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4599     return DAG.getConstant(0, DL, VT);
4600 
4601   MachineFunction &MF = DAG.getMachineFunction();
4602   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4603   // Check for kernel and shader functions
4604   if (Info->isEntryFunction())
4605     return DAG.getConstant(0, DL, VT);
4606 
4607   MachineFrameInfo &MFI = MF.getFrameInfo();
4608   // There is a call to @llvm.returnaddress in this function
4609   MFI.setReturnAddressIsTaken(true);
4610 
4611   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4612   // Get the return address reg and mark it as an implicit live-in
4613   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4614 
4615   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4616 }
4617 
4618 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4619                                             SDValue Op,
4620                                             const SDLoc &DL,
4621                                             EVT VT) const {
4622   return Op.getValueType().bitsLE(VT) ?
4623       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4624     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4625                 DAG.getTargetConstant(0, DL, MVT::i32));
4626 }
4627 
4628 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4629   assert(Op.getValueType() == MVT::f16 &&
4630          "Do not know how to custom lower FP_ROUND for non-f16 type");
4631 
4632   SDValue Src = Op.getOperand(0);
4633   EVT SrcVT = Src.getValueType();
4634   if (SrcVT != MVT::f64)
4635     return Op;
4636 
4637   SDLoc DL(Op);
4638 
4639   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4640   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4641   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4642 }
4643 
4644 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4645                                                SelectionDAG &DAG) const {
4646   EVT VT = Op.getValueType();
4647   const MachineFunction &MF = DAG.getMachineFunction();
4648   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4649   bool IsIEEEMode = Info->getMode().IEEE;
4650 
4651   // FIXME: Assert during selection that this is only selected for
4652   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4653   // mode functions, but this happens to be OK since it's only done in cases
4654   // where there is known no sNaN.
4655   if (IsIEEEMode)
4656     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4657 
4658   if (VT == MVT::v4f16)
4659     return splitBinaryVectorOp(Op, DAG);
4660   return Op;
4661 }
4662 
4663 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4664   SDLoc SL(Op);
4665   SDValue Chain = Op.getOperand(0);
4666 
4667   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4668       !Subtarget->isTrapHandlerEnabled())
4669     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4670 
4671   MachineFunction &MF = DAG.getMachineFunction();
4672   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4673   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4674   assert(UserSGPR != AMDGPU::NoRegister);
4675   SDValue QueuePtr = CreateLiveInRegister(
4676     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4677   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4678   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4679                                    QueuePtr, SDValue());
4680   SDValue Ops[] = {
4681     ToReg,
4682     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4683     SGPR01,
4684     ToReg.getValue(1)
4685   };
4686   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4687 }
4688 
4689 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4690   SDLoc SL(Op);
4691   SDValue Chain = Op.getOperand(0);
4692   MachineFunction &MF = DAG.getMachineFunction();
4693 
4694   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4695       !Subtarget->isTrapHandlerEnabled()) {
4696     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4697                                      "debugtrap handler not supported",
4698                                      Op.getDebugLoc(),
4699                                      DS_Warning);
4700     LLVMContext &Ctx = MF.getFunction().getContext();
4701     Ctx.diagnose(NoTrap);
4702     return Chain;
4703   }
4704 
4705   SDValue Ops[] = {
4706     Chain,
4707     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4708   };
4709   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4710 }
4711 
4712 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4713                                              SelectionDAG &DAG) const {
4714   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4715   if (Subtarget->hasApertureRegs()) {
4716     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4717         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4718         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4719     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4720         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4721         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4722     unsigned Encoding =
4723         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4724         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4725         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4726 
4727     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4728     SDValue ApertureReg = SDValue(
4729         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4730     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4731     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4732   }
4733 
4734   MachineFunction &MF = DAG.getMachineFunction();
4735   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4736   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4737   assert(UserSGPR != AMDGPU::NoRegister);
4738 
4739   SDValue QueuePtr = CreateLiveInRegister(
4740     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4741 
4742   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4743   // private_segment_aperture_base_hi.
4744   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4745 
4746   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4747 
4748   // TODO: Use custom target PseudoSourceValue.
4749   // TODO: We should use the value from the IR intrinsic call, but it might not
4750   // be available and how do we get it?
4751   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
4752   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4753                      MinAlign(64, StructOffset),
4754                      MachineMemOperand::MODereferenceable |
4755                          MachineMemOperand::MOInvariant);
4756 }
4757 
4758 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4759                                              SelectionDAG &DAG) const {
4760   SDLoc SL(Op);
4761   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4762 
4763   SDValue Src = ASC->getOperand(0);
4764   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4765 
4766   const AMDGPUTargetMachine &TM =
4767     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4768 
4769   // flat -> local/private
4770   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4771     unsigned DestAS = ASC->getDestAddressSpace();
4772 
4773     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4774         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4775       unsigned NullVal = TM.getNullPointerValue(DestAS);
4776       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4777       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4778       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4779 
4780       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4781                          NonNull, Ptr, SegmentNullPtr);
4782     }
4783   }
4784 
4785   // local/private -> flat
4786   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4787     unsigned SrcAS = ASC->getSrcAddressSpace();
4788 
4789     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4790         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4791       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4792       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4793 
4794       SDValue NonNull
4795         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4796 
4797       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4798       SDValue CvtPtr
4799         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4800 
4801       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4802                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4803                          FlatNullPtr);
4804     }
4805   }
4806 
4807   // global <-> flat are no-ops and never emitted.
4808 
4809   const MachineFunction &MF = DAG.getMachineFunction();
4810   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4811     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4812   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4813 
4814   return DAG.getUNDEF(ASC->getValueType(0));
4815 }
4816 
4817 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4818 // the small vector and inserting them into the big vector. That is better than
4819 // the default expansion of doing it via a stack slot. Even though the use of
4820 // the stack slot would be optimized away afterwards, the stack slot itself
4821 // remains.
4822 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4823                                                 SelectionDAG &DAG) const {
4824   SDValue Vec = Op.getOperand(0);
4825   SDValue Ins = Op.getOperand(1);
4826   SDValue Idx = Op.getOperand(2);
4827   EVT VecVT = Vec.getValueType();
4828   EVT InsVT = Ins.getValueType();
4829   EVT EltVT = VecVT.getVectorElementType();
4830   unsigned InsNumElts = InsVT.getVectorNumElements();
4831   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4832   SDLoc SL(Op);
4833 
4834   for (unsigned I = 0; I != InsNumElts; ++I) {
4835     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4836                               DAG.getConstant(I, SL, MVT::i32));
4837     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4838                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
4839   }
4840   return Vec;
4841 }
4842 
4843 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4844                                                  SelectionDAG &DAG) const {
4845   SDValue Vec = Op.getOperand(0);
4846   SDValue InsVal = Op.getOperand(1);
4847   SDValue Idx = Op.getOperand(2);
4848   EVT VecVT = Vec.getValueType();
4849   EVT EltVT = VecVT.getVectorElementType();
4850   unsigned VecSize = VecVT.getSizeInBits();
4851   unsigned EltSize = EltVT.getSizeInBits();
4852 
4853 
4854   assert(VecSize <= 64);
4855 
4856   unsigned NumElts = VecVT.getVectorNumElements();
4857   SDLoc SL(Op);
4858   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4859 
4860   if (NumElts == 4 && EltSize == 16 && KIdx) {
4861     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4862 
4863     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4864                                  DAG.getConstant(0, SL, MVT::i32));
4865     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4866                                  DAG.getConstant(1, SL, MVT::i32));
4867 
4868     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4869     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4870 
4871     unsigned Idx = KIdx->getZExtValue();
4872     bool InsertLo = Idx < 2;
4873     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4874       InsertLo ? LoVec : HiVec,
4875       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4876       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4877 
4878     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4879 
4880     SDValue Concat = InsertLo ?
4881       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4882       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4883 
4884     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4885   }
4886 
4887   if (isa<ConstantSDNode>(Idx))
4888     return SDValue();
4889 
4890   MVT IntVT = MVT::getIntegerVT(VecSize);
4891 
4892   // Avoid stack access for dynamic indexing.
4893   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4894 
4895   // Create a congruent vector with the target value in each element so that
4896   // the required element can be masked and ORed into the target vector.
4897   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4898                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
4899 
4900   assert(isPowerOf2_32(EltSize));
4901   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4902 
4903   // Convert vector index to bit-index.
4904   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4905 
4906   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4907   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4908                             DAG.getConstant(0xffff, SL, IntVT),
4909                             ScaledIdx);
4910 
4911   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4912   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4913                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4914 
4915   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4916   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4917 }
4918 
4919 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4920                                                   SelectionDAG &DAG) const {
4921   SDLoc SL(Op);
4922 
4923   EVT ResultVT = Op.getValueType();
4924   SDValue Vec = Op.getOperand(0);
4925   SDValue Idx = Op.getOperand(1);
4926   EVT VecVT = Vec.getValueType();
4927   unsigned VecSize = VecVT.getSizeInBits();
4928   EVT EltVT = VecVT.getVectorElementType();
4929   assert(VecSize <= 64);
4930 
4931   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4932 
4933   // Make sure we do any optimizations that will make it easier to fold
4934   // source modifiers before obscuring it with bit operations.
4935 
4936   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4937   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4938     return Combined;
4939 
4940   unsigned EltSize = EltVT.getSizeInBits();
4941   assert(isPowerOf2_32(EltSize));
4942 
4943   MVT IntVT = MVT::getIntegerVT(VecSize);
4944   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4945 
4946   // Convert vector index to bit-index (* EltSize)
4947   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4948 
4949   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4950   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4951 
4952   if (ResultVT == MVT::f16) {
4953     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4954     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4955   }
4956 
4957   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4958 }
4959 
4960 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
4961   assert(Elt % 2 == 0);
4962   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
4963 }
4964 
4965 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4966                                               SelectionDAG &DAG) const {
4967   SDLoc SL(Op);
4968   EVT ResultVT = Op.getValueType();
4969   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
4970 
4971   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
4972   EVT EltVT = PackVT.getVectorElementType();
4973   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
4974 
4975   // vector_shuffle <0,1,6,7> lhs, rhs
4976   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
4977   //
4978   // vector_shuffle <6,7,2,3> lhs, rhs
4979   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
4980   //
4981   // vector_shuffle <6,7,0,1> lhs, rhs
4982   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
4983 
4984   // Avoid scalarizing when both halves are reading from consecutive elements.
4985   SmallVector<SDValue, 4> Pieces;
4986   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
4987     if (elementPairIsContiguous(SVN->getMask(), I)) {
4988       const int Idx = SVN->getMaskElt(I);
4989       int VecIdx = Idx < SrcNumElts ? 0 : 1;
4990       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
4991       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
4992                                     PackVT, SVN->getOperand(VecIdx),
4993                                     DAG.getConstant(EltIdx, SL, MVT::i32));
4994       Pieces.push_back(SubVec);
4995     } else {
4996       const int Idx0 = SVN->getMaskElt(I);
4997       const int Idx1 = SVN->getMaskElt(I + 1);
4998       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
4999       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5000       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5001       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5002 
5003       SDValue Vec0 = SVN->getOperand(VecIdx0);
5004       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5005                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5006 
5007       SDValue Vec1 = SVN->getOperand(VecIdx1);
5008       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5009                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5010       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5011     }
5012   }
5013 
5014   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5015 }
5016 
5017 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5018                                             SelectionDAG &DAG) const {
5019   SDLoc SL(Op);
5020   EVT VT = Op.getValueType();
5021 
5022   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5023     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5024 
5025     // Turn into pair of packed build_vectors.
5026     // TODO: Special case for constants that can be materialized with s_mov_b64.
5027     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5028                                     { Op.getOperand(0), Op.getOperand(1) });
5029     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5030                                     { Op.getOperand(2), Op.getOperand(3) });
5031 
5032     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5033     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5034 
5035     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5036     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5037   }
5038 
5039   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5040   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5041 
5042   SDValue Lo = Op.getOperand(0);
5043   SDValue Hi = Op.getOperand(1);
5044 
5045   // Avoid adding defined bits with the zero_extend.
5046   if (Hi.isUndef()) {
5047     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5048     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5049     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5050   }
5051 
5052   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5053   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5054 
5055   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5056                               DAG.getConstant(16, SL, MVT::i32));
5057   if (Lo.isUndef())
5058     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5059 
5060   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5061   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5062 
5063   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5064   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5065 }
5066 
5067 bool
5068 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5069   // We can fold offsets for anything that doesn't require a GOT relocation.
5070   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5071           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5072           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5073          !shouldEmitGOTReloc(GA->getGlobal());
5074 }
5075 
5076 static SDValue
5077 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5078                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5079                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5080   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5081   // lowered to the following code sequence:
5082   //
5083   // For constant address space:
5084   //   s_getpc_b64 s[0:1]
5085   //   s_add_u32 s0, s0, $symbol
5086   //   s_addc_u32 s1, s1, 0
5087   //
5088   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5089   //   a fixup or relocation is emitted to replace $symbol with a literal
5090   //   constant, which is a pc-relative offset from the encoding of the $symbol
5091   //   operand to the global variable.
5092   //
5093   // For global address space:
5094   //   s_getpc_b64 s[0:1]
5095   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5096   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5097   //
5098   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5099   //   fixups or relocations are emitted to replace $symbol@*@lo and
5100   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5101   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5102   //   operand to the global variable.
5103   //
5104   // What we want here is an offset from the value returned by s_getpc
5105   // (which is the address of the s_add_u32 instruction) to the global
5106   // variable, but since the encoding of $symbol starts 4 bytes after the start
5107   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5108   // small. This requires us to add 4 to the global variable offset in order to
5109   // compute the correct address.
5110   SDValue PtrLo =
5111       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5112   SDValue PtrHi;
5113   if (GAFlags == SIInstrInfo::MO_NONE) {
5114     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5115   } else {
5116     PtrHi =
5117         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5118   }
5119   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5120 }
5121 
5122 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5123                                              SDValue Op,
5124                                              SelectionDAG &DAG) const {
5125   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5126   const GlobalValue *GV = GSD->getGlobal();
5127   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5128        shouldUseLDSConstAddress(GV)) ||
5129       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5130       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5131     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5132 
5133   SDLoc DL(GSD);
5134   EVT PtrVT = Op.getValueType();
5135 
5136   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5137     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5138                                             SIInstrInfo::MO_ABS32_LO);
5139     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5140   }
5141 
5142   if (shouldEmitFixup(GV))
5143     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5144   else if (shouldEmitPCReloc(GV))
5145     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5146                                    SIInstrInfo::MO_REL32);
5147 
5148   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5149                                             SIInstrInfo::MO_GOTPCREL32);
5150 
5151   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5152   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5153   const DataLayout &DataLayout = DAG.getDataLayout();
5154   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5155   MachinePointerInfo PtrInfo
5156     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5157 
5158   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5159                      MachineMemOperand::MODereferenceable |
5160                          MachineMemOperand::MOInvariant);
5161 }
5162 
5163 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5164                                    const SDLoc &DL, SDValue V) const {
5165   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5166   // the destination register.
5167   //
5168   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5169   // so we will end up with redundant moves to m0.
5170   //
5171   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5172 
5173   // A Null SDValue creates a glue result.
5174   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5175                                   V, Chain);
5176   return SDValue(M0, 0);
5177 }
5178 
5179 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5180                                                  SDValue Op,
5181                                                  MVT VT,
5182                                                  unsigned Offset) const {
5183   SDLoc SL(Op);
5184   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5185                                            DAG.getEntryNode(), Offset, 4, false);
5186   // The local size values will have the hi 16-bits as zero.
5187   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5188                      DAG.getValueType(VT));
5189 }
5190 
5191 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5192                                         EVT VT) {
5193   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5194                                       "non-hsa intrinsic with hsa target",
5195                                       DL.getDebugLoc());
5196   DAG.getContext()->diagnose(BadIntrin);
5197   return DAG.getUNDEF(VT);
5198 }
5199 
5200 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5201                                          EVT VT) {
5202   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5203                                       "intrinsic not supported on subtarget",
5204                                       DL.getDebugLoc());
5205   DAG.getContext()->diagnose(BadIntrin);
5206   return DAG.getUNDEF(VT);
5207 }
5208 
5209 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5210                                     ArrayRef<SDValue> Elts) {
5211   assert(!Elts.empty());
5212   MVT Type;
5213   unsigned NumElts;
5214 
5215   if (Elts.size() == 1) {
5216     Type = MVT::f32;
5217     NumElts = 1;
5218   } else if (Elts.size() == 2) {
5219     Type = MVT::v2f32;
5220     NumElts = 2;
5221   } else if (Elts.size() == 3) {
5222     Type = MVT::v3f32;
5223     NumElts = 3;
5224   } else if (Elts.size() <= 4) {
5225     Type = MVT::v4f32;
5226     NumElts = 4;
5227   } else if (Elts.size() <= 8) {
5228     Type = MVT::v8f32;
5229     NumElts = 8;
5230   } else {
5231     assert(Elts.size() <= 16);
5232     Type = MVT::v16f32;
5233     NumElts = 16;
5234   }
5235 
5236   SmallVector<SDValue, 16> VecElts(NumElts);
5237   for (unsigned i = 0; i < Elts.size(); ++i) {
5238     SDValue Elt = Elts[i];
5239     if (Elt.getValueType() != MVT::f32)
5240       Elt = DAG.getBitcast(MVT::f32, Elt);
5241     VecElts[i] = Elt;
5242   }
5243   for (unsigned i = Elts.size(); i < NumElts; ++i)
5244     VecElts[i] = DAG.getUNDEF(MVT::f32);
5245 
5246   if (NumElts == 1)
5247     return VecElts[0];
5248   return DAG.getBuildVector(Type, DL, VecElts);
5249 }
5250 
5251 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5252                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5253   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5254 
5255   uint64_t Value = CachePolicyConst->getZExtValue();
5256   SDLoc DL(CachePolicy);
5257   if (GLC) {
5258     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5259     Value &= ~(uint64_t)0x1;
5260   }
5261   if (SLC) {
5262     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5263     Value &= ~(uint64_t)0x2;
5264   }
5265   if (DLC) {
5266     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5267     Value &= ~(uint64_t)0x4;
5268   }
5269 
5270   return Value == 0;
5271 }
5272 
5273 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5274                               SDValue Src, int ExtraElts) {
5275   EVT SrcVT = Src.getValueType();
5276 
5277   SmallVector<SDValue, 8> Elts;
5278 
5279   if (SrcVT.isVector())
5280     DAG.ExtractVectorElements(Src, Elts);
5281   else
5282     Elts.push_back(Src);
5283 
5284   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5285   while (ExtraElts--)
5286     Elts.push_back(Undef);
5287 
5288   return DAG.getBuildVector(CastVT, DL, Elts);
5289 }
5290 
5291 // Re-construct the required return value for a image load intrinsic.
5292 // This is more complicated due to the optional use TexFailCtrl which means the required
5293 // return type is an aggregate
5294 static SDValue constructRetValue(SelectionDAG &DAG,
5295                                  MachineSDNode *Result,
5296                                  ArrayRef<EVT> ResultTypes,
5297                                  bool IsTexFail, bool Unpacked, bool IsD16,
5298                                  int DMaskPop, int NumVDataDwords,
5299                                  const SDLoc &DL, LLVMContext &Context) {
5300   // Determine the required return type. This is the same regardless of IsTexFail flag
5301   EVT ReqRetVT = ResultTypes[0];
5302   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5303   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5304     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5305 
5306   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5307     DMaskPop : (DMaskPop + 1) / 2;
5308 
5309   MVT DataDwordVT = NumDataDwords == 1 ?
5310     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5311 
5312   MVT MaskPopVT = MaskPopDwords == 1 ?
5313     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5314 
5315   SDValue Data(Result, 0);
5316   SDValue TexFail;
5317 
5318   if (IsTexFail) {
5319     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5320     if (MaskPopVT.isVector()) {
5321       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5322                          SDValue(Result, 0), ZeroIdx);
5323     } else {
5324       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5325                          SDValue(Result, 0), ZeroIdx);
5326     }
5327 
5328     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5329                           SDValue(Result, 0),
5330                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5331   }
5332 
5333   if (DataDwordVT.isVector())
5334     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5335                           NumDataDwords - MaskPopDwords);
5336 
5337   if (IsD16)
5338     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5339 
5340   if (!ReqRetVT.isVector())
5341     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5342 
5343   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5344 
5345   if (TexFail)
5346     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5347 
5348   if (Result->getNumValues() == 1)
5349     return Data;
5350 
5351   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5352 }
5353 
5354 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5355                          SDValue *LWE, bool &IsTexFail) {
5356   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5357 
5358   uint64_t Value = TexFailCtrlConst->getZExtValue();
5359   if (Value) {
5360     IsTexFail = true;
5361   }
5362 
5363   SDLoc DL(TexFailCtrlConst);
5364   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5365   Value &= ~(uint64_t)0x1;
5366   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5367   Value &= ~(uint64_t)0x2;
5368 
5369   return Value == 0;
5370 }
5371 
5372 SDValue SITargetLowering::lowerImage(SDValue Op,
5373                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5374                                      SelectionDAG &DAG) const {
5375   SDLoc DL(Op);
5376   MachineFunction &MF = DAG.getMachineFunction();
5377   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5378   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5379       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5380   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5381   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5382       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5383   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5384       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5385   unsigned IntrOpcode = Intr->BaseOpcode;
5386   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5387 
5388   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5389   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5390   bool IsD16 = false;
5391   bool IsA16 = false;
5392   SDValue VData;
5393   int NumVDataDwords;
5394   bool AdjustRetType = false;
5395 
5396   unsigned AddrIdx; // Index of first address argument
5397   unsigned DMask;
5398   unsigned DMaskLanes = 0;
5399 
5400   if (BaseOpcode->Atomic) {
5401     VData = Op.getOperand(2);
5402 
5403     bool Is64Bit = VData.getValueType() == MVT::i64;
5404     if (BaseOpcode->AtomicX2) {
5405       SDValue VData2 = Op.getOperand(3);
5406       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5407                                  {VData, VData2});
5408       if (Is64Bit)
5409         VData = DAG.getBitcast(MVT::v4i32, VData);
5410 
5411       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5412       DMask = Is64Bit ? 0xf : 0x3;
5413       NumVDataDwords = Is64Bit ? 4 : 2;
5414       AddrIdx = 4;
5415     } else {
5416       DMask = Is64Bit ? 0x3 : 0x1;
5417       NumVDataDwords = Is64Bit ? 2 : 1;
5418       AddrIdx = 3;
5419     }
5420   } else {
5421     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5422     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5423     DMask = DMaskConst->getZExtValue();
5424     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5425 
5426     if (BaseOpcode->Store) {
5427       VData = Op.getOperand(2);
5428 
5429       MVT StoreVT = VData.getSimpleValueType();
5430       if (StoreVT.getScalarType() == MVT::f16) {
5431         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5432           return Op; // D16 is unsupported for this instruction
5433 
5434         IsD16 = true;
5435         VData = handleD16VData(VData, DAG);
5436       }
5437 
5438       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5439     } else {
5440       // Work out the num dwords based on the dmask popcount and underlying type
5441       // and whether packing is supported.
5442       MVT LoadVT = ResultTypes[0].getSimpleVT();
5443       if (LoadVT.getScalarType() == MVT::f16) {
5444         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5445           return Op; // D16 is unsupported for this instruction
5446 
5447         IsD16 = true;
5448       }
5449 
5450       // Confirm that the return type is large enough for the dmask specified
5451       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5452           (!LoadVT.isVector() && DMaskLanes > 1))
5453           return Op;
5454 
5455       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5456         NumVDataDwords = (DMaskLanes + 1) / 2;
5457       else
5458         NumVDataDwords = DMaskLanes;
5459 
5460       AdjustRetType = true;
5461     }
5462 
5463     AddrIdx = DMaskIdx + 1;
5464   }
5465 
5466   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5467   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5468   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5469   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5470                        NumCoords + NumLCM;
5471   unsigned NumMIVAddrs = NumVAddrs;
5472 
5473   SmallVector<SDValue, 4> VAddrs;
5474 
5475   // Optimize _L to _LZ when _L is zero
5476   if (LZMappingInfo) {
5477     if (auto ConstantLod =
5478          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5479       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5480         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5481         NumMIVAddrs--;               // remove 'lod'
5482       }
5483     }
5484   }
5485 
5486   // Optimize _mip away, when 'lod' is zero
5487   if (MIPMappingInfo) {
5488     if (auto ConstantLod =
5489          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5490       if (ConstantLod->isNullValue()) {
5491         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5492         NumMIVAddrs--;               // remove 'lod'
5493       }
5494     }
5495   }
5496 
5497   // Check for 16 bit addresses and pack if true.
5498   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5499   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5500   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5501   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) {
5502     // Illegal to use a16 images
5503     if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16))
5504       return Op;
5505 
5506     IsA16 = true;
5507     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5508     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5509       SDValue AddrLo;
5510       // Push back extra arguments.
5511       if (i < DimIdx) {
5512         AddrLo = Op.getOperand(i);
5513       } else {
5514         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5515         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5516         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5517             ((NumGradients / 2) % 2 == 1 &&
5518             (i == DimIdx + (NumGradients / 2) - 1 ||
5519              i == DimIdx + NumGradients - 1))) {
5520           AddrLo = Op.getOperand(i);
5521           if (AddrLo.getValueType() != MVT::i16)
5522             AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i));
5523           AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo);
5524         } else {
5525           AddrLo = DAG.getBuildVector(VectorVT, DL,
5526                                       {Op.getOperand(i), Op.getOperand(i + 1)});
5527           i++;
5528         }
5529         AddrLo = DAG.getBitcast(MVT::f32, AddrLo);
5530       }
5531       VAddrs.push_back(AddrLo);
5532     }
5533   } else {
5534     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5535       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5536   }
5537 
5538   // If the register allocator cannot place the address registers contiguously
5539   // without introducing moves, then using the non-sequential address encoding
5540   // is always preferable, since it saves VALU instructions and is usually a
5541   // wash in terms of code size or even better.
5542   //
5543   // However, we currently have no way of hinting to the register allocator that
5544   // MIMG addresses should be placed contiguously when it is possible to do so,
5545   // so force non-NSA for the common 2-address case as a heuristic.
5546   //
5547   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5548   // allocation when possible.
5549   bool UseNSA =
5550       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5551   SDValue VAddr;
5552   if (!UseNSA)
5553     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5554 
5555   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5556   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5557   unsigned CtrlIdx; // Index of texfailctrl argument
5558   SDValue Unorm;
5559   if (!BaseOpcode->Sampler) {
5560     Unorm = True;
5561     CtrlIdx = AddrIdx + NumVAddrs + 1;
5562   } else {
5563     auto UnormConst =
5564         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5565 
5566     Unorm = UnormConst->getZExtValue() ? True : False;
5567     CtrlIdx = AddrIdx + NumVAddrs + 3;
5568   }
5569 
5570   SDValue TFE;
5571   SDValue LWE;
5572   SDValue TexFail = Op.getOperand(CtrlIdx);
5573   bool IsTexFail = false;
5574   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5575     return Op;
5576 
5577   if (IsTexFail) {
5578     if (!DMaskLanes) {
5579       // Expecting to get an error flag since TFC is on - and dmask is 0
5580       // Force dmask to be at least 1 otherwise the instruction will fail
5581       DMask = 0x1;
5582       DMaskLanes = 1;
5583       NumVDataDwords = 1;
5584     }
5585     NumVDataDwords += 1;
5586     AdjustRetType = true;
5587   }
5588 
5589   // Has something earlier tagged that the return type needs adjusting
5590   // This happens if the instruction is a load or has set TexFailCtrl flags
5591   if (AdjustRetType) {
5592     // NumVDataDwords reflects the true number of dwords required in the return type
5593     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5594       // This is a no-op load. This can be eliminated
5595       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5596       if (isa<MemSDNode>(Op))
5597         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5598       return Undef;
5599     }
5600 
5601     EVT NewVT = NumVDataDwords > 1 ?
5602                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
5603                 : MVT::i32;
5604 
5605     ResultTypes[0] = NewVT;
5606     if (ResultTypes.size() == 3) {
5607       // Original result was aggregate type used for TexFailCtrl results
5608       // The actual instruction returns as a vector type which has now been
5609       // created. Remove the aggregate result.
5610       ResultTypes.erase(&ResultTypes[1]);
5611     }
5612   }
5613 
5614   SDValue GLC;
5615   SDValue SLC;
5616   SDValue DLC;
5617   if (BaseOpcode->Atomic) {
5618     GLC = True; // TODO no-return optimization
5619     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5620                           IsGFX10 ? &DLC : nullptr))
5621       return Op;
5622   } else {
5623     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5624                           IsGFX10 ? &DLC : nullptr))
5625       return Op;
5626   }
5627 
5628   SmallVector<SDValue, 26> Ops;
5629   if (BaseOpcode->Store || BaseOpcode->Atomic)
5630     Ops.push_back(VData); // vdata
5631   if (UseNSA) {
5632     for (const SDValue &Addr : VAddrs)
5633       Ops.push_back(Addr);
5634   } else {
5635     Ops.push_back(VAddr);
5636   }
5637   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5638   if (BaseOpcode->Sampler)
5639     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5640   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5641   if (IsGFX10)
5642     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5643   Ops.push_back(Unorm);
5644   if (IsGFX10)
5645     Ops.push_back(DLC);
5646   Ops.push_back(GLC);
5647   Ops.push_back(SLC);
5648   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
5649                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5650   if (IsGFX10)
5651     Ops.push_back(IsA16 ? True : False);
5652   Ops.push_back(TFE);
5653   Ops.push_back(LWE);
5654   if (!IsGFX10)
5655     Ops.push_back(DimInfo->DA ? True : False);
5656   if (BaseOpcode->HasD16)
5657     Ops.push_back(IsD16 ? True : False);
5658   if (isa<MemSDNode>(Op))
5659     Ops.push_back(Op.getOperand(0)); // chain
5660 
5661   int NumVAddrDwords =
5662       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5663   int Opcode = -1;
5664 
5665   if (IsGFX10) {
5666     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5667                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5668                                           : AMDGPU::MIMGEncGfx10Default,
5669                                    NumVDataDwords, NumVAddrDwords);
5670   } else {
5671     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5672       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5673                                      NumVDataDwords, NumVAddrDwords);
5674     if (Opcode == -1)
5675       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5676                                      NumVDataDwords, NumVAddrDwords);
5677   }
5678   assert(Opcode != -1);
5679 
5680   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5681   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5682     MachineMemOperand *MemRef = MemOp->getMemOperand();
5683     DAG.setNodeMemRefs(NewNode, {MemRef});
5684   }
5685 
5686   if (BaseOpcode->AtomicX2) {
5687     SmallVector<SDValue, 1> Elt;
5688     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5689     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5690   } else if (!BaseOpcode->Store) {
5691     return constructRetValue(DAG, NewNode,
5692                              OrigResultTypes, IsTexFail,
5693                              Subtarget->hasUnpackedD16VMem(), IsD16,
5694                              DMaskLanes, NumVDataDwords, DL,
5695                              *DAG.getContext());
5696   }
5697 
5698   return SDValue(NewNode, 0);
5699 }
5700 
5701 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5702                                        SDValue Offset, SDValue CachePolicy,
5703                                        SelectionDAG &DAG) const {
5704   MachineFunction &MF = DAG.getMachineFunction();
5705 
5706   const DataLayout &DataLayout = DAG.getDataLayout();
5707   Align Alignment =
5708       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
5709 
5710   MachineMemOperand *MMO = MF.getMachineMemOperand(
5711       MachinePointerInfo(),
5712       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5713           MachineMemOperand::MOInvariant,
5714       VT.getStoreSize(), Alignment);
5715 
5716   if (!Offset->isDivergent()) {
5717     SDValue Ops[] = {
5718         Rsrc,
5719         Offset, // Offset
5720         CachePolicy
5721     };
5722 
5723     // Widen vec3 load to vec4.
5724     if (VT.isVector() && VT.getVectorNumElements() == 3) {
5725       EVT WidenedVT =
5726           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
5727       auto WidenedOp = DAG.getMemIntrinsicNode(
5728           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
5729           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
5730       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
5731                                    DAG.getVectorIdxConstant(0, DL));
5732       return Subvector;
5733     }
5734 
5735     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5736                                    DAG.getVTList(VT), Ops, VT, MMO);
5737   }
5738 
5739   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5740   // assume that the buffer is unswizzled.
5741   SmallVector<SDValue, 4> Loads;
5742   unsigned NumLoads = 1;
5743   MVT LoadVT = VT.getSimpleVT();
5744   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5745   assert((LoadVT.getScalarType() == MVT::i32 ||
5746           LoadVT.getScalarType() == MVT::f32));
5747 
5748   if (NumElts == 8 || NumElts == 16) {
5749     NumLoads = NumElts / 4;
5750     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
5751   }
5752 
5753   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5754   SDValue Ops[] = {
5755       DAG.getEntryNode(),                               // Chain
5756       Rsrc,                                             // rsrc
5757       DAG.getConstant(0, DL, MVT::i32),                 // vindex
5758       {},                                               // voffset
5759       {},                                               // soffset
5760       {},                                               // offset
5761       CachePolicy,                                      // cachepolicy
5762       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
5763   };
5764 
5765   // Use the alignment to ensure that the required offsets will fit into the
5766   // immediate offsets.
5767   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5768 
5769   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5770   for (unsigned i = 0; i < NumLoads; ++i) {
5771     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5772     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
5773                                         LoadVT, MMO, DAG));
5774   }
5775 
5776   if (NumElts == 8 || NumElts == 16)
5777     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5778 
5779   return Loads[0];
5780 }
5781 
5782 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5783                                                   SelectionDAG &DAG) const {
5784   MachineFunction &MF = DAG.getMachineFunction();
5785   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5786 
5787   EVT VT = Op.getValueType();
5788   SDLoc DL(Op);
5789   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5790 
5791   // TODO: Should this propagate fast-math-flags?
5792 
5793   switch (IntrinsicID) {
5794   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5795     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5796       return emitNonHSAIntrinsicError(DAG, DL, VT);
5797     return getPreloadedValue(DAG, *MFI, VT,
5798                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5799   }
5800   case Intrinsic::amdgcn_dispatch_ptr:
5801   case Intrinsic::amdgcn_queue_ptr: {
5802     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5803       DiagnosticInfoUnsupported BadIntrin(
5804           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5805           DL.getDebugLoc());
5806       DAG.getContext()->diagnose(BadIntrin);
5807       return DAG.getUNDEF(VT);
5808     }
5809 
5810     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5811       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5812     return getPreloadedValue(DAG, *MFI, VT, RegID);
5813   }
5814   case Intrinsic::amdgcn_implicitarg_ptr: {
5815     if (MFI->isEntryFunction())
5816       return getImplicitArgPtr(DAG, DL);
5817     return getPreloadedValue(DAG, *MFI, VT,
5818                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5819   }
5820   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5821     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
5822       // This only makes sense to call in a kernel, so just lower to null.
5823       return DAG.getConstant(0, DL, VT);
5824     }
5825 
5826     return getPreloadedValue(DAG, *MFI, VT,
5827                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5828   }
5829   case Intrinsic::amdgcn_dispatch_id: {
5830     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5831   }
5832   case Intrinsic::amdgcn_rcp:
5833     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5834   case Intrinsic::amdgcn_rsq:
5835     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5836   case Intrinsic::amdgcn_rsq_legacy:
5837     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5838       return emitRemovedIntrinsicError(DAG, DL, VT);
5839 
5840     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5841   case Intrinsic::amdgcn_rcp_legacy:
5842     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5843       return emitRemovedIntrinsicError(DAG, DL, VT);
5844     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5845   case Intrinsic::amdgcn_rsq_clamp: {
5846     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5847       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5848 
5849     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5850     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5851     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5852 
5853     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5854     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5855                               DAG.getConstantFP(Max, DL, VT));
5856     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5857                        DAG.getConstantFP(Min, DL, VT));
5858   }
5859   case Intrinsic::r600_read_ngroups_x:
5860     if (Subtarget->isAmdHsaOS())
5861       return emitNonHSAIntrinsicError(DAG, DL, VT);
5862 
5863     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5864                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
5865   case Intrinsic::r600_read_ngroups_y:
5866     if (Subtarget->isAmdHsaOS())
5867       return emitNonHSAIntrinsicError(DAG, DL, VT);
5868 
5869     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5870                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5871   case Intrinsic::r600_read_ngroups_z:
5872     if (Subtarget->isAmdHsaOS())
5873       return emitNonHSAIntrinsicError(DAG, DL, VT);
5874 
5875     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5876                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5877   case Intrinsic::r600_read_global_size_x:
5878     if (Subtarget->isAmdHsaOS())
5879       return emitNonHSAIntrinsicError(DAG, DL, VT);
5880 
5881     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5882                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5883   case Intrinsic::r600_read_global_size_y:
5884     if (Subtarget->isAmdHsaOS())
5885       return emitNonHSAIntrinsicError(DAG, DL, VT);
5886 
5887     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5888                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5889   case Intrinsic::r600_read_global_size_z:
5890     if (Subtarget->isAmdHsaOS())
5891       return emitNonHSAIntrinsicError(DAG, DL, VT);
5892 
5893     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5894                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5895   case Intrinsic::r600_read_local_size_x:
5896     if (Subtarget->isAmdHsaOS())
5897       return emitNonHSAIntrinsicError(DAG, DL, VT);
5898 
5899     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5900                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
5901   case Intrinsic::r600_read_local_size_y:
5902     if (Subtarget->isAmdHsaOS())
5903       return emitNonHSAIntrinsicError(DAG, DL, VT);
5904 
5905     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5906                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
5907   case Intrinsic::r600_read_local_size_z:
5908     if (Subtarget->isAmdHsaOS())
5909       return emitNonHSAIntrinsicError(DAG, DL, VT);
5910 
5911     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5912                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
5913   case Intrinsic::amdgcn_workgroup_id_x:
5914     return getPreloadedValue(DAG, *MFI, VT,
5915                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5916   case Intrinsic::amdgcn_workgroup_id_y:
5917     return getPreloadedValue(DAG, *MFI, VT,
5918                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5919   case Intrinsic::amdgcn_workgroup_id_z:
5920     return getPreloadedValue(DAG, *MFI, VT,
5921                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5922   case Intrinsic::amdgcn_workitem_id_x:
5923     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5924                           SDLoc(DAG.getEntryNode()),
5925                           MFI->getArgInfo().WorkItemIDX);
5926   case Intrinsic::amdgcn_workitem_id_y:
5927     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5928                           SDLoc(DAG.getEntryNode()),
5929                           MFI->getArgInfo().WorkItemIDY);
5930   case Intrinsic::amdgcn_workitem_id_z:
5931     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5932                           SDLoc(DAG.getEntryNode()),
5933                           MFI->getArgInfo().WorkItemIDZ);
5934   case Intrinsic::amdgcn_wavefrontsize:
5935     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
5936                            SDLoc(Op), MVT::i32);
5937   case Intrinsic::amdgcn_s_buffer_load: {
5938     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5939     SDValue GLC;
5940     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5941     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5942                           IsGFX10 ? &DLC : nullptr))
5943       return Op;
5944     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5945                         DAG);
5946   }
5947   case Intrinsic::amdgcn_fdiv_fast:
5948     return lowerFDIV_FAST(Op, DAG);
5949   case Intrinsic::amdgcn_sin:
5950     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5951 
5952   case Intrinsic::amdgcn_cos:
5953     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5954 
5955   case Intrinsic::amdgcn_mul_u24:
5956     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5957   case Intrinsic::amdgcn_mul_i24:
5958     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5959 
5960   case Intrinsic::amdgcn_log_clamp: {
5961     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5962       return SDValue();
5963 
5964     DiagnosticInfoUnsupported BadIntrin(
5965       MF.getFunction(), "intrinsic not supported on subtarget",
5966       DL.getDebugLoc());
5967       DAG.getContext()->diagnose(BadIntrin);
5968       return DAG.getUNDEF(VT);
5969   }
5970   case Intrinsic::amdgcn_ldexp:
5971     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5972                        Op.getOperand(1), Op.getOperand(2));
5973 
5974   case Intrinsic::amdgcn_fract:
5975     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5976 
5977   case Intrinsic::amdgcn_class:
5978     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5979                        Op.getOperand(1), Op.getOperand(2));
5980   case Intrinsic::amdgcn_div_fmas:
5981     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5982                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5983                        Op.getOperand(4));
5984 
5985   case Intrinsic::amdgcn_div_fixup:
5986     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5987                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5988 
5989   case Intrinsic::amdgcn_trig_preop:
5990     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5991                        Op.getOperand(1), Op.getOperand(2));
5992   case Intrinsic::amdgcn_div_scale: {
5993     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5994 
5995     // Translate to the operands expected by the machine instruction. The
5996     // first parameter must be the same as the first instruction.
5997     SDValue Numerator = Op.getOperand(1);
5998     SDValue Denominator = Op.getOperand(2);
5999 
6000     // Note this order is opposite of the machine instruction's operations,
6001     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6002     // intrinsic has the numerator as the first operand to match a normal
6003     // division operation.
6004 
6005     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6006 
6007     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6008                        Denominator, Numerator);
6009   }
6010   case Intrinsic::amdgcn_icmp: {
6011     // There is a Pat that handles this variant, so return it as-is.
6012     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6013         Op.getConstantOperandVal(2) == 0 &&
6014         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6015       return Op;
6016     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6017   }
6018   case Intrinsic::amdgcn_fcmp: {
6019     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6020   }
6021   case Intrinsic::amdgcn_ballot:
6022     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6023   case Intrinsic::amdgcn_fmed3:
6024     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6025                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6026   case Intrinsic::amdgcn_fdot2:
6027     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6028                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6029                        Op.getOperand(4));
6030   case Intrinsic::amdgcn_fmul_legacy:
6031     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6032                        Op.getOperand(1), Op.getOperand(2));
6033   case Intrinsic::amdgcn_sffbh:
6034     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6035   case Intrinsic::amdgcn_sbfe:
6036     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6037                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6038   case Intrinsic::amdgcn_ubfe:
6039     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6040                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6041   case Intrinsic::amdgcn_cvt_pkrtz:
6042   case Intrinsic::amdgcn_cvt_pknorm_i16:
6043   case Intrinsic::amdgcn_cvt_pknorm_u16:
6044   case Intrinsic::amdgcn_cvt_pk_i16:
6045   case Intrinsic::amdgcn_cvt_pk_u16: {
6046     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6047     EVT VT = Op.getValueType();
6048     unsigned Opcode;
6049 
6050     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6051       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6052     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6053       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6054     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6055       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6056     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6057       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6058     else
6059       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6060 
6061     if (isTypeLegal(VT))
6062       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6063 
6064     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6065                                Op.getOperand(1), Op.getOperand(2));
6066     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6067   }
6068   case Intrinsic::amdgcn_fmad_ftz:
6069     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6070                        Op.getOperand(2), Op.getOperand(3));
6071 
6072   case Intrinsic::amdgcn_if_break:
6073     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6074                                       Op->getOperand(1), Op->getOperand(2)), 0);
6075 
6076   case Intrinsic::amdgcn_groupstaticsize: {
6077     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6078     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6079       return Op;
6080 
6081     const Module *M = MF.getFunction().getParent();
6082     const GlobalValue *GV =
6083         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6084     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6085                                             SIInstrInfo::MO_ABS32_LO);
6086     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6087   }
6088   case Intrinsic::amdgcn_is_shared:
6089   case Intrinsic::amdgcn_is_private: {
6090     SDLoc SL(Op);
6091     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6092       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6093     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6094     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6095                                  Op.getOperand(1));
6096 
6097     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6098                                 DAG.getConstant(1, SL, MVT::i32));
6099     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6100   }
6101   case Intrinsic::amdgcn_alignbit:
6102     return DAG.getNode(ISD::FSHR, DL, VT,
6103                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6104   case Intrinsic::amdgcn_reloc_constant: {
6105     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6106     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6107     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6108     auto RelocSymbol = cast<GlobalVariable>(
6109         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6110     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6111                                             SIInstrInfo::MO_ABS32_LO);
6112     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6113   }
6114   default:
6115     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6116             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6117       return lowerImage(Op, ImageDimIntr, DAG);
6118 
6119     return Op;
6120   }
6121 }
6122 
6123 // This function computes an appropriate offset to pass to
6124 // MachineMemOperand::setOffset() based on the offset inputs to
6125 // an intrinsic.  If any of the offsets are non-contstant or
6126 // if VIndex is non-zero then this function returns 0.  Otherwise,
6127 // it returns the sum of VOffset, SOffset, and Offset.
6128 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6129                                       SDValue SOffset,
6130                                       SDValue Offset,
6131                                       SDValue VIndex = SDValue()) {
6132 
6133   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6134       !isa<ConstantSDNode>(Offset))
6135     return 0;
6136 
6137   if (VIndex) {
6138     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6139       return 0;
6140   }
6141 
6142   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6143          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6144          cast<ConstantSDNode>(Offset)->getSExtValue();
6145 }
6146 
6147 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6148   switch (MF.getFunction().getCallingConv()) {
6149   case CallingConv::AMDGPU_PS:
6150     return 1;
6151   case CallingConv::AMDGPU_VS:
6152     return 2;
6153   case CallingConv::AMDGPU_GS:
6154     return 3;
6155   case CallingConv::AMDGPU_HS:
6156   case CallingConv::AMDGPU_LS:
6157   case CallingConv::AMDGPU_ES:
6158     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6159   case CallingConv::AMDGPU_CS:
6160   case CallingConv::AMDGPU_KERNEL:
6161   case CallingConv::C:
6162   case CallingConv::Fast:
6163   default:
6164     // Assume other calling conventions are various compute callable functions
6165     return 0;
6166   }
6167 }
6168 
6169 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6170                                                  SelectionDAG &DAG) const {
6171   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6172   SDLoc DL(Op);
6173 
6174   switch (IntrID) {
6175   case Intrinsic::amdgcn_ds_ordered_add:
6176   case Intrinsic::amdgcn_ds_ordered_swap: {
6177     MemSDNode *M = cast<MemSDNode>(Op);
6178     SDValue Chain = M->getOperand(0);
6179     SDValue M0 = M->getOperand(2);
6180     SDValue Value = M->getOperand(3);
6181     unsigned IndexOperand = M->getConstantOperandVal(7);
6182     unsigned WaveRelease = M->getConstantOperandVal(8);
6183     unsigned WaveDone = M->getConstantOperandVal(9);
6184 
6185     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6186     IndexOperand &= ~0x3f;
6187     unsigned CountDw = 0;
6188 
6189     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6190       CountDw = (IndexOperand >> 24) & 0xf;
6191       IndexOperand &= ~(0xf << 24);
6192 
6193       if (CountDw < 1 || CountDw > 4) {
6194         report_fatal_error(
6195             "ds_ordered_count: dword count must be between 1 and 4");
6196       }
6197     }
6198 
6199     if (IndexOperand)
6200       report_fatal_error("ds_ordered_count: bad index operand");
6201 
6202     if (WaveDone && !WaveRelease)
6203       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6204 
6205     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6206     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6207     unsigned Offset0 = OrderedCountIndex << 2;
6208     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6209                        (Instruction << 4);
6210 
6211     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6212       Offset1 |= (CountDw - 1) << 6;
6213 
6214     unsigned Offset = Offset0 | (Offset1 << 8);
6215 
6216     SDValue Ops[] = {
6217       Chain,
6218       Value,
6219       DAG.getTargetConstant(Offset, DL, MVT::i16),
6220       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6221     };
6222     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6223                                    M->getVTList(), Ops, M->getMemoryVT(),
6224                                    M->getMemOperand());
6225   }
6226   case Intrinsic::amdgcn_ds_fadd: {
6227     MemSDNode *M = cast<MemSDNode>(Op);
6228     unsigned Opc;
6229     switch (IntrID) {
6230     case Intrinsic::amdgcn_ds_fadd:
6231       Opc = ISD::ATOMIC_LOAD_FADD;
6232       break;
6233     }
6234 
6235     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6236                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6237                          M->getMemOperand());
6238   }
6239   case Intrinsic::amdgcn_atomic_inc:
6240   case Intrinsic::amdgcn_atomic_dec:
6241   case Intrinsic::amdgcn_ds_fmin:
6242   case Intrinsic::amdgcn_ds_fmax: {
6243     MemSDNode *M = cast<MemSDNode>(Op);
6244     unsigned Opc;
6245     switch (IntrID) {
6246     case Intrinsic::amdgcn_atomic_inc:
6247       Opc = AMDGPUISD::ATOMIC_INC;
6248       break;
6249     case Intrinsic::amdgcn_atomic_dec:
6250       Opc = AMDGPUISD::ATOMIC_DEC;
6251       break;
6252     case Intrinsic::amdgcn_ds_fmin:
6253       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6254       break;
6255     case Intrinsic::amdgcn_ds_fmax:
6256       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6257       break;
6258     default:
6259       llvm_unreachable("Unknown intrinsic!");
6260     }
6261     SDValue Ops[] = {
6262       M->getOperand(0), // Chain
6263       M->getOperand(2), // Ptr
6264       M->getOperand(3)  // Value
6265     };
6266 
6267     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6268                                    M->getMemoryVT(), M->getMemOperand());
6269   }
6270   case Intrinsic::amdgcn_buffer_load:
6271   case Intrinsic::amdgcn_buffer_load_format: {
6272     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6273     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6274     unsigned IdxEn = 1;
6275     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6276       IdxEn = Idx->getZExtValue() != 0;
6277     SDValue Ops[] = {
6278       Op.getOperand(0), // Chain
6279       Op.getOperand(2), // rsrc
6280       Op.getOperand(3), // vindex
6281       SDValue(),        // voffset -- will be set by setBufferOffsets
6282       SDValue(),        // soffset -- will be set by setBufferOffsets
6283       SDValue(),        // offset -- will be set by setBufferOffsets
6284       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6285       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6286     };
6287 
6288     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6289     // We don't know the offset if vindex is non-zero, so clear it.
6290     if (IdxEn)
6291       Offset = 0;
6292 
6293     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6294         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6295 
6296     EVT VT = Op.getValueType();
6297     EVT IntVT = VT.changeTypeToInteger();
6298     auto *M = cast<MemSDNode>(Op);
6299     M->getMemOperand()->setOffset(Offset);
6300     EVT LoadVT = Op.getValueType();
6301 
6302     if (LoadVT.getScalarType() == MVT::f16)
6303       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6304                                  M, DAG, Ops);
6305 
6306     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6307     if (LoadVT.getScalarType() == MVT::i8 ||
6308         LoadVT.getScalarType() == MVT::i16)
6309       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6310 
6311     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6312                                M->getMemOperand(), DAG);
6313   }
6314   case Intrinsic::amdgcn_raw_buffer_load:
6315   case Intrinsic::amdgcn_raw_buffer_load_format: {
6316     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6317 
6318     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6319     SDValue Ops[] = {
6320       Op.getOperand(0), // Chain
6321       Op.getOperand(2), // rsrc
6322       DAG.getConstant(0, DL, MVT::i32), // vindex
6323       Offsets.first,    // voffset
6324       Op.getOperand(4), // soffset
6325       Offsets.second,   // offset
6326       Op.getOperand(5), // cachepolicy, swizzled buffer
6327       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6328     };
6329 
6330     auto *M = cast<MemSDNode>(Op);
6331     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6332     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6333   }
6334   case Intrinsic::amdgcn_struct_buffer_load:
6335   case Intrinsic::amdgcn_struct_buffer_load_format: {
6336     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6337 
6338     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6339     SDValue Ops[] = {
6340       Op.getOperand(0), // Chain
6341       Op.getOperand(2), // rsrc
6342       Op.getOperand(3), // vindex
6343       Offsets.first,    // voffset
6344       Op.getOperand(5), // soffset
6345       Offsets.second,   // offset
6346       Op.getOperand(6), // cachepolicy, swizzled buffer
6347       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6348     };
6349 
6350     auto *M = cast<MemSDNode>(Op);
6351     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6352                                                         Ops[2]));
6353     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6354   }
6355   case Intrinsic::amdgcn_tbuffer_load: {
6356     MemSDNode *M = cast<MemSDNode>(Op);
6357     EVT LoadVT = Op.getValueType();
6358 
6359     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6360     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6361     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6362     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6363     unsigned IdxEn = 1;
6364     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6365       IdxEn = Idx->getZExtValue() != 0;
6366     SDValue Ops[] = {
6367       Op.getOperand(0),  // Chain
6368       Op.getOperand(2),  // rsrc
6369       Op.getOperand(3),  // vindex
6370       Op.getOperand(4),  // voffset
6371       Op.getOperand(5),  // soffset
6372       Op.getOperand(6),  // offset
6373       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6374       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6375       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6376     };
6377 
6378     if (LoadVT.getScalarType() == MVT::f16)
6379       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6380                                  M, DAG, Ops);
6381     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6382                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6383                                DAG);
6384   }
6385   case Intrinsic::amdgcn_raw_tbuffer_load: {
6386     MemSDNode *M = cast<MemSDNode>(Op);
6387     EVT LoadVT = Op.getValueType();
6388     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6389 
6390     SDValue Ops[] = {
6391       Op.getOperand(0),  // Chain
6392       Op.getOperand(2),  // rsrc
6393       DAG.getConstant(0, DL, MVT::i32), // vindex
6394       Offsets.first,     // voffset
6395       Op.getOperand(4),  // soffset
6396       Offsets.second,    // offset
6397       Op.getOperand(5),  // format
6398       Op.getOperand(6),  // cachepolicy, swizzled buffer
6399       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6400     };
6401 
6402     if (LoadVT.getScalarType() == MVT::f16)
6403       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6404                                  M, DAG, Ops);
6405     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6406                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6407                                DAG);
6408   }
6409   case Intrinsic::amdgcn_struct_tbuffer_load: {
6410     MemSDNode *M = cast<MemSDNode>(Op);
6411     EVT LoadVT = Op.getValueType();
6412     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6413 
6414     SDValue Ops[] = {
6415       Op.getOperand(0),  // Chain
6416       Op.getOperand(2),  // rsrc
6417       Op.getOperand(3),  // vindex
6418       Offsets.first,     // voffset
6419       Op.getOperand(5),  // soffset
6420       Offsets.second,    // offset
6421       Op.getOperand(6),  // format
6422       Op.getOperand(7),  // cachepolicy, swizzled buffer
6423       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6424     };
6425 
6426     if (LoadVT.getScalarType() == MVT::f16)
6427       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6428                                  M, DAG, Ops);
6429     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6430                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6431                                DAG);
6432   }
6433   case Intrinsic::amdgcn_buffer_atomic_swap:
6434   case Intrinsic::amdgcn_buffer_atomic_add:
6435   case Intrinsic::amdgcn_buffer_atomic_sub:
6436   case Intrinsic::amdgcn_buffer_atomic_smin:
6437   case Intrinsic::amdgcn_buffer_atomic_umin:
6438   case Intrinsic::amdgcn_buffer_atomic_smax:
6439   case Intrinsic::amdgcn_buffer_atomic_umax:
6440   case Intrinsic::amdgcn_buffer_atomic_and:
6441   case Intrinsic::amdgcn_buffer_atomic_or:
6442   case Intrinsic::amdgcn_buffer_atomic_xor: {
6443     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6444     unsigned IdxEn = 1;
6445     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6446       IdxEn = Idx->getZExtValue() != 0;
6447     SDValue Ops[] = {
6448       Op.getOperand(0), // Chain
6449       Op.getOperand(2), // vdata
6450       Op.getOperand(3), // rsrc
6451       Op.getOperand(4), // vindex
6452       SDValue(),        // voffset -- will be set by setBufferOffsets
6453       SDValue(),        // soffset -- will be set by setBufferOffsets
6454       SDValue(),        // offset -- will be set by setBufferOffsets
6455       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6456       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6457     };
6458     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6459     // We don't know the offset if vindex is non-zero, so clear it.
6460     if (IdxEn)
6461       Offset = 0;
6462     EVT VT = Op.getValueType();
6463 
6464     auto *M = cast<MemSDNode>(Op);
6465     M->getMemOperand()->setOffset(Offset);
6466     unsigned Opcode = 0;
6467 
6468     switch (IntrID) {
6469     case Intrinsic::amdgcn_buffer_atomic_swap:
6470       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6471       break;
6472     case Intrinsic::amdgcn_buffer_atomic_add:
6473       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6474       break;
6475     case Intrinsic::amdgcn_buffer_atomic_sub:
6476       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6477       break;
6478     case Intrinsic::amdgcn_buffer_atomic_smin:
6479       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6480       break;
6481     case Intrinsic::amdgcn_buffer_atomic_umin:
6482       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6483       break;
6484     case Intrinsic::amdgcn_buffer_atomic_smax:
6485       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6486       break;
6487     case Intrinsic::amdgcn_buffer_atomic_umax:
6488       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6489       break;
6490     case Intrinsic::amdgcn_buffer_atomic_and:
6491       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6492       break;
6493     case Intrinsic::amdgcn_buffer_atomic_or:
6494       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6495       break;
6496     case Intrinsic::amdgcn_buffer_atomic_xor:
6497       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6498       break;
6499     default:
6500       llvm_unreachable("unhandled atomic opcode");
6501     }
6502 
6503     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6504                                    M->getMemOperand());
6505   }
6506   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6507   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6508   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6509   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6510   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6511   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6512   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6513   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6514   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6515   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6516   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6517   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6518     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6519     SDValue Ops[] = {
6520       Op.getOperand(0), // Chain
6521       Op.getOperand(2), // vdata
6522       Op.getOperand(3), // rsrc
6523       DAG.getConstant(0, DL, MVT::i32), // vindex
6524       Offsets.first,    // voffset
6525       Op.getOperand(5), // soffset
6526       Offsets.second,   // offset
6527       Op.getOperand(6), // cachepolicy
6528       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6529     };
6530     EVT VT = Op.getValueType();
6531 
6532     auto *M = cast<MemSDNode>(Op);
6533     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6534     unsigned Opcode = 0;
6535 
6536     switch (IntrID) {
6537     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6538       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6539       break;
6540     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6541       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6542       break;
6543     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6544       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6545       break;
6546     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6547       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6548       break;
6549     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6550       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6551       break;
6552     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6553       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6554       break;
6555     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6556       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6557       break;
6558     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6559       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6560       break;
6561     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6562       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6563       break;
6564     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6565       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6566       break;
6567     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6568       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6569       break;
6570     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6571       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6572       break;
6573     default:
6574       llvm_unreachable("unhandled atomic opcode");
6575     }
6576 
6577     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6578                                    M->getMemOperand());
6579   }
6580   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6581   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6582   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6583   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6584   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6585   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6586   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6587   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6588   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6589   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6590   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6591   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6592     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6593     SDValue Ops[] = {
6594       Op.getOperand(0), // Chain
6595       Op.getOperand(2), // vdata
6596       Op.getOperand(3), // rsrc
6597       Op.getOperand(4), // vindex
6598       Offsets.first,    // voffset
6599       Op.getOperand(6), // soffset
6600       Offsets.second,   // offset
6601       Op.getOperand(7), // cachepolicy
6602       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6603     };
6604     EVT VT = Op.getValueType();
6605 
6606     auto *M = cast<MemSDNode>(Op);
6607     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6608                                                         Ops[3]));
6609     unsigned Opcode = 0;
6610 
6611     switch (IntrID) {
6612     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6613       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6614       break;
6615     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6616       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6617       break;
6618     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6619       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6620       break;
6621     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6622       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6623       break;
6624     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6625       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6626       break;
6627     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6628       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6629       break;
6630     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6631       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6632       break;
6633     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6634       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6635       break;
6636     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6637       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6638       break;
6639     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6640       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6641       break;
6642     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6643       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6644       break;
6645     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6646       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6647       break;
6648     default:
6649       llvm_unreachable("unhandled atomic opcode");
6650     }
6651 
6652     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6653                                    M->getMemOperand());
6654   }
6655   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6656     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6657     unsigned IdxEn = 1;
6658     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6659       IdxEn = Idx->getZExtValue() != 0;
6660     SDValue Ops[] = {
6661       Op.getOperand(0), // Chain
6662       Op.getOperand(2), // src
6663       Op.getOperand(3), // cmp
6664       Op.getOperand(4), // rsrc
6665       Op.getOperand(5), // vindex
6666       SDValue(),        // voffset -- will be set by setBufferOffsets
6667       SDValue(),        // soffset -- will be set by setBufferOffsets
6668       SDValue(),        // offset -- will be set by setBufferOffsets
6669       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6670       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6671     };
6672     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6673     // We don't know the offset if vindex is non-zero, so clear it.
6674     if (IdxEn)
6675       Offset = 0;
6676     EVT VT = Op.getValueType();
6677     auto *M = cast<MemSDNode>(Op);
6678     M->getMemOperand()->setOffset(Offset);
6679 
6680     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6681                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6682   }
6683   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6684     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6685     SDValue Ops[] = {
6686       Op.getOperand(0), // Chain
6687       Op.getOperand(2), // src
6688       Op.getOperand(3), // cmp
6689       Op.getOperand(4), // rsrc
6690       DAG.getConstant(0, DL, MVT::i32), // vindex
6691       Offsets.first,    // voffset
6692       Op.getOperand(6), // soffset
6693       Offsets.second,   // offset
6694       Op.getOperand(7), // cachepolicy
6695       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6696     };
6697     EVT VT = Op.getValueType();
6698     auto *M = cast<MemSDNode>(Op);
6699     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
6700 
6701     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6702                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6703   }
6704   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6705     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6706     SDValue Ops[] = {
6707       Op.getOperand(0), // Chain
6708       Op.getOperand(2), // src
6709       Op.getOperand(3), // cmp
6710       Op.getOperand(4), // rsrc
6711       Op.getOperand(5), // vindex
6712       Offsets.first,    // voffset
6713       Op.getOperand(7), // soffset
6714       Offsets.second,   // offset
6715       Op.getOperand(8), // cachepolicy
6716       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6717     };
6718     EVT VT = Op.getValueType();
6719     auto *M = cast<MemSDNode>(Op);
6720     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
6721                                                         Ops[4]));
6722 
6723     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6724                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6725   }
6726 
6727   default:
6728     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6729             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6730       return lowerImage(Op, ImageDimIntr, DAG);
6731 
6732     return SDValue();
6733   }
6734 }
6735 
6736 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6737 // dwordx4 if on SI.
6738 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6739                                               SDVTList VTList,
6740                                               ArrayRef<SDValue> Ops, EVT MemVT,
6741                                               MachineMemOperand *MMO,
6742                                               SelectionDAG &DAG) const {
6743   EVT VT = VTList.VTs[0];
6744   EVT WidenedVT = VT;
6745   EVT WidenedMemVT = MemVT;
6746   if (!Subtarget->hasDwordx3LoadStores() &&
6747       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6748     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6749                                  WidenedVT.getVectorElementType(), 4);
6750     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6751                                     WidenedMemVT.getVectorElementType(), 4);
6752     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6753   }
6754 
6755   assert(VTList.NumVTs == 2);
6756   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6757 
6758   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6759                                        WidenedMemVT, MMO);
6760   if (WidenedVT != VT) {
6761     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6762                                DAG.getVectorIdxConstant(0, DL));
6763     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6764   }
6765   return NewOp;
6766 }
6767 
6768 SDValue SITargetLowering::handleD16VData(SDValue VData,
6769                                          SelectionDAG &DAG) const {
6770   EVT StoreVT = VData.getValueType();
6771 
6772   // No change for f16 and legal vector D16 types.
6773   if (!StoreVT.isVector())
6774     return VData;
6775 
6776   SDLoc DL(VData);
6777   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6778 
6779   if (Subtarget->hasUnpackedD16VMem()) {
6780     // We need to unpack the packed data to store.
6781     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6782     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6783 
6784     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6785                                         StoreVT.getVectorNumElements());
6786     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6787     return DAG.UnrollVectorOp(ZExt.getNode());
6788   }
6789 
6790   assert(isTypeLegal(StoreVT));
6791   return VData;
6792 }
6793 
6794 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6795                                               SelectionDAG &DAG) const {
6796   SDLoc DL(Op);
6797   SDValue Chain = Op.getOperand(0);
6798   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6799   MachineFunction &MF = DAG.getMachineFunction();
6800 
6801   switch (IntrinsicID) {
6802   case Intrinsic::amdgcn_exp_compr: {
6803     SDValue Src0 = Op.getOperand(4);
6804     SDValue Src1 = Op.getOperand(5);
6805     // Hack around illegal type on SI by directly selecting it.
6806     if (isTypeLegal(Src0.getValueType()))
6807       return SDValue();
6808 
6809     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6810     SDValue Undef = DAG.getUNDEF(MVT::f32);
6811     const SDValue Ops[] = {
6812       Op.getOperand(2), // tgt
6813       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
6814       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
6815       Undef, // src2
6816       Undef, // src3
6817       Op.getOperand(7), // vm
6818       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6819       Op.getOperand(3), // en
6820       Op.getOperand(0) // Chain
6821     };
6822 
6823     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
6824     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
6825   }
6826   case Intrinsic::amdgcn_s_barrier: {
6827     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6828       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6829       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6830       if (WGSize <= ST.getWavefrontSize())
6831         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6832                                           Op.getOperand(0)), 0);
6833     }
6834     return SDValue();
6835   };
6836   case Intrinsic::amdgcn_tbuffer_store: {
6837     SDValue VData = Op.getOperand(2);
6838     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6839     if (IsD16)
6840       VData = handleD16VData(VData, DAG);
6841     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6842     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6843     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6844     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6845     unsigned IdxEn = 1;
6846     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6847       IdxEn = Idx->getZExtValue() != 0;
6848     SDValue Ops[] = {
6849       Chain,
6850       VData,             // vdata
6851       Op.getOperand(3),  // rsrc
6852       Op.getOperand(4),  // vindex
6853       Op.getOperand(5),  // voffset
6854       Op.getOperand(6),  // soffset
6855       Op.getOperand(7),  // offset
6856       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6857       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6858       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
6859     };
6860     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6861                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6862     MemSDNode *M = cast<MemSDNode>(Op);
6863     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6864                                    M->getMemoryVT(), M->getMemOperand());
6865   }
6866 
6867   case Intrinsic::amdgcn_struct_tbuffer_store: {
6868     SDValue VData = Op.getOperand(2);
6869     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6870     if (IsD16)
6871       VData = handleD16VData(VData, DAG);
6872     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6873     SDValue Ops[] = {
6874       Chain,
6875       VData,             // vdata
6876       Op.getOperand(3),  // rsrc
6877       Op.getOperand(4),  // vindex
6878       Offsets.first,     // voffset
6879       Op.getOperand(6),  // soffset
6880       Offsets.second,    // offset
6881       Op.getOperand(7),  // format
6882       Op.getOperand(8),  // cachepolicy, swizzled buffer
6883       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
6884     };
6885     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6886                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6887     MemSDNode *M = cast<MemSDNode>(Op);
6888     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6889                                    M->getMemoryVT(), M->getMemOperand());
6890   }
6891 
6892   case Intrinsic::amdgcn_raw_tbuffer_store: {
6893     SDValue VData = Op.getOperand(2);
6894     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6895     if (IsD16)
6896       VData = handleD16VData(VData, DAG);
6897     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6898     SDValue Ops[] = {
6899       Chain,
6900       VData,             // vdata
6901       Op.getOperand(3),  // rsrc
6902       DAG.getConstant(0, DL, MVT::i32), // vindex
6903       Offsets.first,     // voffset
6904       Op.getOperand(5),  // soffset
6905       Offsets.second,    // offset
6906       Op.getOperand(6),  // format
6907       Op.getOperand(7),  // cachepolicy, swizzled buffer
6908       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
6909     };
6910     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6911                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6912     MemSDNode *M = cast<MemSDNode>(Op);
6913     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6914                                    M->getMemoryVT(), M->getMemOperand());
6915   }
6916 
6917   case Intrinsic::amdgcn_buffer_store:
6918   case Intrinsic::amdgcn_buffer_store_format: {
6919     SDValue VData = Op.getOperand(2);
6920     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6921     if (IsD16)
6922       VData = handleD16VData(VData, DAG);
6923     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6924     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6925     unsigned IdxEn = 1;
6926     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6927       IdxEn = Idx->getZExtValue() != 0;
6928     SDValue Ops[] = {
6929       Chain,
6930       VData,
6931       Op.getOperand(3), // rsrc
6932       Op.getOperand(4), // vindex
6933       SDValue(), // voffset -- will be set by setBufferOffsets
6934       SDValue(), // soffset -- will be set by setBufferOffsets
6935       SDValue(), // offset -- will be set by setBufferOffsets
6936       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6937       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6938     };
6939     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6940     // We don't know the offset if vindex is non-zero, so clear it.
6941     if (IdxEn)
6942       Offset = 0;
6943     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6944                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6945     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6946     MemSDNode *M = cast<MemSDNode>(Op);
6947     M->getMemOperand()->setOffset(Offset);
6948 
6949     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6950     EVT VDataType = VData.getValueType().getScalarType();
6951     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6952       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6953 
6954     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6955                                    M->getMemoryVT(), M->getMemOperand());
6956   }
6957 
6958   case Intrinsic::amdgcn_raw_buffer_store:
6959   case Intrinsic::amdgcn_raw_buffer_store_format: {
6960     const bool IsFormat =
6961         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
6962 
6963     SDValue VData = Op.getOperand(2);
6964     EVT VDataVT = VData.getValueType();
6965     EVT EltType = VDataVT.getScalarType();
6966     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6967     if (IsD16)
6968       VData = handleD16VData(VData, DAG);
6969 
6970     if (!isTypeLegal(VDataVT)) {
6971       VData =
6972           DAG.getNode(ISD::BITCAST, DL,
6973                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6974     }
6975 
6976     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6977     SDValue Ops[] = {
6978       Chain,
6979       VData,
6980       Op.getOperand(3), // rsrc
6981       DAG.getConstant(0, DL, MVT::i32), // vindex
6982       Offsets.first,    // voffset
6983       Op.getOperand(5), // soffset
6984       Offsets.second,   // offset
6985       Op.getOperand(6), // cachepolicy, swizzled buffer
6986       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6987     };
6988     unsigned Opc =
6989         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
6990     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6991     MemSDNode *M = cast<MemSDNode>(Op);
6992     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6993 
6994     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6995     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
6996       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
6997 
6998     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6999                                    M->getMemoryVT(), M->getMemOperand());
7000   }
7001 
7002   case Intrinsic::amdgcn_struct_buffer_store:
7003   case Intrinsic::amdgcn_struct_buffer_store_format: {
7004     const bool IsFormat =
7005         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7006 
7007     SDValue VData = Op.getOperand(2);
7008     EVT VDataVT = VData.getValueType();
7009     EVT EltType = VDataVT.getScalarType();
7010     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7011 
7012     if (IsD16)
7013       VData = handleD16VData(VData, DAG);
7014 
7015     if (!isTypeLegal(VDataVT)) {
7016       VData =
7017           DAG.getNode(ISD::BITCAST, DL,
7018                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7019     }
7020 
7021     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7022     SDValue Ops[] = {
7023       Chain,
7024       VData,
7025       Op.getOperand(3), // rsrc
7026       Op.getOperand(4), // vindex
7027       Offsets.first,    // voffset
7028       Op.getOperand(6), // soffset
7029       Offsets.second,   // offset
7030       Op.getOperand(7), // cachepolicy, swizzled buffer
7031       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7032     };
7033     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7034                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7035     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7036     MemSDNode *M = cast<MemSDNode>(Op);
7037     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7038                                                         Ops[3]));
7039 
7040     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7041     EVT VDataType = VData.getValueType().getScalarType();
7042     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7043       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7044 
7045     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7046                                    M->getMemoryVT(), M->getMemOperand());
7047   }
7048 
7049   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7050     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7051     unsigned IdxEn = 1;
7052     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7053       IdxEn = Idx->getZExtValue() != 0;
7054     SDValue Ops[] = {
7055       Chain,
7056       Op.getOperand(2), // vdata
7057       Op.getOperand(3), // rsrc
7058       Op.getOperand(4), // vindex
7059       SDValue(),        // voffset -- will be set by setBufferOffsets
7060       SDValue(),        // soffset -- will be set by setBufferOffsets
7061       SDValue(),        // offset -- will be set by setBufferOffsets
7062       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7063       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7064     };
7065     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7066     // We don't know the offset if vindex is non-zero, so clear it.
7067     if (IdxEn)
7068       Offset = 0;
7069     EVT VT = Op.getOperand(2).getValueType();
7070 
7071     auto *M = cast<MemSDNode>(Op);
7072     M->getMemOperand()->setOffset(Offset);
7073     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7074                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7075 
7076     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7077                                    M->getMemOperand());
7078   }
7079 
7080   case Intrinsic::amdgcn_global_atomic_fadd: {
7081     SDValue Ops[] = {
7082       Chain,
7083       Op.getOperand(2), // ptr
7084       Op.getOperand(3)  // vdata
7085     };
7086     EVT VT = Op.getOperand(3).getValueType();
7087 
7088     auto *M = cast<MemSDNode>(Op);
7089     if (VT.isVector()) {
7090       return DAG.getMemIntrinsicNode(
7091         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7092         M->getMemOperand());
7093     }
7094 
7095     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7096                          DAG.getVTList(VT, MVT::Other), Ops,
7097                          M->getMemOperand()).getValue(1);
7098   }
7099   case Intrinsic::amdgcn_end_cf:
7100     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7101                                       Op->getOperand(2), Chain), 0);
7102 
7103   default: {
7104     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7105             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7106       return lowerImage(Op, ImageDimIntr, DAG);
7107 
7108     return Op;
7109   }
7110   }
7111 }
7112 
7113 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7114 // offset (the offset that is included in bounds checking and swizzling, to be
7115 // split between the instruction's voffset and immoffset fields) and soffset
7116 // (the offset that is excluded from bounds checking and swizzling, to go in
7117 // the instruction's soffset field).  This function takes the first kind of
7118 // offset and figures out how to split it between voffset and immoffset.
7119 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7120     SDValue Offset, SelectionDAG &DAG) const {
7121   SDLoc DL(Offset);
7122   const unsigned MaxImm = 4095;
7123   SDValue N0 = Offset;
7124   ConstantSDNode *C1 = nullptr;
7125 
7126   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7127     N0 = SDValue();
7128   else if (DAG.isBaseWithConstantOffset(N0)) {
7129     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7130     N0 = N0.getOperand(0);
7131   }
7132 
7133   if (C1) {
7134     unsigned ImmOffset = C1->getZExtValue();
7135     // If the immediate value is too big for the immoffset field, put the value
7136     // and -4096 into the immoffset field so that the value that is copied/added
7137     // for the voffset field is a multiple of 4096, and it stands more chance
7138     // of being CSEd with the copy/add for another similar load/store.
7139     // However, do not do that rounding down to a multiple of 4096 if that is a
7140     // negative number, as it appears to be illegal to have a negative offset
7141     // in the vgpr, even if adding the immediate offset makes it positive.
7142     unsigned Overflow = ImmOffset & ~MaxImm;
7143     ImmOffset -= Overflow;
7144     if ((int32_t)Overflow < 0) {
7145       Overflow += ImmOffset;
7146       ImmOffset = 0;
7147     }
7148     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7149     if (Overflow) {
7150       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7151       if (!N0)
7152         N0 = OverflowVal;
7153       else {
7154         SDValue Ops[] = { N0, OverflowVal };
7155         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7156       }
7157     }
7158   }
7159   if (!N0)
7160     N0 = DAG.getConstant(0, DL, MVT::i32);
7161   if (!C1)
7162     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7163   return {N0, SDValue(C1, 0)};
7164 }
7165 
7166 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7167 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7168 // pointed to by Offsets.
7169 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7170                                         SelectionDAG &DAG, SDValue *Offsets,
7171                                         unsigned Align) const {
7172   SDLoc DL(CombinedOffset);
7173   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7174     uint32_t Imm = C->getZExtValue();
7175     uint32_t SOffset, ImmOffset;
7176     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7177       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7178       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7179       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7180       return SOffset + ImmOffset;
7181     }
7182   }
7183   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7184     SDValue N0 = CombinedOffset.getOperand(0);
7185     SDValue N1 = CombinedOffset.getOperand(1);
7186     uint32_t SOffset, ImmOffset;
7187     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7188     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7189                                                 Subtarget, Align)) {
7190       Offsets[0] = N0;
7191       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7192       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7193       return 0;
7194     }
7195   }
7196   Offsets[0] = CombinedOffset;
7197   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7198   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7199   return 0;
7200 }
7201 
7202 // Handle 8 bit and 16 bit buffer loads
7203 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7204                                                      EVT LoadVT, SDLoc DL,
7205                                                      ArrayRef<SDValue> Ops,
7206                                                      MemSDNode *M) const {
7207   EVT IntVT = LoadVT.changeTypeToInteger();
7208   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7209          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7210 
7211   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7212   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7213                                                Ops, IntVT,
7214                                                M->getMemOperand());
7215   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7216   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7217 
7218   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7219 }
7220 
7221 // Handle 8 bit and 16 bit buffer stores
7222 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7223                                                       EVT VDataType, SDLoc DL,
7224                                                       SDValue Ops[],
7225                                                       MemSDNode *M) const {
7226   if (VDataType == MVT::f16)
7227     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7228 
7229   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7230   Ops[1] = BufferStoreExt;
7231   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7232                                  AMDGPUISD::BUFFER_STORE_SHORT;
7233   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7234   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7235                                      M->getMemOperand());
7236 }
7237 
7238 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7239                                  ISD::LoadExtType ExtType, SDValue Op,
7240                                  const SDLoc &SL, EVT VT) {
7241   if (VT.bitsLT(Op.getValueType()))
7242     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7243 
7244   switch (ExtType) {
7245   case ISD::SEXTLOAD:
7246     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7247   case ISD::ZEXTLOAD:
7248     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7249   case ISD::EXTLOAD:
7250     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7251   case ISD::NON_EXTLOAD:
7252     return Op;
7253   }
7254 
7255   llvm_unreachable("invalid ext type");
7256 }
7257 
7258 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7259   SelectionDAG &DAG = DCI.DAG;
7260   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7261     return SDValue();
7262 
7263   // FIXME: Constant loads should all be marked invariant.
7264   unsigned AS = Ld->getAddressSpace();
7265   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7266       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7267       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7268     return SDValue();
7269 
7270   // Don't do this early, since it may interfere with adjacent load merging for
7271   // illegal types. We can avoid losing alignment information for exotic types
7272   // pre-legalize.
7273   EVT MemVT = Ld->getMemoryVT();
7274   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7275       MemVT.getSizeInBits() >= 32)
7276     return SDValue();
7277 
7278   SDLoc SL(Ld);
7279 
7280   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7281          "unexpected vector extload");
7282 
7283   // TODO: Drop only high part of range.
7284   SDValue Ptr = Ld->getBasePtr();
7285   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7286                                 MVT::i32, SL, Ld->getChain(), Ptr,
7287                                 Ld->getOffset(),
7288                                 Ld->getPointerInfo(), MVT::i32,
7289                                 Ld->getAlignment(),
7290                                 Ld->getMemOperand()->getFlags(),
7291                                 Ld->getAAInfo(),
7292                                 nullptr); // Drop ranges
7293 
7294   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7295   if (MemVT.isFloatingPoint()) {
7296     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7297            "unexpected fp extload");
7298     TruncVT = MemVT.changeTypeToInteger();
7299   }
7300 
7301   SDValue Cvt = NewLoad;
7302   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7303     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7304                       DAG.getValueType(TruncVT));
7305   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7306              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7307     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7308   } else {
7309     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7310   }
7311 
7312   EVT VT = Ld->getValueType(0);
7313   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7314 
7315   DCI.AddToWorklist(Cvt.getNode());
7316 
7317   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7318   // the appropriate extension from the 32-bit load.
7319   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7320   DCI.AddToWorklist(Cvt.getNode());
7321 
7322   // Handle conversion back to floating point if necessary.
7323   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7324 
7325   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7326 }
7327 
7328 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7329   SDLoc DL(Op);
7330   LoadSDNode *Load = cast<LoadSDNode>(Op);
7331   ISD::LoadExtType ExtType = Load->getExtensionType();
7332   EVT MemVT = Load->getMemoryVT();
7333 
7334   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7335     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7336       return SDValue();
7337 
7338     // FIXME: Copied from PPC
7339     // First, load into 32 bits, then truncate to 1 bit.
7340 
7341     SDValue Chain = Load->getChain();
7342     SDValue BasePtr = Load->getBasePtr();
7343     MachineMemOperand *MMO = Load->getMemOperand();
7344 
7345     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7346 
7347     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7348                                    BasePtr, RealMemVT, MMO);
7349 
7350     if (!MemVT.isVector()) {
7351       SDValue Ops[] = {
7352         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7353         NewLD.getValue(1)
7354       };
7355 
7356       return DAG.getMergeValues(Ops, DL);
7357     }
7358 
7359     SmallVector<SDValue, 3> Elts;
7360     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7361       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7362                                 DAG.getConstant(I, DL, MVT::i32));
7363 
7364       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7365     }
7366 
7367     SDValue Ops[] = {
7368       DAG.getBuildVector(MemVT, DL, Elts),
7369       NewLD.getValue(1)
7370     };
7371 
7372     return DAG.getMergeValues(Ops, DL);
7373   }
7374 
7375   if (!MemVT.isVector())
7376     return SDValue();
7377 
7378   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7379          "Custom lowering for non-i32 vectors hasn't been implemented.");
7380 
7381   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7382                                       MemVT, *Load->getMemOperand())) {
7383     SDValue Ops[2];
7384     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7385     return DAG.getMergeValues(Ops, DL);
7386   }
7387 
7388   unsigned Alignment = Load->getAlignment();
7389   unsigned AS = Load->getAddressSpace();
7390   if (Subtarget->hasLDSMisalignedBug() &&
7391       AS == AMDGPUAS::FLAT_ADDRESS &&
7392       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7393     return SplitVectorLoad(Op, DAG);
7394   }
7395 
7396   MachineFunction &MF = DAG.getMachineFunction();
7397   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7398   // If there is a possibilty that flat instruction access scratch memory
7399   // then we need to use the same legalization rules we use for private.
7400   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7401       !Subtarget->hasMultiDwordFlatScratchAddressing())
7402     AS = MFI->hasFlatScratchInit() ?
7403          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7404 
7405   unsigned NumElements = MemVT.getVectorNumElements();
7406 
7407   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7408       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7409     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7410       if (MemVT.isPow2VectorType())
7411         return SDValue();
7412       if (NumElements == 3)
7413         return WidenVectorLoad(Op, DAG);
7414       return SplitVectorLoad(Op, DAG);
7415     }
7416     // Non-uniform loads will be selected to MUBUF instructions, so they
7417     // have the same legalization requirements as global and private
7418     // loads.
7419     //
7420   }
7421 
7422   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7423       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7424       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7425     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7426         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7427         Alignment >= 4 && NumElements < 32) {
7428       if (MemVT.isPow2VectorType())
7429         return SDValue();
7430       if (NumElements == 3)
7431         return WidenVectorLoad(Op, DAG);
7432       return SplitVectorLoad(Op, DAG);
7433     }
7434     // Non-uniform loads will be selected to MUBUF instructions, so they
7435     // have the same legalization requirements as global and private
7436     // loads.
7437     //
7438   }
7439   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7440       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7441       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7442       AS == AMDGPUAS::FLAT_ADDRESS) {
7443     if (NumElements > 4)
7444       return SplitVectorLoad(Op, DAG);
7445     // v3 loads not supported on SI.
7446     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7447       return WidenVectorLoad(Op, DAG);
7448     // v3 and v4 loads are supported for private and global memory.
7449     return SDValue();
7450   }
7451   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7452     // Depending on the setting of the private_element_size field in the
7453     // resource descriptor, we can only make private accesses up to a certain
7454     // size.
7455     switch (Subtarget->getMaxPrivateElementSize()) {
7456     case 4: {
7457       SDValue Ops[2];
7458       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7459       return DAG.getMergeValues(Ops, DL);
7460     }
7461     case 8:
7462       if (NumElements > 2)
7463         return SplitVectorLoad(Op, DAG);
7464       return SDValue();
7465     case 16:
7466       // Same as global/flat
7467       if (NumElements > 4)
7468         return SplitVectorLoad(Op, DAG);
7469       // v3 loads not supported on SI.
7470       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7471         return WidenVectorLoad(Op, DAG);
7472       return SDValue();
7473     default:
7474       llvm_unreachable("unsupported private_element_size");
7475     }
7476   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7477     // Use ds_read_b128 if possible.
7478     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7479         MemVT.getStoreSize() == 16)
7480       return SDValue();
7481 
7482     if (NumElements > 2)
7483       return SplitVectorLoad(Op, DAG);
7484 
7485     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7486     // address is negative, then the instruction is incorrectly treated as
7487     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7488     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7489     // load later in the SILoadStoreOptimizer.
7490     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7491         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7492         Load->getAlignment() < 8) {
7493       return SplitVectorLoad(Op, DAG);
7494     }
7495   }
7496   return SDValue();
7497 }
7498 
7499 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7500   EVT VT = Op.getValueType();
7501   assert(VT.getSizeInBits() == 64);
7502 
7503   SDLoc DL(Op);
7504   SDValue Cond = Op.getOperand(0);
7505 
7506   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7507   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7508 
7509   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7510   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7511 
7512   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7513   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7514 
7515   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7516 
7517   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7518   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7519 
7520   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7521 
7522   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7523   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7524 }
7525 
7526 // Catch division cases where we can use shortcuts with rcp and rsq
7527 // instructions.
7528 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7529                                               SelectionDAG &DAG) const {
7530   SDLoc SL(Op);
7531   SDValue LHS = Op.getOperand(0);
7532   SDValue RHS = Op.getOperand(1);
7533   EVT VT = Op.getValueType();
7534   const SDNodeFlags Flags = Op->getFlags();
7535 
7536   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7537                             Flags.hasApproximateFuncs();
7538 
7539   // Without !fpmath accuracy information, we can't do more because we don't
7540   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7541   if (!AllowInaccurateRcp)
7542     return SDValue();
7543 
7544   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7545     if (CLHS->isExactlyValue(1.0)) {
7546       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7547       // the CI documentation has a worst case error of 1 ulp.
7548       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7549       // use it as long as we aren't trying to use denormals.
7550       //
7551       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7552 
7553       // 1.0 / sqrt(x) -> rsq(x)
7554 
7555       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7556       // error seems really high at 2^29 ULP.
7557       if (RHS.getOpcode() == ISD::FSQRT)
7558         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7559 
7560       // 1.0 / x -> rcp(x)
7561       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7562     }
7563 
7564     // Same as for 1.0, but expand the sign out of the constant.
7565     if (CLHS->isExactlyValue(-1.0)) {
7566       // -1.0 / x -> rcp (fneg x)
7567       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7568       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7569     }
7570   }
7571 
7572   // Turn into multiply by the reciprocal.
7573   // x / y -> x * (1.0 / y)
7574   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7575   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7576 }
7577 
7578 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7579                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7580   if (GlueChain->getNumValues() <= 1) {
7581     return DAG.getNode(Opcode, SL, VT, A, B);
7582   }
7583 
7584   assert(GlueChain->getNumValues() == 3);
7585 
7586   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7587   switch (Opcode) {
7588   default: llvm_unreachable("no chain equivalent for opcode");
7589   case ISD::FMUL:
7590     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7591     break;
7592   }
7593 
7594   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7595                      GlueChain.getValue(2));
7596 }
7597 
7598 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7599                            EVT VT, SDValue A, SDValue B, SDValue C,
7600                            SDValue GlueChain) {
7601   if (GlueChain->getNumValues() <= 1) {
7602     return DAG.getNode(Opcode, SL, VT, A, B, C);
7603   }
7604 
7605   assert(GlueChain->getNumValues() == 3);
7606 
7607   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7608   switch (Opcode) {
7609   default: llvm_unreachable("no chain equivalent for opcode");
7610   case ISD::FMA:
7611     Opcode = AMDGPUISD::FMA_W_CHAIN;
7612     break;
7613   }
7614 
7615   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7616                      GlueChain.getValue(2));
7617 }
7618 
7619 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7620   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7621     return FastLowered;
7622 
7623   SDLoc SL(Op);
7624   SDValue Src0 = Op.getOperand(0);
7625   SDValue Src1 = Op.getOperand(1);
7626 
7627   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7628   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7629 
7630   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7631   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7632 
7633   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7634   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7635 
7636   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7637 }
7638 
7639 // Faster 2.5 ULP division that does not support denormals.
7640 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7641   SDLoc SL(Op);
7642   SDValue LHS = Op.getOperand(1);
7643   SDValue RHS = Op.getOperand(2);
7644 
7645   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7646 
7647   const APFloat K0Val(BitsToFloat(0x6f800000));
7648   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7649 
7650   const APFloat K1Val(BitsToFloat(0x2f800000));
7651   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7652 
7653   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7654 
7655   EVT SetCCVT =
7656     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7657 
7658   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7659 
7660   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7661 
7662   // TODO: Should this propagate fast-math-flags?
7663   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7664 
7665   // rcp does not support denormals.
7666   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7667 
7668   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7669 
7670   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7671 }
7672 
7673 // Returns immediate value for setting the F32 denorm mode when using the
7674 // S_DENORM_MODE instruction.
7675 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7676                                           const SDLoc &SL, const GCNSubtarget *ST) {
7677   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7678   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
7679                                 ? FP_DENORM_FLUSH_NONE
7680                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7681 
7682   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7683   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7684 }
7685 
7686 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7687   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7688     return FastLowered;
7689 
7690   SDLoc SL(Op);
7691   SDValue LHS = Op.getOperand(0);
7692   SDValue RHS = Op.getOperand(1);
7693 
7694   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7695 
7696   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7697 
7698   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7699                                           RHS, RHS, LHS);
7700   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7701                                         LHS, RHS, LHS);
7702 
7703   // Denominator is scaled to not be denormal, so using rcp is ok.
7704   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7705                                   DenominatorScaled);
7706   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7707                                      DenominatorScaled);
7708 
7709   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7710                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7711                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7712   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7713 
7714   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
7715 
7716   if (!HasFP32Denormals) {
7717     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7718 
7719     SDValue EnableDenorm;
7720     if (Subtarget->hasDenormModeInst()) {
7721       const SDValue EnableDenormValue =
7722           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7723 
7724       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7725                                  DAG.getEntryNode(), EnableDenormValue);
7726     } else {
7727       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7728                                                         SL, MVT::i32);
7729       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7730                                  DAG.getEntryNode(), EnableDenormValue,
7731                                  BitField);
7732     }
7733 
7734     SDValue Ops[3] = {
7735       NegDivScale0,
7736       EnableDenorm.getValue(0),
7737       EnableDenorm.getValue(1)
7738     };
7739 
7740     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7741   }
7742 
7743   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7744                              ApproxRcp, One, NegDivScale0);
7745 
7746   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7747                              ApproxRcp, Fma0);
7748 
7749   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7750                            Fma1, Fma1);
7751 
7752   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7753                              NumeratorScaled, Mul);
7754 
7755   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7756 
7757   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7758                              NumeratorScaled, Fma3);
7759 
7760   if (!HasFP32Denormals) {
7761     SDValue DisableDenorm;
7762     if (Subtarget->hasDenormModeInst()) {
7763       const SDValue DisableDenormValue =
7764           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7765 
7766       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7767                                   Fma4.getValue(1), DisableDenormValue,
7768                                   Fma4.getValue(2));
7769     } else {
7770       const SDValue DisableDenormValue =
7771           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7772 
7773       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7774                                   Fma4.getValue(1), DisableDenormValue,
7775                                   BitField, Fma4.getValue(2));
7776     }
7777 
7778     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7779                                       DisableDenorm, DAG.getRoot());
7780     DAG.setRoot(OutputChain);
7781   }
7782 
7783   SDValue Scale = NumeratorScaled.getValue(1);
7784   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7785                              Fma4, Fma1, Fma3, Scale);
7786 
7787   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7788 }
7789 
7790 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7791   if (DAG.getTarget().Options.UnsafeFPMath)
7792     return lowerFastUnsafeFDIV(Op, DAG);
7793 
7794   SDLoc SL(Op);
7795   SDValue X = Op.getOperand(0);
7796   SDValue Y = Op.getOperand(1);
7797 
7798   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7799 
7800   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7801 
7802   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7803 
7804   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7805 
7806   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7807 
7808   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7809 
7810   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7811 
7812   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7813 
7814   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7815 
7816   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7817   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7818 
7819   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7820                              NegDivScale0, Mul, DivScale1);
7821 
7822   SDValue Scale;
7823 
7824   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
7825     // Workaround a hardware bug on SI where the condition output from div_scale
7826     // is not usable.
7827 
7828     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7829 
7830     // Figure out if the scale to use for div_fmas.
7831     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7832     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7833     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7834     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7835 
7836     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7837     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7838 
7839     SDValue Scale0Hi
7840       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7841     SDValue Scale1Hi
7842       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7843 
7844     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7845     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7846     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7847   } else {
7848     Scale = DivScale1.getValue(1);
7849   }
7850 
7851   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7852                              Fma4, Fma3, Mul, Scale);
7853 
7854   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7855 }
7856 
7857 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7858   EVT VT = Op.getValueType();
7859 
7860   if (VT == MVT::f32)
7861     return LowerFDIV32(Op, DAG);
7862 
7863   if (VT == MVT::f64)
7864     return LowerFDIV64(Op, DAG);
7865 
7866   if (VT == MVT::f16)
7867     return LowerFDIV16(Op, DAG);
7868 
7869   llvm_unreachable("Unexpected type for fdiv");
7870 }
7871 
7872 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7873   SDLoc DL(Op);
7874   StoreSDNode *Store = cast<StoreSDNode>(Op);
7875   EVT VT = Store->getMemoryVT();
7876 
7877   if (VT == MVT::i1) {
7878     return DAG.getTruncStore(Store->getChain(), DL,
7879        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7880        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
7881   }
7882 
7883   assert(VT.isVector() &&
7884          Store->getValue().getValueType().getScalarType() == MVT::i32);
7885 
7886   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7887                                       VT, *Store->getMemOperand())) {
7888     return expandUnalignedStore(Store, DAG);
7889   }
7890 
7891   unsigned AS = Store->getAddressSpace();
7892   if (Subtarget->hasLDSMisalignedBug() &&
7893       AS == AMDGPUAS::FLAT_ADDRESS &&
7894       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7895     return SplitVectorStore(Op, DAG);
7896   }
7897 
7898   MachineFunction &MF = DAG.getMachineFunction();
7899   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7900   // If there is a possibilty that flat instruction access scratch memory
7901   // then we need to use the same legalization rules we use for private.
7902   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7903       !Subtarget->hasMultiDwordFlatScratchAddressing())
7904     AS = MFI->hasFlatScratchInit() ?
7905          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7906 
7907   unsigned NumElements = VT.getVectorNumElements();
7908   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7909       AS == AMDGPUAS::FLAT_ADDRESS) {
7910     if (NumElements > 4)
7911       return SplitVectorStore(Op, DAG);
7912     // v3 stores not supported on SI.
7913     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7914       return SplitVectorStore(Op, DAG);
7915     return SDValue();
7916   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7917     switch (Subtarget->getMaxPrivateElementSize()) {
7918     case 4:
7919       return scalarizeVectorStore(Store, DAG);
7920     case 8:
7921       if (NumElements > 2)
7922         return SplitVectorStore(Op, DAG);
7923       return SDValue();
7924     case 16:
7925       if (NumElements > 4 || NumElements == 3)
7926         return SplitVectorStore(Op, DAG);
7927       return SDValue();
7928     default:
7929       llvm_unreachable("unsupported private_element_size");
7930     }
7931   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7932     // Use ds_write_b128 if possible.
7933     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
7934         VT.getStoreSize() == 16 && NumElements != 3)
7935       return SDValue();
7936 
7937     if (NumElements > 2)
7938       return SplitVectorStore(Op, DAG);
7939 
7940     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7941     // address is negative, then the instruction is incorrectly treated as
7942     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7943     // stores here to avoid emitting ds_write2_b32. We may re-combine the
7944     // store later in the SILoadStoreOptimizer.
7945     if (!Subtarget->hasUsableDSOffset() &&
7946         NumElements == 2 && VT.getStoreSize() == 8 &&
7947         Store->getAlignment() < 8) {
7948       return SplitVectorStore(Op, DAG);
7949     }
7950 
7951     return SDValue();
7952   } else {
7953     llvm_unreachable("unhandled address space");
7954   }
7955 }
7956 
7957 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
7958   SDLoc DL(Op);
7959   EVT VT = Op.getValueType();
7960   SDValue Arg = Op.getOperand(0);
7961   SDValue TrigVal;
7962 
7963   // TODO: Should this propagate fast-math-flags?
7964 
7965   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7966 
7967   if (Subtarget->hasTrigReducedRange()) {
7968     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7969     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7970   } else {
7971     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7972   }
7973 
7974   switch (Op.getOpcode()) {
7975   case ISD::FCOS:
7976     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7977   case ISD::FSIN:
7978     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7979   default:
7980     llvm_unreachable("Wrong trig opcode");
7981   }
7982 }
7983 
7984 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7985   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7986   assert(AtomicNode->isCompareAndSwap());
7987   unsigned AS = AtomicNode->getAddressSpace();
7988 
7989   // No custom lowering required for local address space
7990   if (!isFlatGlobalAddrSpace(AS))
7991     return Op;
7992 
7993   // Non-local address space requires custom lowering for atomic compare
7994   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
7995   SDLoc DL(Op);
7996   SDValue ChainIn = Op.getOperand(0);
7997   SDValue Addr = Op.getOperand(1);
7998   SDValue Old = Op.getOperand(2);
7999   SDValue New = Op.getOperand(3);
8000   EVT VT = Op.getValueType();
8001   MVT SimpleVT = VT.getSimpleVT();
8002   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8003 
8004   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8005   SDValue Ops[] = { ChainIn, Addr, NewOld };
8006 
8007   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8008                                  Ops, VT, AtomicNode->getMemOperand());
8009 }
8010 
8011 //===----------------------------------------------------------------------===//
8012 // Custom DAG optimizations
8013 //===----------------------------------------------------------------------===//
8014 
8015 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8016                                                      DAGCombinerInfo &DCI) const {
8017   EVT VT = N->getValueType(0);
8018   EVT ScalarVT = VT.getScalarType();
8019   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8020     return SDValue();
8021 
8022   SelectionDAG &DAG = DCI.DAG;
8023   SDLoc DL(N);
8024 
8025   SDValue Src = N->getOperand(0);
8026   EVT SrcVT = Src.getValueType();
8027 
8028   // TODO: We could try to match extracting the higher bytes, which would be
8029   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8030   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8031   // about in practice.
8032   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8033     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8034       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8035       DCI.AddToWorklist(Cvt.getNode());
8036 
8037       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8038       if (ScalarVT != MVT::f32) {
8039         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8040                           DAG.getTargetConstant(0, DL, MVT::i32));
8041       }
8042       return Cvt;
8043     }
8044   }
8045 
8046   return SDValue();
8047 }
8048 
8049 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8050 
8051 // This is a variant of
8052 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8053 //
8054 // The normal DAG combiner will do this, but only if the add has one use since
8055 // that would increase the number of instructions.
8056 //
8057 // This prevents us from seeing a constant offset that can be folded into a
8058 // memory instruction's addressing mode. If we know the resulting add offset of
8059 // a pointer can be folded into an addressing offset, we can replace the pointer
8060 // operand with the add of new constant offset. This eliminates one of the uses,
8061 // and may allow the remaining use to also be simplified.
8062 //
8063 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8064                                                unsigned AddrSpace,
8065                                                EVT MemVT,
8066                                                DAGCombinerInfo &DCI) const {
8067   SDValue N0 = N->getOperand(0);
8068   SDValue N1 = N->getOperand(1);
8069 
8070   // We only do this to handle cases where it's profitable when there are
8071   // multiple uses of the add, so defer to the standard combine.
8072   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8073       N0->hasOneUse())
8074     return SDValue();
8075 
8076   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8077   if (!CN1)
8078     return SDValue();
8079 
8080   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8081   if (!CAdd)
8082     return SDValue();
8083 
8084   // If the resulting offset is too large, we can't fold it into the addressing
8085   // mode offset.
8086   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8087   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8088 
8089   AddrMode AM;
8090   AM.HasBaseReg = true;
8091   AM.BaseOffs = Offset.getSExtValue();
8092   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8093     return SDValue();
8094 
8095   SelectionDAG &DAG = DCI.DAG;
8096   SDLoc SL(N);
8097   EVT VT = N->getValueType(0);
8098 
8099   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8100   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8101 
8102   SDNodeFlags Flags;
8103   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8104                           (N0.getOpcode() == ISD::OR ||
8105                            N0->getFlags().hasNoUnsignedWrap()));
8106 
8107   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8108 }
8109 
8110 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8111                                                   DAGCombinerInfo &DCI) const {
8112   SDValue Ptr = N->getBasePtr();
8113   SelectionDAG &DAG = DCI.DAG;
8114   SDLoc SL(N);
8115 
8116   // TODO: We could also do this for multiplies.
8117   if (Ptr.getOpcode() == ISD::SHL) {
8118     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8119                                           N->getMemoryVT(), DCI);
8120     if (NewPtr) {
8121       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8122 
8123       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8124       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8125     }
8126   }
8127 
8128   return SDValue();
8129 }
8130 
8131 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8132   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8133          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8134          (Opc == ISD::XOR && Val == 0);
8135 }
8136 
8137 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8138 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8139 // integer combine opportunities since most 64-bit operations are decomposed
8140 // this way.  TODO: We won't want this for SALU especially if it is an inline
8141 // immediate.
8142 SDValue SITargetLowering::splitBinaryBitConstantOp(
8143   DAGCombinerInfo &DCI,
8144   const SDLoc &SL,
8145   unsigned Opc, SDValue LHS,
8146   const ConstantSDNode *CRHS) const {
8147   uint64_t Val = CRHS->getZExtValue();
8148   uint32_t ValLo = Lo_32(Val);
8149   uint32_t ValHi = Hi_32(Val);
8150   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8151 
8152     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8153          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8154         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8155     // If we need to materialize a 64-bit immediate, it will be split up later
8156     // anyway. Avoid creating the harder to understand 64-bit immediate
8157     // materialization.
8158     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8159   }
8160 
8161   return SDValue();
8162 }
8163 
8164 // Returns true if argument is a boolean value which is not serialized into
8165 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8166 static bool isBoolSGPR(SDValue V) {
8167   if (V.getValueType() != MVT::i1)
8168     return false;
8169   switch (V.getOpcode()) {
8170   default: break;
8171   case ISD::SETCC:
8172   case ISD::AND:
8173   case ISD::OR:
8174   case ISD::XOR:
8175   case AMDGPUISD::FP_CLASS:
8176     return true;
8177   }
8178   return false;
8179 }
8180 
8181 // If a constant has all zeroes or all ones within each byte return it.
8182 // Otherwise return 0.
8183 static uint32_t getConstantPermuteMask(uint32_t C) {
8184   // 0xff for any zero byte in the mask
8185   uint32_t ZeroByteMask = 0;
8186   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8187   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8188   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8189   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8190   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8191   if ((NonZeroByteMask & C) != NonZeroByteMask)
8192     return 0; // Partial bytes selected.
8193   return C;
8194 }
8195 
8196 // Check if a node selects whole bytes from its operand 0 starting at a byte
8197 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8198 // or -1 if not succeeded.
8199 // Note byte select encoding:
8200 // value 0-3 selects corresponding source byte;
8201 // value 0xc selects zero;
8202 // value 0xff selects 0xff.
8203 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8204   assert(V.getValueSizeInBits() == 32);
8205 
8206   if (V.getNumOperands() != 2)
8207     return ~0;
8208 
8209   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8210   if (!N1)
8211     return ~0;
8212 
8213   uint32_t C = N1->getZExtValue();
8214 
8215   switch (V.getOpcode()) {
8216   default:
8217     break;
8218   case ISD::AND:
8219     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8220       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8221     }
8222     break;
8223 
8224   case ISD::OR:
8225     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8226       return (0x03020100 & ~ConstMask) | ConstMask;
8227     }
8228     break;
8229 
8230   case ISD::SHL:
8231     if (C % 8)
8232       return ~0;
8233 
8234     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8235 
8236   case ISD::SRL:
8237     if (C % 8)
8238       return ~0;
8239 
8240     return uint32_t(0x0c0c0c0c03020100ull >> C);
8241   }
8242 
8243   return ~0;
8244 }
8245 
8246 SDValue SITargetLowering::performAndCombine(SDNode *N,
8247                                             DAGCombinerInfo &DCI) const {
8248   if (DCI.isBeforeLegalize())
8249     return SDValue();
8250 
8251   SelectionDAG &DAG = DCI.DAG;
8252   EVT VT = N->getValueType(0);
8253   SDValue LHS = N->getOperand(0);
8254   SDValue RHS = N->getOperand(1);
8255 
8256 
8257   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8258   if (VT == MVT::i64 && CRHS) {
8259     if (SDValue Split
8260         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8261       return Split;
8262   }
8263 
8264   if (CRHS && VT == MVT::i32) {
8265     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8266     // nb = number of trailing zeroes in mask
8267     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8268     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8269     uint64_t Mask = CRHS->getZExtValue();
8270     unsigned Bits = countPopulation(Mask);
8271     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8272         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8273       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8274         unsigned Shift = CShift->getZExtValue();
8275         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8276         unsigned Offset = NB + Shift;
8277         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8278           SDLoc SL(N);
8279           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8280                                     LHS->getOperand(0),
8281                                     DAG.getConstant(Offset, SL, MVT::i32),
8282                                     DAG.getConstant(Bits, SL, MVT::i32));
8283           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8284           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8285                                     DAG.getValueType(NarrowVT));
8286           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8287                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8288           return Shl;
8289         }
8290       }
8291     }
8292 
8293     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8294     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8295         isa<ConstantSDNode>(LHS.getOperand(2))) {
8296       uint32_t Sel = getConstantPermuteMask(Mask);
8297       if (!Sel)
8298         return SDValue();
8299 
8300       // Select 0xc for all zero bytes
8301       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8302       SDLoc DL(N);
8303       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8304                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8305     }
8306   }
8307 
8308   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8309   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8310   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8311     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8312     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8313 
8314     SDValue X = LHS.getOperand(0);
8315     SDValue Y = RHS.getOperand(0);
8316     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8317       return SDValue();
8318 
8319     if (LCC == ISD::SETO) {
8320       if (X != LHS.getOperand(1))
8321         return SDValue();
8322 
8323       if (RCC == ISD::SETUNE) {
8324         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8325         if (!C1 || !C1->isInfinity() || C1->isNegative())
8326           return SDValue();
8327 
8328         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8329                               SIInstrFlags::N_SUBNORMAL |
8330                               SIInstrFlags::N_ZERO |
8331                               SIInstrFlags::P_ZERO |
8332                               SIInstrFlags::P_SUBNORMAL |
8333                               SIInstrFlags::P_NORMAL;
8334 
8335         static_assert(((~(SIInstrFlags::S_NAN |
8336                           SIInstrFlags::Q_NAN |
8337                           SIInstrFlags::N_INFINITY |
8338                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8339                       "mask not equal");
8340 
8341         SDLoc DL(N);
8342         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8343                            X, DAG.getConstant(Mask, DL, MVT::i32));
8344       }
8345     }
8346   }
8347 
8348   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8349     std::swap(LHS, RHS);
8350 
8351   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8352       RHS.hasOneUse()) {
8353     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8354     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8355     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8356     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8357     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8358         (RHS.getOperand(0) == LHS.getOperand(0) &&
8359          LHS.getOperand(0) == LHS.getOperand(1))) {
8360       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8361       unsigned NewMask = LCC == ISD::SETO ?
8362         Mask->getZExtValue() & ~OrdMask :
8363         Mask->getZExtValue() & OrdMask;
8364 
8365       SDLoc DL(N);
8366       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8367                          DAG.getConstant(NewMask, DL, MVT::i32));
8368     }
8369   }
8370 
8371   if (VT == MVT::i32 &&
8372       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8373     // and x, (sext cc from i1) => select cc, x, 0
8374     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8375       std::swap(LHS, RHS);
8376     if (isBoolSGPR(RHS.getOperand(0)))
8377       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8378                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8379   }
8380 
8381   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8382   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8383   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8384       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8385     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8386     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8387     if (LHSMask != ~0u && RHSMask != ~0u) {
8388       // Canonicalize the expression in an attempt to have fewer unique masks
8389       // and therefore fewer registers used to hold the masks.
8390       if (LHSMask > RHSMask) {
8391         std::swap(LHSMask, RHSMask);
8392         std::swap(LHS, RHS);
8393       }
8394 
8395       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8396       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8397       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8398       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8399 
8400       // Check of we need to combine values from two sources within a byte.
8401       if (!(LHSUsedLanes & RHSUsedLanes) &&
8402           // If we select high and lower word keep it for SDWA.
8403           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8404           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8405         // Each byte in each mask is either selector mask 0-3, or has higher
8406         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8407         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8408         // mask which is not 0xff wins. By anding both masks we have a correct
8409         // result except that 0x0c shall be corrected to give 0x0c only.
8410         uint32_t Mask = LHSMask & RHSMask;
8411         for (unsigned I = 0; I < 32; I += 8) {
8412           uint32_t ByteSel = 0xff << I;
8413           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8414             Mask &= (0x0c << I) & 0xffffffff;
8415         }
8416 
8417         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8418         // or 0x0c.
8419         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8420         SDLoc DL(N);
8421 
8422         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8423                            LHS.getOperand(0), RHS.getOperand(0),
8424                            DAG.getConstant(Sel, DL, MVT::i32));
8425       }
8426     }
8427   }
8428 
8429   return SDValue();
8430 }
8431 
8432 SDValue SITargetLowering::performOrCombine(SDNode *N,
8433                                            DAGCombinerInfo &DCI) const {
8434   SelectionDAG &DAG = DCI.DAG;
8435   SDValue LHS = N->getOperand(0);
8436   SDValue RHS = N->getOperand(1);
8437 
8438   EVT VT = N->getValueType(0);
8439   if (VT == MVT::i1) {
8440     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8441     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8442         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8443       SDValue Src = LHS.getOperand(0);
8444       if (Src != RHS.getOperand(0))
8445         return SDValue();
8446 
8447       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8448       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8449       if (!CLHS || !CRHS)
8450         return SDValue();
8451 
8452       // Only 10 bits are used.
8453       static const uint32_t MaxMask = 0x3ff;
8454 
8455       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8456       SDLoc DL(N);
8457       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8458                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8459     }
8460 
8461     return SDValue();
8462   }
8463 
8464   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8465   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8466       LHS.getOpcode() == AMDGPUISD::PERM &&
8467       isa<ConstantSDNode>(LHS.getOperand(2))) {
8468     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8469     if (!Sel)
8470       return SDValue();
8471 
8472     Sel |= LHS.getConstantOperandVal(2);
8473     SDLoc DL(N);
8474     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8475                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8476   }
8477 
8478   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8479   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8480   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8481       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8482     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8483     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8484     if (LHSMask != ~0u && RHSMask != ~0u) {
8485       // Canonicalize the expression in an attempt to have fewer unique masks
8486       // and therefore fewer registers used to hold the masks.
8487       if (LHSMask > RHSMask) {
8488         std::swap(LHSMask, RHSMask);
8489         std::swap(LHS, RHS);
8490       }
8491 
8492       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8493       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8494       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8495       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8496 
8497       // Check of we need to combine values from two sources within a byte.
8498       if (!(LHSUsedLanes & RHSUsedLanes) &&
8499           // If we select high and lower word keep it for SDWA.
8500           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8501           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8502         // Kill zero bytes selected by other mask. Zero value is 0xc.
8503         LHSMask &= ~RHSUsedLanes;
8504         RHSMask &= ~LHSUsedLanes;
8505         // Add 4 to each active LHS lane
8506         LHSMask |= LHSUsedLanes & 0x04040404;
8507         // Combine masks
8508         uint32_t Sel = LHSMask | RHSMask;
8509         SDLoc DL(N);
8510 
8511         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8512                            LHS.getOperand(0), RHS.getOperand(0),
8513                            DAG.getConstant(Sel, DL, MVT::i32));
8514       }
8515     }
8516   }
8517 
8518   if (VT != MVT::i64)
8519     return SDValue();
8520 
8521   // TODO: This could be a generic combine with a predicate for extracting the
8522   // high half of an integer being free.
8523 
8524   // (or i64:x, (zero_extend i32:y)) ->
8525   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8526   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8527       RHS.getOpcode() != ISD::ZERO_EXTEND)
8528     std::swap(LHS, RHS);
8529 
8530   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8531     SDValue ExtSrc = RHS.getOperand(0);
8532     EVT SrcVT = ExtSrc.getValueType();
8533     if (SrcVT == MVT::i32) {
8534       SDLoc SL(N);
8535       SDValue LowLHS, HiBits;
8536       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8537       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8538 
8539       DCI.AddToWorklist(LowOr.getNode());
8540       DCI.AddToWorklist(HiBits.getNode());
8541 
8542       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8543                                 LowOr, HiBits);
8544       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8545     }
8546   }
8547 
8548   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8549   if (CRHS) {
8550     if (SDValue Split
8551           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8552       return Split;
8553   }
8554 
8555   return SDValue();
8556 }
8557 
8558 SDValue SITargetLowering::performXorCombine(SDNode *N,
8559                                             DAGCombinerInfo &DCI) const {
8560   EVT VT = N->getValueType(0);
8561   if (VT != MVT::i64)
8562     return SDValue();
8563 
8564   SDValue LHS = N->getOperand(0);
8565   SDValue RHS = N->getOperand(1);
8566 
8567   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8568   if (CRHS) {
8569     if (SDValue Split
8570           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8571       return Split;
8572   }
8573 
8574   return SDValue();
8575 }
8576 
8577 // Instructions that will be lowered with a final instruction that zeros the
8578 // high result bits.
8579 // XXX - probably only need to list legal operations.
8580 static bool fp16SrcZerosHighBits(unsigned Opc) {
8581   switch (Opc) {
8582   case ISD::FADD:
8583   case ISD::FSUB:
8584   case ISD::FMUL:
8585   case ISD::FDIV:
8586   case ISD::FREM:
8587   case ISD::FMA:
8588   case ISD::FMAD:
8589   case ISD::FCANONICALIZE:
8590   case ISD::FP_ROUND:
8591   case ISD::UINT_TO_FP:
8592   case ISD::SINT_TO_FP:
8593   case ISD::FABS:
8594     // Fabs is lowered to a bit operation, but it's an and which will clear the
8595     // high bits anyway.
8596   case ISD::FSQRT:
8597   case ISD::FSIN:
8598   case ISD::FCOS:
8599   case ISD::FPOWI:
8600   case ISD::FPOW:
8601   case ISD::FLOG:
8602   case ISD::FLOG2:
8603   case ISD::FLOG10:
8604   case ISD::FEXP:
8605   case ISD::FEXP2:
8606   case ISD::FCEIL:
8607   case ISD::FTRUNC:
8608   case ISD::FRINT:
8609   case ISD::FNEARBYINT:
8610   case ISD::FROUND:
8611   case ISD::FFLOOR:
8612   case ISD::FMINNUM:
8613   case ISD::FMAXNUM:
8614   case AMDGPUISD::FRACT:
8615   case AMDGPUISD::CLAMP:
8616   case AMDGPUISD::COS_HW:
8617   case AMDGPUISD::SIN_HW:
8618   case AMDGPUISD::FMIN3:
8619   case AMDGPUISD::FMAX3:
8620   case AMDGPUISD::FMED3:
8621   case AMDGPUISD::FMAD_FTZ:
8622   case AMDGPUISD::RCP:
8623   case AMDGPUISD::RSQ:
8624   case AMDGPUISD::RCP_IFLAG:
8625   case AMDGPUISD::LDEXP:
8626     return true;
8627   default:
8628     // fcopysign, select and others may be lowered to 32-bit bit operations
8629     // which don't zero the high bits.
8630     return false;
8631   }
8632 }
8633 
8634 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8635                                                    DAGCombinerInfo &DCI) const {
8636   if (!Subtarget->has16BitInsts() ||
8637       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8638     return SDValue();
8639 
8640   EVT VT = N->getValueType(0);
8641   if (VT != MVT::i32)
8642     return SDValue();
8643 
8644   SDValue Src = N->getOperand(0);
8645   if (Src.getValueType() != MVT::i16)
8646     return SDValue();
8647 
8648   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8649   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8650   if (Src.getOpcode() == ISD::BITCAST) {
8651     SDValue BCSrc = Src.getOperand(0);
8652     if (BCSrc.getValueType() == MVT::f16 &&
8653         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8654       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8655   }
8656 
8657   return SDValue();
8658 }
8659 
8660 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8661                                                         DAGCombinerInfo &DCI)
8662                                                         const {
8663   SDValue Src = N->getOperand(0);
8664   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8665 
8666   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8667       VTSign->getVT() == MVT::i8) ||
8668       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8669       VTSign->getVT() == MVT::i16)) &&
8670       Src.hasOneUse()) {
8671     auto *M = cast<MemSDNode>(Src);
8672     SDValue Ops[] = {
8673       Src.getOperand(0), // Chain
8674       Src.getOperand(1), // rsrc
8675       Src.getOperand(2), // vindex
8676       Src.getOperand(3), // voffset
8677       Src.getOperand(4), // soffset
8678       Src.getOperand(5), // offset
8679       Src.getOperand(6),
8680       Src.getOperand(7)
8681     };
8682     // replace with BUFFER_LOAD_BYTE/SHORT
8683     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8684                                          Src.getOperand(0).getValueType());
8685     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8686                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8687     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8688                                                           ResList,
8689                                                           Ops, M->getMemoryVT(),
8690                                                           M->getMemOperand());
8691     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8692                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8693   }
8694   return SDValue();
8695 }
8696 
8697 SDValue SITargetLowering::performClassCombine(SDNode *N,
8698                                               DAGCombinerInfo &DCI) const {
8699   SelectionDAG &DAG = DCI.DAG;
8700   SDValue Mask = N->getOperand(1);
8701 
8702   // fp_class x, 0 -> false
8703   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8704     if (CMask->isNullValue())
8705       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8706   }
8707 
8708   if (N->getOperand(0).isUndef())
8709     return DAG.getUNDEF(MVT::i1);
8710 
8711   return SDValue();
8712 }
8713 
8714 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8715                                             DAGCombinerInfo &DCI) const {
8716   EVT VT = N->getValueType(0);
8717   SDValue N0 = N->getOperand(0);
8718 
8719   if (N0.isUndef())
8720     return N0;
8721 
8722   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8723                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8724     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8725                            N->getFlags());
8726   }
8727 
8728   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
8729     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
8730                            N0.getOperand(0), N->getFlags());
8731   }
8732 
8733   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8734 }
8735 
8736 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8737                                        unsigned MaxDepth) const {
8738   unsigned Opcode = Op.getOpcode();
8739   if (Opcode == ISD::FCANONICALIZE)
8740     return true;
8741 
8742   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8743     auto F = CFP->getValueAPF();
8744     if (F.isNaN() && F.isSignaling())
8745       return false;
8746     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
8747   }
8748 
8749   // If source is a result of another standard FP operation it is already in
8750   // canonical form.
8751   if (MaxDepth == 0)
8752     return false;
8753 
8754   switch (Opcode) {
8755   // These will flush denorms if required.
8756   case ISD::FADD:
8757   case ISD::FSUB:
8758   case ISD::FMUL:
8759   case ISD::FCEIL:
8760   case ISD::FFLOOR:
8761   case ISD::FMA:
8762   case ISD::FMAD:
8763   case ISD::FSQRT:
8764   case ISD::FDIV:
8765   case ISD::FREM:
8766   case ISD::FP_ROUND:
8767   case ISD::FP_EXTEND:
8768   case AMDGPUISD::FMUL_LEGACY:
8769   case AMDGPUISD::FMAD_FTZ:
8770   case AMDGPUISD::RCP:
8771   case AMDGPUISD::RSQ:
8772   case AMDGPUISD::RSQ_CLAMP:
8773   case AMDGPUISD::RCP_LEGACY:
8774   case AMDGPUISD::RSQ_LEGACY:
8775   case AMDGPUISD::RCP_IFLAG:
8776   case AMDGPUISD::TRIG_PREOP:
8777   case AMDGPUISD::DIV_SCALE:
8778   case AMDGPUISD::DIV_FMAS:
8779   case AMDGPUISD::DIV_FIXUP:
8780   case AMDGPUISD::FRACT:
8781   case AMDGPUISD::LDEXP:
8782   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8783   case AMDGPUISD::CVT_F32_UBYTE0:
8784   case AMDGPUISD::CVT_F32_UBYTE1:
8785   case AMDGPUISD::CVT_F32_UBYTE2:
8786   case AMDGPUISD::CVT_F32_UBYTE3:
8787     return true;
8788 
8789   // It can/will be lowered or combined as a bit operation.
8790   // Need to check their input recursively to handle.
8791   case ISD::FNEG:
8792   case ISD::FABS:
8793   case ISD::FCOPYSIGN:
8794     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8795 
8796   case ISD::FSIN:
8797   case ISD::FCOS:
8798   case ISD::FSINCOS:
8799     return Op.getValueType().getScalarType() != MVT::f16;
8800 
8801   case ISD::FMINNUM:
8802   case ISD::FMAXNUM:
8803   case ISD::FMINNUM_IEEE:
8804   case ISD::FMAXNUM_IEEE:
8805   case AMDGPUISD::CLAMP:
8806   case AMDGPUISD::FMED3:
8807   case AMDGPUISD::FMAX3:
8808   case AMDGPUISD::FMIN3: {
8809     // FIXME: Shouldn't treat the generic operations different based these.
8810     // However, we aren't really required to flush the result from
8811     // minnum/maxnum..
8812 
8813     // snans will be quieted, so we only need to worry about denormals.
8814     if (Subtarget->supportsMinMaxDenormModes() ||
8815         denormalsEnabledForType(DAG, Op.getValueType()))
8816       return true;
8817 
8818     // Flushing may be required.
8819     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8820     // targets need to check their input recursively.
8821 
8822     // FIXME: Does this apply with clamp? It's implemented with max.
8823     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8824       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8825         return false;
8826     }
8827 
8828     return true;
8829   }
8830   case ISD::SELECT: {
8831     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8832            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8833   }
8834   case ISD::BUILD_VECTOR: {
8835     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8836       SDValue SrcOp = Op.getOperand(i);
8837       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8838         return false;
8839     }
8840 
8841     return true;
8842   }
8843   case ISD::EXTRACT_VECTOR_ELT:
8844   case ISD::EXTRACT_SUBVECTOR: {
8845     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8846   }
8847   case ISD::INSERT_VECTOR_ELT: {
8848     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8849            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8850   }
8851   case ISD::UNDEF:
8852     // Could be anything.
8853     return false;
8854 
8855   case ISD::BITCAST: {
8856     // Hack round the mess we make when legalizing extract_vector_elt
8857     SDValue Src = Op.getOperand(0);
8858     if (Src.getValueType() == MVT::i16 &&
8859         Src.getOpcode() == ISD::TRUNCATE) {
8860       SDValue TruncSrc = Src.getOperand(0);
8861       if (TruncSrc.getValueType() == MVT::i32 &&
8862           TruncSrc.getOpcode() == ISD::BITCAST &&
8863           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8864         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8865       }
8866     }
8867 
8868     return false;
8869   }
8870   case ISD::INTRINSIC_WO_CHAIN: {
8871     unsigned IntrinsicID
8872       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8873     // TODO: Handle more intrinsics
8874     switch (IntrinsicID) {
8875     case Intrinsic::amdgcn_cvt_pkrtz:
8876     case Intrinsic::amdgcn_cubeid:
8877     case Intrinsic::amdgcn_frexp_mant:
8878     case Intrinsic::amdgcn_fdot2:
8879       return true;
8880     default:
8881       break;
8882     }
8883 
8884     LLVM_FALLTHROUGH;
8885   }
8886   default:
8887     return denormalsEnabledForType(DAG, Op.getValueType()) &&
8888            DAG.isKnownNeverSNaN(Op);
8889   }
8890 
8891   llvm_unreachable("invalid operation");
8892 }
8893 
8894 // Constant fold canonicalize.
8895 SDValue SITargetLowering::getCanonicalConstantFP(
8896   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8897   // Flush denormals to 0 if not enabled.
8898   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
8899     return DAG.getConstantFP(0.0, SL, VT);
8900 
8901   if (C.isNaN()) {
8902     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8903     if (C.isSignaling()) {
8904       // Quiet a signaling NaN.
8905       // FIXME: Is this supposed to preserve payload bits?
8906       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8907     }
8908 
8909     // Make sure it is the canonical NaN bitpattern.
8910     //
8911     // TODO: Can we use -1 as the canonical NaN value since it's an inline
8912     // immediate?
8913     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8914       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8915   }
8916 
8917   // Already canonical.
8918   return DAG.getConstantFP(C, SL, VT);
8919 }
8920 
8921 static bool vectorEltWillFoldAway(SDValue Op) {
8922   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8923 }
8924 
8925 SDValue SITargetLowering::performFCanonicalizeCombine(
8926   SDNode *N,
8927   DAGCombinerInfo &DCI) const {
8928   SelectionDAG &DAG = DCI.DAG;
8929   SDValue N0 = N->getOperand(0);
8930   EVT VT = N->getValueType(0);
8931 
8932   // fcanonicalize undef -> qnan
8933   if (N0.isUndef()) {
8934     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
8935     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8936   }
8937 
8938   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
8939     EVT VT = N->getValueType(0);
8940     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
8941   }
8942 
8943   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8944   //                                                   (fcanonicalize k)
8945   //
8946   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8947 
8948   // TODO: This could be better with wider vectors that will be split to v2f16,
8949   // and to consider uses since there aren't that many packed operations.
8950   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8951       isTypeLegal(MVT::v2f16)) {
8952     SDLoc SL(N);
8953     SDValue NewElts[2];
8954     SDValue Lo = N0.getOperand(0);
8955     SDValue Hi = N0.getOperand(1);
8956     EVT EltVT = Lo.getValueType();
8957 
8958     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
8959       for (unsigned I = 0; I != 2; ++I) {
8960         SDValue Op = N0.getOperand(I);
8961         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8962           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8963                                               CFP->getValueAPF());
8964         } else if (Op.isUndef()) {
8965           // Handled below based on what the other operand is.
8966           NewElts[I] = Op;
8967         } else {
8968           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8969         }
8970       }
8971 
8972       // If one half is undef, and one is constant, perfer a splat vector rather
8973       // than the normal qNaN. If it's a register, prefer 0.0 since that's
8974       // cheaper to use and may be free with a packed operation.
8975       if (NewElts[0].isUndef()) {
8976         if (isa<ConstantFPSDNode>(NewElts[1]))
8977           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8978             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8979       }
8980 
8981       if (NewElts[1].isUndef()) {
8982         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8983           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8984       }
8985 
8986       return DAG.getBuildVector(VT, SL, NewElts);
8987     }
8988   }
8989 
8990   unsigned SrcOpc = N0.getOpcode();
8991 
8992   // If it's free to do so, push canonicalizes further up the source, which may
8993   // find a canonical source.
8994   //
8995   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
8996   // sNaNs.
8997   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
8998     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8999     if (CRHS && N0.hasOneUse()) {
9000       SDLoc SL(N);
9001       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9002                                    N0.getOperand(0));
9003       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9004       DCI.AddToWorklist(Canon0.getNode());
9005 
9006       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9007     }
9008   }
9009 
9010   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9011 }
9012 
9013 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9014   switch (Opc) {
9015   case ISD::FMAXNUM:
9016   case ISD::FMAXNUM_IEEE:
9017     return AMDGPUISD::FMAX3;
9018   case ISD::SMAX:
9019     return AMDGPUISD::SMAX3;
9020   case ISD::UMAX:
9021     return AMDGPUISD::UMAX3;
9022   case ISD::FMINNUM:
9023   case ISD::FMINNUM_IEEE:
9024     return AMDGPUISD::FMIN3;
9025   case ISD::SMIN:
9026     return AMDGPUISD::SMIN3;
9027   case ISD::UMIN:
9028     return AMDGPUISD::UMIN3;
9029   default:
9030     llvm_unreachable("Not a min/max opcode");
9031   }
9032 }
9033 
9034 SDValue SITargetLowering::performIntMed3ImmCombine(
9035   SelectionDAG &DAG, const SDLoc &SL,
9036   SDValue Op0, SDValue Op1, bool Signed) const {
9037   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9038   if (!K1)
9039     return SDValue();
9040 
9041   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9042   if (!K0)
9043     return SDValue();
9044 
9045   if (Signed) {
9046     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9047       return SDValue();
9048   } else {
9049     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9050       return SDValue();
9051   }
9052 
9053   EVT VT = K0->getValueType(0);
9054   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9055   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9056     return DAG.getNode(Med3Opc, SL, VT,
9057                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9058   }
9059 
9060   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9061   MVT NVT = MVT::i32;
9062   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9063 
9064   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9065   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9066   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9067 
9068   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9069   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9070 }
9071 
9072 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9073   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9074     return C;
9075 
9076   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9077     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9078       return C;
9079   }
9080 
9081   return nullptr;
9082 }
9083 
9084 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9085                                                   const SDLoc &SL,
9086                                                   SDValue Op0,
9087                                                   SDValue Op1) const {
9088   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9089   if (!K1)
9090     return SDValue();
9091 
9092   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9093   if (!K0)
9094     return SDValue();
9095 
9096   // Ordered >= (although NaN inputs should have folded away by now).
9097   if (K0->getValueAPF() > K1->getValueAPF())
9098     return SDValue();
9099 
9100   const MachineFunction &MF = DAG.getMachineFunction();
9101   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9102 
9103   // TODO: Check IEEE bit enabled?
9104   EVT VT = Op0.getValueType();
9105   if (Info->getMode().DX10Clamp) {
9106     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9107     // hardware fmed3 behavior converting to a min.
9108     // FIXME: Should this be allowing -0.0?
9109     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9110       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9111   }
9112 
9113   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9114   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9115     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9116     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9117     // then give the other result, which is different from med3 with a NaN
9118     // input.
9119     SDValue Var = Op0.getOperand(0);
9120     if (!DAG.isKnownNeverSNaN(Var))
9121       return SDValue();
9122 
9123     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9124 
9125     if ((!K0->hasOneUse() ||
9126          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9127         (!K1->hasOneUse() ||
9128          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9129       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9130                          Var, SDValue(K0, 0), SDValue(K1, 0));
9131     }
9132   }
9133 
9134   return SDValue();
9135 }
9136 
9137 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9138                                                DAGCombinerInfo &DCI) const {
9139   SelectionDAG &DAG = DCI.DAG;
9140 
9141   EVT VT = N->getValueType(0);
9142   unsigned Opc = N->getOpcode();
9143   SDValue Op0 = N->getOperand(0);
9144   SDValue Op1 = N->getOperand(1);
9145 
9146   // Only do this if the inner op has one use since this will just increases
9147   // register pressure for no benefit.
9148 
9149   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9150       !VT.isVector() &&
9151       (VT == MVT::i32 || VT == MVT::f32 ||
9152        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9153     // max(max(a, b), c) -> max3(a, b, c)
9154     // min(min(a, b), c) -> min3(a, b, c)
9155     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9156       SDLoc DL(N);
9157       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9158                          DL,
9159                          N->getValueType(0),
9160                          Op0.getOperand(0),
9161                          Op0.getOperand(1),
9162                          Op1);
9163     }
9164 
9165     // Try commuted.
9166     // max(a, max(b, c)) -> max3(a, b, c)
9167     // min(a, min(b, c)) -> min3(a, b, c)
9168     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9169       SDLoc DL(N);
9170       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9171                          DL,
9172                          N->getValueType(0),
9173                          Op0,
9174                          Op1.getOperand(0),
9175                          Op1.getOperand(1));
9176     }
9177   }
9178 
9179   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9180   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9181     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9182       return Med3;
9183   }
9184 
9185   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9186     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9187       return Med3;
9188   }
9189 
9190   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9191   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9192        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9193        (Opc == AMDGPUISD::FMIN_LEGACY &&
9194         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9195       (VT == MVT::f32 || VT == MVT::f64 ||
9196        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9197        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9198       Op0.hasOneUse()) {
9199     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9200       return Res;
9201   }
9202 
9203   return SDValue();
9204 }
9205 
9206 static bool isClampZeroToOne(SDValue A, SDValue B) {
9207   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9208     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9209       // FIXME: Should this be allowing -0.0?
9210       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9211              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9212     }
9213   }
9214 
9215   return false;
9216 }
9217 
9218 // FIXME: Should only worry about snans for version with chain.
9219 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9220                                               DAGCombinerInfo &DCI) const {
9221   EVT VT = N->getValueType(0);
9222   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9223   // NaNs. With a NaN input, the order of the operands may change the result.
9224 
9225   SelectionDAG &DAG = DCI.DAG;
9226   SDLoc SL(N);
9227 
9228   SDValue Src0 = N->getOperand(0);
9229   SDValue Src1 = N->getOperand(1);
9230   SDValue Src2 = N->getOperand(2);
9231 
9232   if (isClampZeroToOne(Src0, Src1)) {
9233     // const_a, const_b, x -> clamp is safe in all cases including signaling
9234     // nans.
9235     // FIXME: Should this be allowing -0.0?
9236     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9237   }
9238 
9239   const MachineFunction &MF = DAG.getMachineFunction();
9240   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9241 
9242   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9243   // handling no dx10-clamp?
9244   if (Info->getMode().DX10Clamp) {
9245     // If NaNs is clamped to 0, we are free to reorder the inputs.
9246 
9247     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9248       std::swap(Src0, Src1);
9249 
9250     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9251       std::swap(Src1, Src2);
9252 
9253     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9254       std::swap(Src0, Src1);
9255 
9256     if (isClampZeroToOne(Src1, Src2))
9257       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9258   }
9259 
9260   return SDValue();
9261 }
9262 
9263 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9264                                                  DAGCombinerInfo &DCI) const {
9265   SDValue Src0 = N->getOperand(0);
9266   SDValue Src1 = N->getOperand(1);
9267   if (Src0.isUndef() && Src1.isUndef())
9268     return DCI.DAG.getUNDEF(N->getValueType(0));
9269   return SDValue();
9270 }
9271 
9272 SDValue SITargetLowering::performExtractVectorEltCombine(
9273   SDNode *N, DAGCombinerInfo &DCI) const {
9274   SDValue Vec = N->getOperand(0);
9275   SelectionDAG &DAG = DCI.DAG;
9276 
9277   EVT VecVT = Vec.getValueType();
9278   EVT EltVT = VecVT.getVectorElementType();
9279 
9280   if ((Vec.getOpcode() == ISD::FNEG ||
9281        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9282     SDLoc SL(N);
9283     EVT EltVT = N->getValueType(0);
9284     SDValue Idx = N->getOperand(1);
9285     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9286                               Vec.getOperand(0), Idx);
9287     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9288   }
9289 
9290   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9291   //    =>
9292   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9293   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9294   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9295   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9296     SDLoc SL(N);
9297     EVT EltVT = N->getValueType(0);
9298     SDValue Idx = N->getOperand(1);
9299     unsigned Opc = Vec.getOpcode();
9300 
9301     switch(Opc) {
9302     default:
9303       break;
9304       // TODO: Support other binary operations.
9305     case ISD::FADD:
9306     case ISD::FSUB:
9307     case ISD::FMUL:
9308     case ISD::ADD:
9309     case ISD::UMIN:
9310     case ISD::UMAX:
9311     case ISD::SMIN:
9312     case ISD::SMAX:
9313     case ISD::FMAXNUM:
9314     case ISD::FMINNUM:
9315     case ISD::FMAXNUM_IEEE:
9316     case ISD::FMINNUM_IEEE: {
9317       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9318                                  Vec.getOperand(0), Idx);
9319       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9320                                  Vec.getOperand(1), Idx);
9321 
9322       DCI.AddToWorklist(Elt0.getNode());
9323       DCI.AddToWorklist(Elt1.getNode());
9324       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9325     }
9326     }
9327   }
9328 
9329   unsigned VecSize = VecVT.getSizeInBits();
9330   unsigned EltSize = EltVT.getSizeInBits();
9331 
9332   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9333   // This elminates non-constant index and subsequent movrel or scratch access.
9334   // Sub-dword vectors of size 2 dword or less have better implementation.
9335   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9336   // instructions.
9337   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9338       !isa<ConstantSDNode>(N->getOperand(1))) {
9339     SDLoc SL(N);
9340     SDValue Idx = N->getOperand(1);
9341     SDValue V;
9342     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9343       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9344       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9345       if (I == 0)
9346         V = Elt;
9347       else
9348         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9349     }
9350     return V;
9351   }
9352 
9353   if (!DCI.isBeforeLegalize())
9354     return SDValue();
9355 
9356   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9357   // elements. This exposes more load reduction opportunities by replacing
9358   // multiple small extract_vector_elements with a single 32-bit extract.
9359   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9360   if (isa<MemSDNode>(Vec) &&
9361       EltSize <= 16 &&
9362       EltVT.isByteSized() &&
9363       VecSize > 32 &&
9364       VecSize % 32 == 0 &&
9365       Idx) {
9366     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9367 
9368     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9369     unsigned EltIdx = BitIndex / 32;
9370     unsigned LeftoverBitIdx = BitIndex % 32;
9371     SDLoc SL(N);
9372 
9373     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9374     DCI.AddToWorklist(Cast.getNode());
9375 
9376     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9377                               DAG.getConstant(EltIdx, SL, MVT::i32));
9378     DCI.AddToWorklist(Elt.getNode());
9379     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9380                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9381     DCI.AddToWorklist(Srl.getNode());
9382 
9383     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9384     DCI.AddToWorklist(Trunc.getNode());
9385     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9386   }
9387 
9388   return SDValue();
9389 }
9390 
9391 SDValue
9392 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9393                                                 DAGCombinerInfo &DCI) const {
9394   SDValue Vec = N->getOperand(0);
9395   SDValue Idx = N->getOperand(2);
9396   EVT VecVT = Vec.getValueType();
9397   EVT EltVT = VecVT.getVectorElementType();
9398   unsigned VecSize = VecVT.getSizeInBits();
9399   unsigned EltSize = EltVT.getSizeInBits();
9400 
9401   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9402   // => BUILD_VECTOR n x select (e, const-idx)
9403   // This elminates non-constant index and subsequent movrel or scratch access.
9404   // Sub-dword vectors of size 2 dword or less have better implementation.
9405   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9406   // instructions.
9407   if (isa<ConstantSDNode>(Idx) ||
9408       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9409     return SDValue();
9410 
9411   SelectionDAG &DAG = DCI.DAG;
9412   SDLoc SL(N);
9413   SDValue Ins = N->getOperand(1);
9414   EVT IdxVT = Idx.getValueType();
9415 
9416   SmallVector<SDValue, 16> Ops;
9417   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9418     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9419     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9420     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9421     Ops.push_back(V);
9422   }
9423 
9424   return DAG.getBuildVector(VecVT, SL, Ops);
9425 }
9426 
9427 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9428                                           const SDNode *N0,
9429                                           const SDNode *N1) const {
9430   EVT VT = N0->getValueType(0);
9431 
9432   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9433   // support denormals ever.
9434   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9435        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9436         getSubtarget()->hasMadF16())) &&
9437        isOperationLegal(ISD::FMAD, VT))
9438     return ISD::FMAD;
9439 
9440   const TargetOptions &Options = DAG.getTarget().Options;
9441   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9442        (N0->getFlags().hasAllowContract() &&
9443         N1->getFlags().hasAllowContract())) &&
9444       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9445     return ISD::FMA;
9446   }
9447 
9448   return 0;
9449 }
9450 
9451 // For a reassociatable opcode perform:
9452 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9453 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9454                                                SelectionDAG &DAG) const {
9455   EVT VT = N->getValueType(0);
9456   if (VT != MVT::i32 && VT != MVT::i64)
9457     return SDValue();
9458 
9459   unsigned Opc = N->getOpcode();
9460   SDValue Op0 = N->getOperand(0);
9461   SDValue Op1 = N->getOperand(1);
9462 
9463   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9464     return SDValue();
9465 
9466   if (Op0->isDivergent())
9467     std::swap(Op0, Op1);
9468 
9469   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9470     return SDValue();
9471 
9472   SDValue Op2 = Op1.getOperand(1);
9473   Op1 = Op1.getOperand(0);
9474   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9475     return SDValue();
9476 
9477   if (Op1->isDivergent())
9478     std::swap(Op1, Op2);
9479 
9480   // If either operand is constant this will conflict with
9481   // DAGCombiner::ReassociateOps().
9482   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9483       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9484     return SDValue();
9485 
9486   SDLoc SL(N);
9487   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9488   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9489 }
9490 
9491 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9492                            EVT VT,
9493                            SDValue N0, SDValue N1, SDValue N2,
9494                            bool Signed) {
9495   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9496   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9497   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9498   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9499 }
9500 
9501 SDValue SITargetLowering::performAddCombine(SDNode *N,
9502                                             DAGCombinerInfo &DCI) const {
9503   SelectionDAG &DAG = DCI.DAG;
9504   EVT VT = N->getValueType(0);
9505   SDLoc SL(N);
9506   SDValue LHS = N->getOperand(0);
9507   SDValue RHS = N->getOperand(1);
9508 
9509   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9510       && Subtarget->hasMad64_32() &&
9511       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9512       VT.getScalarSizeInBits() <= 64) {
9513     if (LHS.getOpcode() != ISD::MUL)
9514       std::swap(LHS, RHS);
9515 
9516     SDValue MulLHS = LHS.getOperand(0);
9517     SDValue MulRHS = LHS.getOperand(1);
9518     SDValue AddRHS = RHS;
9519 
9520     // TODO: Maybe restrict if SGPR inputs.
9521     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9522         numBitsUnsigned(MulRHS, DAG) <= 32) {
9523       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9524       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9525       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9526       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9527     }
9528 
9529     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9530       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9531       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9532       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9533       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9534     }
9535 
9536     return SDValue();
9537   }
9538 
9539   if (SDValue V = reassociateScalarOps(N, DAG)) {
9540     return V;
9541   }
9542 
9543   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9544     return SDValue();
9545 
9546   // add x, zext (setcc) => addcarry x, 0, setcc
9547   // add x, sext (setcc) => subcarry x, 0, setcc
9548   unsigned Opc = LHS.getOpcode();
9549   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9550       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9551     std::swap(RHS, LHS);
9552 
9553   Opc = RHS.getOpcode();
9554   switch (Opc) {
9555   default: break;
9556   case ISD::ZERO_EXTEND:
9557   case ISD::SIGN_EXTEND:
9558   case ISD::ANY_EXTEND: {
9559     auto Cond = RHS.getOperand(0);
9560     // If this won't be a real VOPC output, we would still need to insert an
9561     // extra instruction anyway.
9562     if (!isBoolSGPR(Cond))
9563       break;
9564     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9565     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9566     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9567     return DAG.getNode(Opc, SL, VTList, Args);
9568   }
9569   case ISD::ADDCARRY: {
9570     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9571     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9572     if (!C || C->getZExtValue() != 0) break;
9573     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9574     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9575   }
9576   }
9577   return SDValue();
9578 }
9579 
9580 SDValue SITargetLowering::performSubCombine(SDNode *N,
9581                                             DAGCombinerInfo &DCI) const {
9582   SelectionDAG &DAG = DCI.DAG;
9583   EVT VT = N->getValueType(0);
9584 
9585   if (VT != MVT::i32)
9586     return SDValue();
9587 
9588   SDLoc SL(N);
9589   SDValue LHS = N->getOperand(0);
9590   SDValue RHS = N->getOperand(1);
9591 
9592   // sub x, zext (setcc) => subcarry x, 0, setcc
9593   // sub x, sext (setcc) => addcarry x, 0, setcc
9594   unsigned Opc = RHS.getOpcode();
9595   switch (Opc) {
9596   default: break;
9597   case ISD::ZERO_EXTEND:
9598   case ISD::SIGN_EXTEND:
9599   case ISD::ANY_EXTEND: {
9600     auto Cond = RHS.getOperand(0);
9601     // If this won't be a real VOPC output, we would still need to insert an
9602     // extra instruction anyway.
9603     if (!isBoolSGPR(Cond))
9604       break;
9605     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9606     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9607     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
9608     return DAG.getNode(Opc, SL, VTList, Args);
9609   }
9610   }
9611 
9612   if (LHS.getOpcode() == ISD::SUBCARRY) {
9613     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9614     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9615     if (!C || !C->isNullValue())
9616       return SDValue();
9617     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9618     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9619   }
9620   return SDValue();
9621 }
9622 
9623 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9624   DAGCombinerInfo &DCI) const {
9625 
9626   if (N->getValueType(0) != MVT::i32)
9627     return SDValue();
9628 
9629   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9630   if (!C || C->getZExtValue() != 0)
9631     return SDValue();
9632 
9633   SelectionDAG &DAG = DCI.DAG;
9634   SDValue LHS = N->getOperand(0);
9635 
9636   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9637   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9638   unsigned LHSOpc = LHS.getOpcode();
9639   unsigned Opc = N->getOpcode();
9640   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9641       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9642     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9643     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9644   }
9645   return SDValue();
9646 }
9647 
9648 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9649                                              DAGCombinerInfo &DCI) const {
9650   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9651     return SDValue();
9652 
9653   SelectionDAG &DAG = DCI.DAG;
9654   EVT VT = N->getValueType(0);
9655 
9656   SDLoc SL(N);
9657   SDValue LHS = N->getOperand(0);
9658   SDValue RHS = N->getOperand(1);
9659 
9660   // These should really be instruction patterns, but writing patterns with
9661   // source modiifiers is a pain.
9662 
9663   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9664   if (LHS.getOpcode() == ISD::FADD) {
9665     SDValue A = LHS.getOperand(0);
9666     if (A == LHS.getOperand(1)) {
9667       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9668       if (FusedOp != 0) {
9669         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9670         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9671       }
9672     }
9673   }
9674 
9675   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9676   if (RHS.getOpcode() == ISD::FADD) {
9677     SDValue A = RHS.getOperand(0);
9678     if (A == RHS.getOperand(1)) {
9679       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9680       if (FusedOp != 0) {
9681         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9682         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9683       }
9684     }
9685   }
9686 
9687   return SDValue();
9688 }
9689 
9690 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9691                                              DAGCombinerInfo &DCI) const {
9692   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9693     return SDValue();
9694 
9695   SelectionDAG &DAG = DCI.DAG;
9696   SDLoc SL(N);
9697   EVT VT = N->getValueType(0);
9698   assert(!VT.isVector());
9699 
9700   // Try to get the fneg to fold into the source modifier. This undoes generic
9701   // DAG combines and folds them into the mad.
9702   //
9703   // Only do this if we are not trying to support denormals. v_mad_f32 does
9704   // not support denormals ever.
9705   SDValue LHS = N->getOperand(0);
9706   SDValue RHS = N->getOperand(1);
9707   if (LHS.getOpcode() == ISD::FADD) {
9708     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9709     SDValue A = LHS.getOperand(0);
9710     if (A == LHS.getOperand(1)) {
9711       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9712       if (FusedOp != 0){
9713         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9714         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9715 
9716         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9717       }
9718     }
9719   }
9720 
9721   if (RHS.getOpcode() == ISD::FADD) {
9722     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9723 
9724     SDValue A = RHS.getOperand(0);
9725     if (A == RHS.getOperand(1)) {
9726       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9727       if (FusedOp != 0){
9728         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9729         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9730       }
9731     }
9732   }
9733 
9734   return SDValue();
9735 }
9736 
9737 SDValue SITargetLowering::performFMACombine(SDNode *N,
9738                                             DAGCombinerInfo &DCI) const {
9739   SelectionDAG &DAG = DCI.DAG;
9740   EVT VT = N->getValueType(0);
9741   SDLoc SL(N);
9742 
9743   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9744     return SDValue();
9745 
9746   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9747   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9748   SDValue Op1 = N->getOperand(0);
9749   SDValue Op2 = N->getOperand(1);
9750   SDValue FMA = N->getOperand(2);
9751 
9752   if (FMA.getOpcode() != ISD::FMA ||
9753       Op1.getOpcode() != ISD::FP_EXTEND ||
9754       Op2.getOpcode() != ISD::FP_EXTEND)
9755     return SDValue();
9756 
9757   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9758   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9759   // is sufficient to allow generaing fdot2.
9760   const TargetOptions &Options = DAG.getTarget().Options;
9761   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9762       (N->getFlags().hasAllowContract() &&
9763        FMA->getFlags().hasAllowContract())) {
9764     Op1 = Op1.getOperand(0);
9765     Op2 = Op2.getOperand(0);
9766     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9767         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9768       return SDValue();
9769 
9770     SDValue Vec1 = Op1.getOperand(0);
9771     SDValue Idx1 = Op1.getOperand(1);
9772     SDValue Vec2 = Op2.getOperand(0);
9773 
9774     SDValue FMAOp1 = FMA.getOperand(0);
9775     SDValue FMAOp2 = FMA.getOperand(1);
9776     SDValue FMAAcc = FMA.getOperand(2);
9777 
9778     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9779         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9780       return SDValue();
9781 
9782     FMAOp1 = FMAOp1.getOperand(0);
9783     FMAOp2 = FMAOp2.getOperand(0);
9784     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9785         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9786       return SDValue();
9787 
9788     SDValue Vec3 = FMAOp1.getOperand(0);
9789     SDValue Vec4 = FMAOp2.getOperand(0);
9790     SDValue Idx2 = FMAOp1.getOperand(1);
9791 
9792     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9793         // Idx1 and Idx2 cannot be the same.
9794         Idx1 == Idx2)
9795       return SDValue();
9796 
9797     if (Vec1 == Vec2 || Vec3 == Vec4)
9798       return SDValue();
9799 
9800     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9801       return SDValue();
9802 
9803     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9804         (Vec1 == Vec4 && Vec2 == Vec3)) {
9805       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9806                          DAG.getTargetConstant(0, SL, MVT::i1));
9807     }
9808   }
9809   return SDValue();
9810 }
9811 
9812 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9813                                               DAGCombinerInfo &DCI) const {
9814   SelectionDAG &DAG = DCI.DAG;
9815   SDLoc SL(N);
9816 
9817   SDValue LHS = N->getOperand(0);
9818   SDValue RHS = N->getOperand(1);
9819   EVT VT = LHS.getValueType();
9820   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9821 
9822   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9823   if (!CRHS) {
9824     CRHS = dyn_cast<ConstantSDNode>(LHS);
9825     if (CRHS) {
9826       std::swap(LHS, RHS);
9827       CC = getSetCCSwappedOperands(CC);
9828     }
9829   }
9830 
9831   if (CRHS) {
9832     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9833         isBoolSGPR(LHS.getOperand(0))) {
9834       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9835       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9836       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9837       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9838       if ((CRHS->isAllOnesValue() &&
9839            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9840           (CRHS->isNullValue() &&
9841            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9842         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9843                            DAG.getConstant(-1, SL, MVT::i1));
9844       if ((CRHS->isAllOnesValue() &&
9845            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9846           (CRHS->isNullValue() &&
9847            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9848         return LHS.getOperand(0);
9849     }
9850 
9851     uint64_t CRHSVal = CRHS->getZExtValue();
9852     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9853         LHS.getOpcode() == ISD::SELECT &&
9854         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9855         isa<ConstantSDNode>(LHS.getOperand(2)) &&
9856         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9857         isBoolSGPR(LHS.getOperand(0))) {
9858       // Given CT != FT:
9859       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9860       // setcc (select cc, CT, CF), CF, ne => cc
9861       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9862       // setcc (select cc, CT, CF), CT, eq => cc
9863       uint64_t CT = LHS.getConstantOperandVal(1);
9864       uint64_t CF = LHS.getConstantOperandVal(2);
9865 
9866       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9867           (CT == CRHSVal && CC == ISD::SETNE))
9868         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9869                            DAG.getConstant(-1, SL, MVT::i1));
9870       if ((CF == CRHSVal && CC == ISD::SETNE) ||
9871           (CT == CRHSVal && CC == ISD::SETEQ))
9872         return LHS.getOperand(0);
9873     }
9874   }
9875 
9876   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9877                                            VT != MVT::f16))
9878     return SDValue();
9879 
9880   // Match isinf/isfinite pattern
9881   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
9882   // (fcmp one (fabs x), inf) -> (fp_class x,
9883   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9884   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
9885     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9886     if (!CRHS)
9887       return SDValue();
9888 
9889     const APFloat &APF = CRHS->getValueAPF();
9890     if (APF.isInfinity() && !APF.isNegative()) {
9891       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9892                                  SIInstrFlags::N_INFINITY;
9893       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9894                                     SIInstrFlags::P_ZERO |
9895                                     SIInstrFlags::N_NORMAL |
9896                                     SIInstrFlags::P_NORMAL |
9897                                     SIInstrFlags::N_SUBNORMAL |
9898                                     SIInstrFlags::P_SUBNORMAL;
9899       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
9900       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9901                          DAG.getConstant(Mask, SL, MVT::i32));
9902     }
9903   }
9904 
9905   return SDValue();
9906 }
9907 
9908 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9909                                                      DAGCombinerInfo &DCI) const {
9910   SelectionDAG &DAG = DCI.DAG;
9911   SDLoc SL(N);
9912   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9913 
9914   SDValue Src = N->getOperand(0);
9915   SDValue Shift = N->getOperand(0);
9916   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
9917     Shift = Shift.getOperand(0);
9918 
9919   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
9920     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
9921     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
9922     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9923     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9924     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
9925     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
9926       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
9927                                  SDLoc(Shift.getOperand(0)), MVT::i32);
9928 
9929       unsigned ShiftOffset = 8 * Offset;
9930       if (Shift.getOpcode() == ISD::SHL)
9931         ShiftOffset -= C->getZExtValue();
9932       else
9933         ShiftOffset += C->getZExtValue();
9934 
9935       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
9936         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
9937                            MVT::f32, Shift);
9938       }
9939     }
9940   }
9941 
9942   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9943   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9944   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
9945     // We simplified Src. If this node is not dead, visit it again so it is
9946     // folded properly.
9947     if (N->getOpcode() != ISD::DELETED_NODE)
9948       DCI.AddToWorklist(N);
9949     return SDValue(N, 0);
9950   }
9951 
9952   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
9953   if (SDValue DemandedSrc =
9954           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
9955     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
9956 
9957   return SDValue();
9958 }
9959 
9960 SDValue SITargetLowering::performClampCombine(SDNode *N,
9961                                               DAGCombinerInfo &DCI) const {
9962   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
9963   if (!CSrc)
9964     return SDValue();
9965 
9966   const MachineFunction &MF = DCI.DAG.getMachineFunction();
9967   const APFloat &F = CSrc->getValueAPF();
9968   APFloat Zero = APFloat::getZero(F.getSemantics());
9969   if (F < Zero ||
9970       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
9971     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9972   }
9973 
9974   APFloat One(F.getSemantics(), "1.0");
9975   if (F > One)
9976     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9977 
9978   return SDValue(CSrc, 0);
9979 }
9980 
9981 
9982 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
9983                                             DAGCombinerInfo &DCI) const {
9984   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9985     return SDValue();
9986   switch (N->getOpcode()) {
9987   default:
9988     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9989   case ISD::ADD:
9990     return performAddCombine(N, DCI);
9991   case ISD::SUB:
9992     return performSubCombine(N, DCI);
9993   case ISD::ADDCARRY:
9994   case ISD::SUBCARRY:
9995     return performAddCarrySubCarryCombine(N, DCI);
9996   case ISD::FADD:
9997     return performFAddCombine(N, DCI);
9998   case ISD::FSUB:
9999     return performFSubCombine(N, DCI);
10000   case ISD::SETCC:
10001     return performSetCCCombine(N, DCI);
10002   case ISD::FMAXNUM:
10003   case ISD::FMINNUM:
10004   case ISD::FMAXNUM_IEEE:
10005   case ISD::FMINNUM_IEEE:
10006   case ISD::SMAX:
10007   case ISD::SMIN:
10008   case ISD::UMAX:
10009   case ISD::UMIN:
10010   case AMDGPUISD::FMIN_LEGACY:
10011   case AMDGPUISD::FMAX_LEGACY:
10012     return performMinMaxCombine(N, DCI);
10013   case ISD::FMA:
10014     return performFMACombine(N, DCI);
10015   case ISD::LOAD: {
10016     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10017       return Widended;
10018     LLVM_FALLTHROUGH;
10019   }
10020   case ISD::STORE:
10021   case ISD::ATOMIC_LOAD:
10022   case ISD::ATOMIC_STORE:
10023   case ISD::ATOMIC_CMP_SWAP:
10024   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10025   case ISD::ATOMIC_SWAP:
10026   case ISD::ATOMIC_LOAD_ADD:
10027   case ISD::ATOMIC_LOAD_SUB:
10028   case ISD::ATOMIC_LOAD_AND:
10029   case ISD::ATOMIC_LOAD_OR:
10030   case ISD::ATOMIC_LOAD_XOR:
10031   case ISD::ATOMIC_LOAD_NAND:
10032   case ISD::ATOMIC_LOAD_MIN:
10033   case ISD::ATOMIC_LOAD_MAX:
10034   case ISD::ATOMIC_LOAD_UMIN:
10035   case ISD::ATOMIC_LOAD_UMAX:
10036   case ISD::ATOMIC_LOAD_FADD:
10037   case AMDGPUISD::ATOMIC_INC:
10038   case AMDGPUISD::ATOMIC_DEC:
10039   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10040   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10041     if (DCI.isBeforeLegalize())
10042       break;
10043     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10044   case ISD::AND:
10045     return performAndCombine(N, DCI);
10046   case ISD::OR:
10047     return performOrCombine(N, DCI);
10048   case ISD::XOR:
10049     return performXorCombine(N, DCI);
10050   case ISD::ZERO_EXTEND:
10051     return performZeroExtendCombine(N, DCI);
10052   case ISD::SIGN_EXTEND_INREG:
10053     return performSignExtendInRegCombine(N , DCI);
10054   case AMDGPUISD::FP_CLASS:
10055     return performClassCombine(N, DCI);
10056   case ISD::FCANONICALIZE:
10057     return performFCanonicalizeCombine(N, DCI);
10058   case AMDGPUISD::RCP:
10059     return performRcpCombine(N, DCI);
10060   case AMDGPUISD::FRACT:
10061   case AMDGPUISD::RSQ:
10062   case AMDGPUISD::RCP_LEGACY:
10063   case AMDGPUISD::RSQ_LEGACY:
10064   case AMDGPUISD::RCP_IFLAG:
10065   case AMDGPUISD::RSQ_CLAMP:
10066   case AMDGPUISD::LDEXP: {
10067     SDValue Src = N->getOperand(0);
10068     if (Src.isUndef())
10069       return Src;
10070     break;
10071   }
10072   case ISD::SINT_TO_FP:
10073   case ISD::UINT_TO_FP:
10074     return performUCharToFloatCombine(N, DCI);
10075   case AMDGPUISD::CVT_F32_UBYTE0:
10076   case AMDGPUISD::CVT_F32_UBYTE1:
10077   case AMDGPUISD::CVT_F32_UBYTE2:
10078   case AMDGPUISD::CVT_F32_UBYTE3:
10079     return performCvtF32UByteNCombine(N, DCI);
10080   case AMDGPUISD::FMED3:
10081     return performFMed3Combine(N, DCI);
10082   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10083     return performCvtPkRTZCombine(N, DCI);
10084   case AMDGPUISD::CLAMP:
10085     return performClampCombine(N, DCI);
10086   case ISD::SCALAR_TO_VECTOR: {
10087     SelectionDAG &DAG = DCI.DAG;
10088     EVT VT = N->getValueType(0);
10089 
10090     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10091     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10092       SDLoc SL(N);
10093       SDValue Src = N->getOperand(0);
10094       EVT EltVT = Src.getValueType();
10095       if (EltVT == MVT::f16)
10096         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10097 
10098       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10099       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10100     }
10101 
10102     break;
10103   }
10104   case ISD::EXTRACT_VECTOR_ELT:
10105     return performExtractVectorEltCombine(N, DCI);
10106   case ISD::INSERT_VECTOR_ELT:
10107     return performInsertVectorEltCombine(N, DCI);
10108   }
10109   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10110 }
10111 
10112 /// Helper function for adjustWritemask
10113 static unsigned SubIdx2Lane(unsigned Idx) {
10114   switch (Idx) {
10115   default: return 0;
10116   case AMDGPU::sub0: return 0;
10117   case AMDGPU::sub1: return 1;
10118   case AMDGPU::sub2: return 2;
10119   case AMDGPU::sub3: return 3;
10120   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10121   }
10122 }
10123 
10124 /// Adjust the writemask of MIMG instructions
10125 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10126                                           SelectionDAG &DAG) const {
10127   unsigned Opcode = Node->getMachineOpcode();
10128 
10129   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10130   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10131   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10132     return Node; // not implemented for D16
10133 
10134   SDNode *Users[5] = { nullptr };
10135   unsigned Lane = 0;
10136   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10137   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10138   unsigned NewDmask = 0;
10139   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10140   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10141   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10142                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10143   unsigned TFCLane = 0;
10144   bool HasChain = Node->getNumValues() > 1;
10145 
10146   if (OldDmask == 0) {
10147     // These are folded out, but on the chance it happens don't assert.
10148     return Node;
10149   }
10150 
10151   unsigned OldBitsSet = countPopulation(OldDmask);
10152   // Work out which is the TFE/LWE lane if that is enabled.
10153   if (UsesTFC) {
10154     TFCLane = OldBitsSet;
10155   }
10156 
10157   // Try to figure out the used register components
10158   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10159        I != E; ++I) {
10160 
10161     // Don't look at users of the chain.
10162     if (I.getUse().getResNo() != 0)
10163       continue;
10164 
10165     // Abort if we can't understand the usage
10166     if (!I->isMachineOpcode() ||
10167         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10168       return Node;
10169 
10170     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10171     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10172     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10173     // set, etc.
10174     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10175 
10176     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10177     if (UsesTFC && Lane == TFCLane) {
10178       Users[Lane] = *I;
10179     } else {
10180       // Set which texture component corresponds to the lane.
10181       unsigned Comp;
10182       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10183         Comp = countTrailingZeros(Dmask);
10184         Dmask &= ~(1 << Comp);
10185       }
10186 
10187       // Abort if we have more than one user per component.
10188       if (Users[Lane])
10189         return Node;
10190 
10191       Users[Lane] = *I;
10192       NewDmask |= 1 << Comp;
10193     }
10194   }
10195 
10196   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10197   bool NoChannels = !NewDmask;
10198   if (NoChannels) {
10199     if (!UsesTFC) {
10200       // No uses of the result and not using TFC. Then do nothing.
10201       return Node;
10202     }
10203     // If the original dmask has one channel - then nothing to do
10204     if (OldBitsSet == 1)
10205       return Node;
10206     // Use an arbitrary dmask - required for the instruction to work
10207     NewDmask = 1;
10208   }
10209   // Abort if there's no change
10210   if (NewDmask == OldDmask)
10211     return Node;
10212 
10213   unsigned BitsSet = countPopulation(NewDmask);
10214 
10215   // Check for TFE or LWE - increase the number of channels by one to account
10216   // for the extra return value
10217   // This will need adjustment for D16 if this is also included in
10218   // adjustWriteMask (this function) but at present D16 are excluded.
10219   unsigned NewChannels = BitsSet + UsesTFC;
10220 
10221   int NewOpcode =
10222       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10223   assert(NewOpcode != -1 &&
10224          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10225          "failed to find equivalent MIMG op");
10226 
10227   // Adjust the writemask in the node
10228   SmallVector<SDValue, 12> Ops;
10229   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10230   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10231   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10232 
10233   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10234 
10235   MVT ResultVT = NewChannels == 1 ?
10236     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10237                            NewChannels == 5 ? 8 : NewChannels);
10238   SDVTList NewVTList = HasChain ?
10239     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10240 
10241 
10242   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10243                                               NewVTList, Ops);
10244 
10245   if (HasChain) {
10246     // Update chain.
10247     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10248     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10249   }
10250 
10251   if (NewChannels == 1) {
10252     assert(Node->hasNUsesOfValue(1, 0));
10253     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10254                                       SDLoc(Node), Users[Lane]->getValueType(0),
10255                                       SDValue(NewNode, 0));
10256     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10257     return nullptr;
10258   }
10259 
10260   // Update the users of the node with the new indices
10261   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10262     SDNode *User = Users[i];
10263     if (!User) {
10264       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10265       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10266       if (i || !NoChannels)
10267         continue;
10268     } else {
10269       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10270       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10271     }
10272 
10273     switch (Idx) {
10274     default: break;
10275     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10276     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10277     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10278     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10279     }
10280   }
10281 
10282   DAG.RemoveDeadNode(Node);
10283   return nullptr;
10284 }
10285 
10286 static bool isFrameIndexOp(SDValue Op) {
10287   if (Op.getOpcode() == ISD::AssertZext)
10288     Op = Op.getOperand(0);
10289 
10290   return isa<FrameIndexSDNode>(Op);
10291 }
10292 
10293 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10294 /// with frame index operands.
10295 /// LLVM assumes that inputs are to these instructions are registers.
10296 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10297                                                         SelectionDAG &DAG) const {
10298   if (Node->getOpcode() == ISD::CopyToReg) {
10299     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10300     SDValue SrcVal = Node->getOperand(2);
10301 
10302     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10303     // to try understanding copies to physical registers.
10304     if (SrcVal.getValueType() == MVT::i1 &&
10305         Register::isPhysicalRegister(DestReg->getReg())) {
10306       SDLoc SL(Node);
10307       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10308       SDValue VReg = DAG.getRegister(
10309         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10310 
10311       SDNode *Glued = Node->getGluedNode();
10312       SDValue ToVReg
10313         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10314                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10315       SDValue ToResultReg
10316         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10317                            VReg, ToVReg.getValue(1));
10318       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10319       DAG.RemoveDeadNode(Node);
10320       return ToResultReg.getNode();
10321     }
10322   }
10323 
10324   SmallVector<SDValue, 8> Ops;
10325   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10326     if (!isFrameIndexOp(Node->getOperand(i))) {
10327       Ops.push_back(Node->getOperand(i));
10328       continue;
10329     }
10330 
10331     SDLoc DL(Node);
10332     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10333                                      Node->getOperand(i).getValueType(),
10334                                      Node->getOperand(i)), 0));
10335   }
10336 
10337   return DAG.UpdateNodeOperands(Node, Ops);
10338 }
10339 
10340 /// Fold the instructions after selecting them.
10341 /// Returns null if users were already updated.
10342 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10343                                           SelectionDAG &DAG) const {
10344   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10345   unsigned Opcode = Node->getMachineOpcode();
10346 
10347   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10348       !TII->isGather4(Opcode)) {
10349     return adjustWritemask(Node, DAG);
10350   }
10351 
10352   if (Opcode == AMDGPU::INSERT_SUBREG ||
10353       Opcode == AMDGPU::REG_SEQUENCE) {
10354     legalizeTargetIndependentNode(Node, DAG);
10355     return Node;
10356   }
10357 
10358   switch (Opcode) {
10359   case AMDGPU::V_DIV_SCALE_F32:
10360   case AMDGPU::V_DIV_SCALE_F64: {
10361     // Satisfy the operand register constraint when one of the inputs is
10362     // undefined. Ordinarily each undef value will have its own implicit_def of
10363     // a vreg, so force these to use a single register.
10364     SDValue Src0 = Node->getOperand(0);
10365     SDValue Src1 = Node->getOperand(1);
10366     SDValue Src2 = Node->getOperand(2);
10367 
10368     if ((Src0.isMachineOpcode() &&
10369          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10370         (Src0 == Src1 || Src0 == Src2))
10371       break;
10372 
10373     MVT VT = Src0.getValueType().getSimpleVT();
10374     const TargetRegisterClass *RC =
10375         getRegClassFor(VT, Src0.getNode()->isDivergent());
10376 
10377     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10378     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10379 
10380     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10381                                       UndefReg, Src0, SDValue());
10382 
10383     // src0 must be the same register as src1 or src2, even if the value is
10384     // undefined, so make sure we don't violate this constraint.
10385     if (Src0.isMachineOpcode() &&
10386         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10387       if (Src1.isMachineOpcode() &&
10388           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10389         Src0 = Src1;
10390       else if (Src2.isMachineOpcode() &&
10391                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10392         Src0 = Src2;
10393       else {
10394         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10395         Src0 = UndefReg;
10396         Src1 = UndefReg;
10397       }
10398     } else
10399       break;
10400 
10401     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10402     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10403       Ops.push_back(Node->getOperand(I));
10404 
10405     Ops.push_back(ImpDef.getValue(1));
10406     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10407   }
10408   default:
10409     break;
10410   }
10411 
10412   return Node;
10413 }
10414 
10415 /// Assign the register class depending on the number of
10416 /// bits set in the writemask
10417 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10418                                                      SDNode *Node) const {
10419   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10420 
10421   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10422 
10423   if (TII->isVOP3(MI.getOpcode())) {
10424     // Make sure constant bus requirements are respected.
10425     TII->legalizeOperandsVOP3(MRI, MI);
10426 
10427     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10428     // This saves a chain-copy of registers and better ballance register
10429     // use between vgpr and agpr as agpr tuples tend to be big.
10430     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10431       unsigned Opc = MI.getOpcode();
10432       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10433       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10434                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10435         if (I == -1)
10436           break;
10437         MachineOperand &Op = MI.getOperand(I);
10438         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10439              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10440             !Register::isVirtualRegister(Op.getReg()) ||
10441             !TRI->isAGPR(MRI, Op.getReg()))
10442           continue;
10443         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10444         if (!Src || !Src->isCopy() ||
10445             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10446           continue;
10447         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10448         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10449         // All uses of agpr64 and agpr32 can also accept vgpr except for
10450         // v_accvgpr_read, but we do not produce agpr reads during selection,
10451         // so no use checks are needed.
10452         MRI.setRegClass(Op.getReg(), NewRC);
10453       }
10454     }
10455 
10456     return;
10457   }
10458 
10459   // Replace unused atomics with the no return version.
10460   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10461   if (NoRetAtomicOp != -1) {
10462     if (!Node->hasAnyUseOfValue(0)) {
10463       MI.setDesc(TII->get(NoRetAtomicOp));
10464       MI.RemoveOperand(0);
10465       return;
10466     }
10467 
10468     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10469     // instruction, because the return type of these instructions is a vec2 of
10470     // the memory type, so it can be tied to the input operand.
10471     // This means these instructions always have a use, so we need to add a
10472     // special case to check if the atomic has only one extract_subreg use,
10473     // which itself has no uses.
10474     if ((Node->hasNUsesOfValue(1, 0) &&
10475          Node->use_begin()->isMachineOpcode() &&
10476          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10477          !Node->use_begin()->hasAnyUseOfValue(0))) {
10478       Register Def = MI.getOperand(0).getReg();
10479 
10480       // Change this into a noret atomic.
10481       MI.setDesc(TII->get(NoRetAtomicOp));
10482       MI.RemoveOperand(0);
10483 
10484       // If we only remove the def operand from the atomic instruction, the
10485       // extract_subreg will be left with a use of a vreg without a def.
10486       // So we need to insert an implicit_def to avoid machine verifier
10487       // errors.
10488       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10489               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10490     }
10491     return;
10492   }
10493 }
10494 
10495 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10496                               uint64_t Val) {
10497   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10498   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10499 }
10500 
10501 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10502                                                 const SDLoc &DL,
10503                                                 SDValue Ptr) const {
10504   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10505 
10506   // Build the half of the subregister with the constants before building the
10507   // full 128-bit register. If we are building multiple resource descriptors,
10508   // this will allow CSEing of the 2-component register.
10509   const SDValue Ops0[] = {
10510     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10511     buildSMovImm32(DAG, DL, 0),
10512     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10513     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10514     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10515   };
10516 
10517   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10518                                                 MVT::v2i32, Ops0), 0);
10519 
10520   // Combine the constants and the pointer.
10521   const SDValue Ops1[] = {
10522     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10523     Ptr,
10524     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10525     SubRegHi,
10526     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10527   };
10528 
10529   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10530 }
10531 
10532 /// Return a resource descriptor with the 'Add TID' bit enabled
10533 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10534 ///        of the resource descriptor) to create an offset, which is added to
10535 ///        the resource pointer.
10536 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10537                                            SDValue Ptr, uint32_t RsrcDword1,
10538                                            uint64_t RsrcDword2And3) const {
10539   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10540   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10541   if (RsrcDword1) {
10542     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10543                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10544                     0);
10545   }
10546 
10547   SDValue DataLo = buildSMovImm32(DAG, DL,
10548                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10549   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10550 
10551   const SDValue Ops[] = {
10552     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10553     PtrLo,
10554     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10555     PtrHi,
10556     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10557     DataLo,
10558     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10559     DataHi,
10560     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10561   };
10562 
10563   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10564 }
10565 
10566 //===----------------------------------------------------------------------===//
10567 //                         SI Inline Assembly Support
10568 //===----------------------------------------------------------------------===//
10569 
10570 std::pair<unsigned, const TargetRegisterClass *>
10571 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10572                                                StringRef Constraint,
10573                                                MVT VT) const {
10574   const TargetRegisterClass *RC = nullptr;
10575   if (Constraint.size() == 1) {
10576     switch (Constraint[0]) {
10577     default:
10578       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10579     case 's':
10580     case 'r':
10581       switch (VT.getSizeInBits()) {
10582       default:
10583         return std::make_pair(0U, nullptr);
10584       case 32:
10585       case 16:
10586         RC = &AMDGPU::SReg_32RegClass;
10587         break;
10588       case 64:
10589         RC = &AMDGPU::SGPR_64RegClass;
10590         break;
10591       case 96:
10592         RC = &AMDGPU::SReg_96RegClass;
10593         break;
10594       case 128:
10595         RC = &AMDGPU::SGPR_128RegClass;
10596         break;
10597       case 160:
10598         RC = &AMDGPU::SReg_160RegClass;
10599         break;
10600       case 256:
10601         RC = &AMDGPU::SReg_256RegClass;
10602         break;
10603       case 512:
10604         RC = &AMDGPU::SReg_512RegClass;
10605         break;
10606       }
10607       break;
10608     case 'v':
10609       switch (VT.getSizeInBits()) {
10610       default:
10611         return std::make_pair(0U, nullptr);
10612       case 32:
10613       case 16:
10614         RC = &AMDGPU::VGPR_32RegClass;
10615         break;
10616       case 64:
10617         RC = &AMDGPU::VReg_64RegClass;
10618         break;
10619       case 96:
10620         RC = &AMDGPU::VReg_96RegClass;
10621         break;
10622       case 128:
10623         RC = &AMDGPU::VReg_128RegClass;
10624         break;
10625       case 160:
10626         RC = &AMDGPU::VReg_160RegClass;
10627         break;
10628       case 256:
10629         RC = &AMDGPU::VReg_256RegClass;
10630         break;
10631       case 512:
10632         RC = &AMDGPU::VReg_512RegClass;
10633         break;
10634       }
10635       break;
10636     case 'a':
10637       if (!Subtarget->hasMAIInsts())
10638         break;
10639       switch (VT.getSizeInBits()) {
10640       default:
10641         return std::make_pair(0U, nullptr);
10642       case 32:
10643       case 16:
10644         RC = &AMDGPU::AGPR_32RegClass;
10645         break;
10646       case 64:
10647         RC = &AMDGPU::AReg_64RegClass;
10648         break;
10649       case 128:
10650         RC = &AMDGPU::AReg_128RegClass;
10651         break;
10652       case 512:
10653         RC = &AMDGPU::AReg_512RegClass;
10654         break;
10655       case 1024:
10656         RC = &AMDGPU::AReg_1024RegClass;
10657         // v32 types are not legal but we support them here.
10658         return std::make_pair(0U, RC);
10659       }
10660       break;
10661     }
10662     // We actually support i128, i16 and f16 as inline parameters
10663     // even if they are not reported as legal
10664     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10665                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10666       return std::make_pair(0U, RC);
10667   }
10668 
10669   if (Constraint.size() > 1) {
10670     if (Constraint[1] == 'v') {
10671       RC = &AMDGPU::VGPR_32RegClass;
10672     } else if (Constraint[1] == 's') {
10673       RC = &AMDGPU::SGPR_32RegClass;
10674     } else if (Constraint[1] == 'a') {
10675       RC = &AMDGPU::AGPR_32RegClass;
10676     }
10677 
10678     if (RC) {
10679       uint32_t Idx;
10680       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10681       if (!Failed && Idx < RC->getNumRegs())
10682         return std::make_pair(RC->getRegister(Idx), RC);
10683     }
10684   }
10685 
10686   // FIXME: Returns VS_32 for physical SGPR constraints
10687   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10688 }
10689 
10690 SITargetLowering::ConstraintType
10691 SITargetLowering::getConstraintType(StringRef Constraint) const {
10692   if (Constraint.size() == 1) {
10693     switch (Constraint[0]) {
10694     default: break;
10695     case 's':
10696     case 'v':
10697     case 'a':
10698       return C_RegisterClass;
10699     }
10700   }
10701   return TargetLowering::getConstraintType(Constraint);
10702 }
10703 
10704 // Figure out which registers should be reserved for stack access. Only after
10705 // the function is legalized do we know all of the non-spill stack objects or if
10706 // calls are present.
10707 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10708   MachineRegisterInfo &MRI = MF.getRegInfo();
10709   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10710   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10711   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10712 
10713   if (Info->isEntryFunction()) {
10714     // Callable functions have fixed registers used for stack access.
10715     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10716   }
10717 
10718   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10719                              Info->getStackPtrOffsetReg()));
10720   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10721     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10722 
10723   // We need to worry about replacing the default register with itself in case
10724   // of MIR testcases missing the MFI.
10725   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10726     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10727 
10728   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10729     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10730 
10731   Info->limitOccupancy(MF);
10732 
10733   if (ST.isWave32() && !MF.empty()) {
10734     // Add VCC_HI def because many instructions marked as imp-use VCC where
10735     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10736     // having a use of undef.
10737 
10738     const SIInstrInfo *TII = ST.getInstrInfo();
10739     DebugLoc DL;
10740 
10741     MachineBasicBlock &MBB = MF.front();
10742     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10743     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10744 
10745     for (auto &MBB : MF) {
10746       for (auto &MI : MBB) {
10747         TII->fixImplicitOperands(MI);
10748       }
10749     }
10750   }
10751 
10752   TargetLoweringBase::finalizeLowering(MF);
10753 }
10754 
10755 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10756                                                      KnownBits &Known,
10757                                                      const APInt &DemandedElts,
10758                                                      const SelectionDAG &DAG,
10759                                                      unsigned Depth) const {
10760   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10761                                                 DAG, Depth);
10762 
10763   // Set the high bits to zero based on the maximum allowed scratch size per
10764   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10765   // calculation won't overflow, so assume the sign bit is never set.
10766   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10767 }
10768 
10769 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10770   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10771   const Align CacheLineAlign = Align(64);
10772 
10773   // Pre-GFX10 target did not benefit from loop alignment
10774   if (!ML || DisableLoopAlignment ||
10775       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10776       getSubtarget()->hasInstFwdPrefetchBug())
10777     return PrefAlign;
10778 
10779   // On GFX10 I$ is 4 x 64 bytes cache lines.
10780   // By default prefetcher keeps one cache line behind and reads two ahead.
10781   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10782   // behind and one ahead.
10783   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10784   // If loop fits 64 bytes it always spans no more than two cache lines and
10785   // does not need an alignment.
10786   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10787   // Else if loop is less or equal 192 bytes we need two lines behind.
10788 
10789   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10790   const MachineBasicBlock *Header = ML->getHeader();
10791   if (Header->getAlignment() != PrefAlign)
10792     return Header->getAlignment(); // Already processed.
10793 
10794   unsigned LoopSize = 0;
10795   for (const MachineBasicBlock *MBB : ML->blocks()) {
10796     // If inner loop block is aligned assume in average half of the alignment
10797     // size to be added as nops.
10798     if (MBB != Header)
10799       LoopSize += MBB->getAlignment().value() / 2;
10800 
10801     for (const MachineInstr &MI : *MBB) {
10802       LoopSize += TII->getInstSizeInBytes(MI);
10803       if (LoopSize > 192)
10804         return PrefAlign;
10805     }
10806   }
10807 
10808   if (LoopSize <= 64)
10809     return PrefAlign;
10810 
10811   if (LoopSize <= 128)
10812     return CacheLineAlign;
10813 
10814   // If any of parent loops is surrounded by prefetch instructions do not
10815   // insert new for inner loop, which would reset parent's settings.
10816   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10817     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10818       auto I = Exit->getFirstNonDebugInstr();
10819       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10820         return CacheLineAlign;
10821     }
10822   }
10823 
10824   MachineBasicBlock *Pre = ML->getLoopPreheader();
10825   MachineBasicBlock *Exit = ML->getExitBlock();
10826 
10827   if (Pre && Exit) {
10828     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10829             TII->get(AMDGPU::S_INST_PREFETCH))
10830       .addImm(1); // prefetch 2 lines behind PC
10831 
10832     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10833             TII->get(AMDGPU::S_INST_PREFETCH))
10834       .addImm(2); // prefetch 1 line behind PC
10835   }
10836 
10837   return CacheLineAlign;
10838 }
10839 
10840 LLVM_ATTRIBUTE_UNUSED
10841 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10842   assert(N->getOpcode() == ISD::CopyFromReg);
10843   do {
10844     // Follow the chain until we find an INLINEASM node.
10845     N = N->getOperand(0).getNode();
10846     if (N->getOpcode() == ISD::INLINEASM ||
10847         N->getOpcode() == ISD::INLINEASM_BR)
10848       return true;
10849   } while (N->getOpcode() == ISD::CopyFromReg);
10850   return false;
10851 }
10852 
10853 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10854   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10855 {
10856   switch (N->getOpcode()) {
10857     case ISD::CopyFromReg:
10858     {
10859       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10860       const MachineFunction * MF = FLI->MF;
10861       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10862       const MachineRegisterInfo &MRI = MF->getRegInfo();
10863       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10864       Register Reg = R->getReg();
10865       if (Reg.isPhysical())
10866         return !TRI.isSGPRReg(MRI, Reg);
10867 
10868       if (MRI.isLiveIn(Reg)) {
10869         // workitem.id.x workitem.id.y workitem.id.z
10870         // Any VGPR formal argument is also considered divergent
10871         if (!TRI.isSGPRReg(MRI, Reg))
10872           return true;
10873         // Formal arguments of non-entry functions
10874         // are conservatively considered divergent
10875         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10876           return true;
10877         return false;
10878       }
10879       const Value *V = FLI->getValueFromVirtualReg(Reg);
10880       if (V)
10881         return KDA->isDivergent(V);
10882       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10883       return !TRI.isSGPRReg(MRI, Reg);
10884     }
10885     break;
10886     case ISD::LOAD: {
10887       const LoadSDNode *L = cast<LoadSDNode>(N);
10888       unsigned AS = L->getAddressSpace();
10889       // A flat load may access private memory.
10890       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10891     } break;
10892     case ISD::CALLSEQ_END:
10893     return true;
10894     break;
10895     case ISD::INTRINSIC_WO_CHAIN:
10896     {
10897 
10898     }
10899       return AMDGPU::isIntrinsicSourceOfDivergence(
10900       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10901     case ISD::INTRINSIC_W_CHAIN:
10902       return AMDGPU::isIntrinsicSourceOfDivergence(
10903       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10904   }
10905   return false;
10906 }
10907 
10908 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
10909                                                EVT VT) const {
10910   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10911   case MVT::f32:
10912     return hasFP32Denormals(DAG.getMachineFunction());
10913   case MVT::f64:
10914   case MVT::f16:
10915     return hasFP64FP16Denormals(DAG.getMachineFunction());
10916   default:
10917     return false;
10918   }
10919 }
10920 
10921 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
10922                                                     const SelectionDAG &DAG,
10923                                                     bool SNaN,
10924                                                     unsigned Depth) const {
10925   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
10926     const MachineFunction &MF = DAG.getMachineFunction();
10927     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10928 
10929     if (Info->getMode().DX10Clamp)
10930       return true; // Clamped to 0.
10931     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10932   }
10933 
10934   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
10935                                                             SNaN, Depth);
10936 }
10937 
10938 TargetLowering::AtomicExpansionKind
10939 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
10940   switch (RMW->getOperation()) {
10941   case AtomicRMWInst::FAdd: {
10942     Type *Ty = RMW->getType();
10943 
10944     // We don't have a way to support 16-bit atomics now, so just leave them
10945     // as-is.
10946     if (Ty->isHalfTy())
10947       return AtomicExpansionKind::None;
10948 
10949     if (!Ty->isFloatTy())
10950       return AtomicExpansionKind::CmpXChg;
10951 
10952     // TODO: Do have these for flat. Older targets also had them for buffers.
10953     unsigned AS = RMW->getPointerAddressSpace();
10954 
10955     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
10956       return RMW->use_empty() ? AtomicExpansionKind::None :
10957                                 AtomicExpansionKind::CmpXChg;
10958     }
10959 
10960     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10961       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
10962   }
10963   default:
10964     break;
10965   }
10966 
10967   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
10968 }
10969 
10970 const TargetRegisterClass *
10971 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
10972   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
10973   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10974   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
10975     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
10976                                                : &AMDGPU::SReg_32RegClass;
10977   if (!TRI->isSGPRClass(RC) && !isDivergent)
10978     return TRI->getEquivalentSGPRClass(RC);
10979   else if (TRI->isSGPRClass(RC) && isDivergent)
10980     return TRI->getEquivalentVGPRClass(RC);
10981 
10982   return RC;
10983 }
10984 
10985 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
10986                       unsigned WaveSize) {
10987   // FIXME: We asssume we never cast the mask results of a control flow
10988   // intrinsic.
10989   // Early exit if the type won't be consistent as a compile time hack.
10990   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
10991   if (!IT || IT->getBitWidth() != WaveSize)
10992     return false;
10993 
10994   if (!isa<Instruction>(V))
10995     return false;
10996   if (!Visited.insert(V).second)
10997     return false;
10998   bool Result = false;
10999   for (auto U : V->users()) {
11000     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11001       if (V == U->getOperand(1)) {
11002         switch (Intrinsic->getIntrinsicID()) {
11003         default:
11004           Result = false;
11005           break;
11006         case Intrinsic::amdgcn_if_break:
11007         case Intrinsic::amdgcn_if:
11008         case Intrinsic::amdgcn_else:
11009           Result = true;
11010           break;
11011         }
11012       }
11013       if (V == U->getOperand(0)) {
11014         switch (Intrinsic->getIntrinsicID()) {
11015         default:
11016           Result = false;
11017           break;
11018         case Intrinsic::amdgcn_end_cf:
11019         case Intrinsic::amdgcn_loop:
11020           Result = true;
11021           break;
11022         }
11023       }
11024     } else {
11025       Result = hasCFUser(U, Visited, WaveSize);
11026     }
11027     if (Result)
11028       break;
11029   }
11030   return Result;
11031 }
11032 
11033 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11034                                                const Value *V) const {
11035   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) {
11036     switch (Intrinsic->getIntrinsicID()) {
11037     default:
11038       return false;
11039     case Intrinsic::amdgcn_if_break:
11040       return true;
11041     }
11042   }
11043   if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) {
11044     if (const IntrinsicInst *Intrinsic =
11045             dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) {
11046       switch (Intrinsic->getIntrinsicID()) {
11047       default:
11048         return false;
11049       case Intrinsic::amdgcn_if:
11050       case Intrinsic::amdgcn_else: {
11051         ArrayRef<unsigned> Indices = ExtValue->getIndices();
11052         if (Indices.size() == 1 && Indices[0] == 1) {
11053           return true;
11054         }
11055       }
11056       }
11057     }
11058   }
11059   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11060     if (isa<InlineAsm>(CI->getCalledValue())) {
11061       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11062       ImmutableCallSite CS(CI);
11063       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11064           MF.getDataLayout(), Subtarget->getRegisterInfo(), CS);
11065       for (auto &TC : TargetConstraints) {
11066         if (TC.Type == InlineAsm::isOutput) {
11067           ComputeConstraintToUse(TC, SDValue());
11068           unsigned AssignedReg;
11069           const TargetRegisterClass *RC;
11070           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11071               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11072           if (RC) {
11073             MachineRegisterInfo &MRI = MF.getRegInfo();
11074             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11075               return true;
11076             else if (SIRI->isSGPRClass(RC))
11077               return true;
11078           }
11079         }
11080       }
11081     }
11082   }
11083   SmallPtrSet<const Value *, 16> Visited;
11084   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11085 }
11086