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::BSWAP, MVT::i32, Legal);
365   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
366 
367   // On SI this is s_memtime and s_memrealtime on VI.
368   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
369   setOperationAction(ISD::TRAP, MVT::Other, Custom);
370   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
371 
372   if (Subtarget->has16BitInsts()) {
373     setOperationAction(ISD::FPOW, MVT::f16, Promote);
374     setOperationAction(ISD::FLOG, MVT::f16, Custom);
375     setOperationAction(ISD::FEXP, MVT::f16, Custom);
376     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
377   }
378 
379   // v_mad_f32 does not support denormals. We report it as unconditionally
380   // legal, and the context where it is formed will disallow it when fp32
381   // denormals are enabled.
382   setOperationAction(ISD::FMAD, MVT::f32, Legal);
383 
384   if (!Subtarget->hasBFI()) {
385     // fcopysign can be done in a single instruction with BFI.
386     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
387     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
388   }
389 
390   if (!Subtarget->hasBCNT(32))
391     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
392 
393   if (!Subtarget->hasBCNT(64))
394     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
395 
396   if (Subtarget->hasFFBH())
397     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
398 
399   if (Subtarget->hasFFBL())
400     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
401 
402   // We only really have 32-bit BFE instructions (and 16-bit on VI).
403   //
404   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
405   // effort to match them now. We want this to be false for i64 cases when the
406   // extraction isn't restricted to the upper or lower half. Ideally we would
407   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
408   // span the midpoint are probably relatively rare, so don't worry about them
409   // for now.
410   if (Subtarget->hasBFE())
411     setHasExtractBitsInsn(true);
412 
413   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
414   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
415   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
416   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
417 
418 
419   // These are really only legal for ieee_mode functions. We should be avoiding
420   // them for functions that don't have ieee_mode enabled, so just say they are
421   // legal.
422   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
423   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
424   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
425   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
426 
427 
428   if (Subtarget->haveRoundOpsF64()) {
429     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
430     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
431     setOperationAction(ISD::FRINT, MVT::f64, Legal);
432   } else {
433     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
434     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
435     setOperationAction(ISD::FRINT, MVT::f64, Custom);
436     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
437   }
438 
439   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
440 
441   setOperationAction(ISD::FSIN, MVT::f32, Custom);
442   setOperationAction(ISD::FCOS, MVT::f32, Custom);
443   setOperationAction(ISD::FDIV, MVT::f32, Custom);
444   setOperationAction(ISD::FDIV, MVT::f64, Custom);
445 
446   if (Subtarget->has16BitInsts()) {
447     setOperationAction(ISD::Constant, MVT::i16, Legal);
448 
449     setOperationAction(ISD::SMIN, MVT::i16, Legal);
450     setOperationAction(ISD::SMAX, MVT::i16, Legal);
451 
452     setOperationAction(ISD::UMIN, MVT::i16, Legal);
453     setOperationAction(ISD::UMAX, MVT::i16, Legal);
454 
455     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
456     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
457 
458     setOperationAction(ISD::ROTR, MVT::i16, Promote);
459     setOperationAction(ISD::ROTL, MVT::i16, Promote);
460 
461     setOperationAction(ISD::SDIV, MVT::i16, Promote);
462     setOperationAction(ISD::UDIV, MVT::i16, Promote);
463     setOperationAction(ISD::SREM, MVT::i16, Promote);
464     setOperationAction(ISD::UREM, MVT::i16, Promote);
465 
466     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
467     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
468 
469     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
470     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
471     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
472     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
473     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
474 
475     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
476 
477     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
478 
479     setOperationAction(ISD::LOAD, MVT::i16, Custom);
480 
481     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
482 
483     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
484     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
485     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
486     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
487 
488     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
489     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
490 
491     // F16 - Constant Actions.
492     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
493 
494     // F16 - Load/Store Actions.
495     setOperationAction(ISD::LOAD, MVT::f16, Promote);
496     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
497     setOperationAction(ISD::STORE, MVT::f16, Promote);
498     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
499 
500     // F16 - VOP1 Actions.
501     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
502     setOperationAction(ISD::FCOS, MVT::f16, Custom);
503     setOperationAction(ISD::FSIN, MVT::f16, Custom);
504 
505     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
506     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
507 
508     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
509     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
510     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
511     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
512     setOperationAction(ISD::FROUND, MVT::f16, Custom);
513 
514     // F16 - VOP2 Actions.
515     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
516     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
517 
518     setOperationAction(ISD::FDIV, MVT::f16, Custom);
519 
520     // F16 - VOP3 Actions.
521     setOperationAction(ISD::FMA, MVT::f16, Legal);
522     if (STI.hasMadF16())
523       setOperationAction(ISD::FMAD, MVT::f16, Legal);
524 
525     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
526       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
527         switch (Op) {
528         case ISD::LOAD:
529         case ISD::STORE:
530         case ISD::BUILD_VECTOR:
531         case ISD::BITCAST:
532         case ISD::EXTRACT_VECTOR_ELT:
533         case ISD::INSERT_VECTOR_ELT:
534         case ISD::INSERT_SUBVECTOR:
535         case ISD::EXTRACT_SUBVECTOR:
536         case ISD::SCALAR_TO_VECTOR:
537           break;
538         case ISD::CONCAT_VECTORS:
539           setOperationAction(Op, VT, Custom);
540           break;
541         default:
542           setOperationAction(Op, VT, Expand);
543           break;
544         }
545       }
546     }
547 
548     // XXX - Do these do anything? Vector constants turn into build_vector.
549     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
550     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
551 
552     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
553     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
554 
555     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
556     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
557     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
558     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
559 
560     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
561     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
562     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
563     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
564 
565     setOperationAction(ISD::AND, MVT::v2i16, Promote);
566     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
567     setOperationAction(ISD::OR, MVT::v2i16, Promote);
568     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
569     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
570     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
571 
572     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
573     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
574     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
575     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
576 
577     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
578     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
579     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
580     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
581 
582     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
583     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
584     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
585     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
586 
587     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
588     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
589     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
590 
591     if (!Subtarget->hasVOP3PInsts()) {
592       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
593       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
594     }
595 
596     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
597     // This isn't really legal, but this avoids the legalizer unrolling it (and
598     // allows matching fneg (fabs x) patterns)
599     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
600 
601     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
602     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
603     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
604     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
605 
606     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
607     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
608 
609     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
610     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
611   }
612 
613   if (Subtarget->hasVOP3PInsts()) {
614     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
615     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
616     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
617     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
618     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
619     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
620     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
621     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
622     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
623     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
624 
625     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
626     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
627     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
628 
629     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
630     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
631 
632     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
633 
634     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
635     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
636 
637     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
638     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
639 
640     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
641     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
642     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
643     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
644     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
645     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
646 
647     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
648     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
649     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
650     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
651 
652     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
653     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
654     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
655 
656     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
657     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
658 
659     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
660     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
661     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
662 
663     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
664     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
665     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
666   }
667 
668   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
669   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
670 
671   if (Subtarget->has16BitInsts()) {
672     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
673     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
674     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
675     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
676   } else {
677     // Legalization hack.
678     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
679     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
680 
681     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
682     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
683   }
684 
685   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
686     setOperationAction(ISD::SELECT, VT, Custom);
687   }
688 
689   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
690   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
691   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
692   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
693   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
694   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
695   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
696 
697   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
698   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
699   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
700   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
701   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
702   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
703   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
704   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
705   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
706 
707   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
708   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
709   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
710   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
711   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
712   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
713   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
714   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
715 
716   setTargetDAGCombine(ISD::ADD);
717   setTargetDAGCombine(ISD::ADDCARRY);
718   setTargetDAGCombine(ISD::SUB);
719   setTargetDAGCombine(ISD::SUBCARRY);
720   setTargetDAGCombine(ISD::FADD);
721   setTargetDAGCombine(ISD::FSUB);
722   setTargetDAGCombine(ISD::FMINNUM);
723   setTargetDAGCombine(ISD::FMAXNUM);
724   setTargetDAGCombine(ISD::FMINNUM_IEEE);
725   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
726   setTargetDAGCombine(ISD::FMA);
727   setTargetDAGCombine(ISD::SMIN);
728   setTargetDAGCombine(ISD::SMAX);
729   setTargetDAGCombine(ISD::UMIN);
730   setTargetDAGCombine(ISD::UMAX);
731   setTargetDAGCombine(ISD::SETCC);
732   setTargetDAGCombine(ISD::AND);
733   setTargetDAGCombine(ISD::OR);
734   setTargetDAGCombine(ISD::XOR);
735   setTargetDAGCombine(ISD::SINT_TO_FP);
736   setTargetDAGCombine(ISD::UINT_TO_FP);
737   setTargetDAGCombine(ISD::FCANONICALIZE);
738   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
739   setTargetDAGCombine(ISD::ZERO_EXTEND);
740   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
741   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
742   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
743 
744   // All memory operations. Some folding on the pointer operand is done to help
745   // matching the constant offsets in the addressing modes.
746   setTargetDAGCombine(ISD::LOAD);
747   setTargetDAGCombine(ISD::STORE);
748   setTargetDAGCombine(ISD::ATOMIC_LOAD);
749   setTargetDAGCombine(ISD::ATOMIC_STORE);
750   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
751   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
752   setTargetDAGCombine(ISD::ATOMIC_SWAP);
753   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
754   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
755   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
756   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
757   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
758   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
759   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
760   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
761   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
762   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
763   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
764 
765   setSchedulingPreference(Sched::RegPressure);
766 }
767 
768 const GCNSubtarget *SITargetLowering::getSubtarget() const {
769   return Subtarget;
770 }
771 
772 //===----------------------------------------------------------------------===//
773 // TargetLowering queries
774 //===----------------------------------------------------------------------===//
775 
776 // v_mad_mix* support a conversion from f16 to f32.
777 //
778 // There is only one special case when denormals are enabled we don't currently,
779 // where this is OK to use.
780 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
781                                        EVT DestVT, EVT SrcVT) const {
782   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
783           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
784     DestVT.getScalarType() == MVT::f32 &&
785     SrcVT.getScalarType() == MVT::f16 &&
786     // TODO: This probably only requires no input flushing?
787     !hasFP32Denormals(DAG.getMachineFunction());
788 }
789 
790 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
791   // SI has some legal vector types, but no legal vector operations. Say no
792   // shuffles are legal in order to prefer scalarizing some vector operations.
793   return false;
794 }
795 
796 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
797                                                     CallingConv::ID CC,
798                                                     EVT VT) const {
799   if (CC == CallingConv::AMDGPU_KERNEL)
800     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
801 
802   if (VT.isVector()) {
803     EVT ScalarVT = VT.getScalarType();
804     unsigned Size = ScalarVT.getSizeInBits();
805     if (Size == 32)
806       return ScalarVT.getSimpleVT();
807 
808     if (Size > 32)
809       return MVT::i32;
810 
811     if (Size == 16 && Subtarget->has16BitInsts())
812       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
813   } else if (VT.getSizeInBits() > 32)
814     return MVT::i32;
815 
816   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
817 }
818 
819 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
820                                                          CallingConv::ID CC,
821                                                          EVT VT) const {
822   if (CC == CallingConv::AMDGPU_KERNEL)
823     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
824 
825   if (VT.isVector()) {
826     unsigned NumElts = VT.getVectorNumElements();
827     EVT ScalarVT = VT.getScalarType();
828     unsigned Size = ScalarVT.getSizeInBits();
829 
830     if (Size == 32)
831       return NumElts;
832 
833     if (Size > 32)
834       return NumElts * ((Size + 31) / 32);
835 
836     if (Size == 16 && Subtarget->has16BitInsts())
837       return (NumElts + 1) / 2;
838   } else if (VT.getSizeInBits() > 32)
839     return (VT.getSizeInBits() + 31) / 32;
840 
841   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
842 }
843 
844 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
845   LLVMContext &Context, CallingConv::ID CC,
846   EVT VT, EVT &IntermediateVT,
847   unsigned &NumIntermediates, MVT &RegisterVT) const {
848   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
849     unsigned NumElts = VT.getVectorNumElements();
850     EVT ScalarVT = VT.getScalarType();
851     unsigned Size = ScalarVT.getSizeInBits();
852     if (Size == 32) {
853       RegisterVT = ScalarVT.getSimpleVT();
854       IntermediateVT = RegisterVT;
855       NumIntermediates = NumElts;
856       return NumIntermediates;
857     }
858 
859     if (Size > 32) {
860       RegisterVT = MVT::i32;
861       IntermediateVT = RegisterVT;
862       NumIntermediates = NumElts * ((Size + 31) / 32);
863       return NumIntermediates;
864     }
865 
866     // FIXME: We should fix the ABI to be the same on targets without 16-bit
867     // support, but unless we can properly handle 3-vectors, it will be still be
868     // inconsistent.
869     if (Size == 16 && Subtarget->has16BitInsts()) {
870       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
871       IntermediateVT = RegisterVT;
872       NumIntermediates = (NumElts + 1) / 2;
873       return NumIntermediates;
874     }
875   }
876 
877   return TargetLowering::getVectorTypeBreakdownForCallingConv(
878     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
879 }
880 
881 // Peek through TFE struct returns to only use the data size.
882 static EVT memVTFromImageReturn(Type *Ty) {
883   auto *ST = dyn_cast<StructType>(Ty);
884   if (!ST)
885     return EVT::getEVT(Ty, true);
886 
887   // Some intrinsics return an aggregate type - special case to work out the
888   // correct memVT.
889   //
890   // Only limited forms of aggregate type currently expected.
891   if (ST->getNumContainedTypes() != 2 ||
892       !ST->getContainedType(1)->isIntegerTy(32))
893     return EVT();
894   return EVT::getEVT(ST->getContainedType(0));
895 }
896 
897 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
898                                           const CallInst &CI,
899                                           MachineFunction &MF,
900                                           unsigned IntrID) const {
901   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
902           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
903     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
904                                                   (Intrinsic::ID)IntrID);
905     if (Attr.hasFnAttribute(Attribute::ReadNone))
906       return false;
907 
908     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
909 
910     if (RsrcIntr->IsImage) {
911       Info.ptrVal = MFI->getImagePSV(
912         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
913         CI.getArgOperand(RsrcIntr->RsrcArg));
914       Info.align.reset();
915     } else {
916       Info.ptrVal = MFI->getBufferPSV(
917         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
918         CI.getArgOperand(RsrcIntr->RsrcArg));
919     }
920 
921     Info.flags = MachineMemOperand::MODereferenceable;
922     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
923       Info.opc = ISD::INTRINSIC_W_CHAIN;
924       // TODO: Account for dmask reducing loaded size.
925       Info.memVT = memVTFromImageReturn(CI.getType());
926       Info.flags |= MachineMemOperand::MOLoad;
927     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
928       Info.opc = ISD::INTRINSIC_VOID;
929       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
930       Info.flags |= MachineMemOperand::MOStore;
931     } else {
932       // Atomic
933       Info.opc = ISD::INTRINSIC_W_CHAIN;
934       Info.memVT = MVT::getVT(CI.getType());
935       Info.flags = MachineMemOperand::MOLoad |
936                    MachineMemOperand::MOStore |
937                    MachineMemOperand::MODereferenceable;
938 
939       // XXX - Should this be volatile without known ordering?
940       Info.flags |= MachineMemOperand::MOVolatile;
941     }
942     return true;
943   }
944 
945   switch (IntrID) {
946   case Intrinsic::amdgcn_atomic_inc:
947   case Intrinsic::amdgcn_atomic_dec:
948   case Intrinsic::amdgcn_ds_ordered_add:
949   case Intrinsic::amdgcn_ds_ordered_swap:
950   case Intrinsic::amdgcn_ds_fadd:
951   case Intrinsic::amdgcn_ds_fmin:
952   case Intrinsic::amdgcn_ds_fmax: {
953     Info.opc = ISD::INTRINSIC_W_CHAIN;
954     Info.memVT = MVT::getVT(CI.getType());
955     Info.ptrVal = CI.getOperand(0);
956     Info.align.reset();
957     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
958 
959     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
960     if (!Vol->isZero())
961       Info.flags |= MachineMemOperand::MOVolatile;
962 
963     return true;
964   }
965   case Intrinsic::amdgcn_buffer_atomic_fadd: {
966     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
967 
968     Info.opc = ISD::INTRINSIC_VOID;
969     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
970     Info.ptrVal = MFI->getBufferPSV(
971       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
972       CI.getArgOperand(1));
973     Info.align.reset();
974     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
975 
976     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
977     if (!Vol || !Vol->isZero())
978       Info.flags |= MachineMemOperand::MOVolatile;
979 
980     return true;
981   }
982   case Intrinsic::amdgcn_global_atomic_fadd: {
983     Info.opc = ISD::INTRINSIC_VOID;
984     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
985                             ->getPointerElementType());
986     Info.ptrVal = CI.getOperand(0);
987     Info.align.reset();
988     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
989 
990     return true;
991   }
992   case Intrinsic::amdgcn_ds_append:
993   case Intrinsic::amdgcn_ds_consume: {
994     Info.opc = ISD::INTRINSIC_W_CHAIN;
995     Info.memVT = MVT::getVT(CI.getType());
996     Info.ptrVal = CI.getOperand(0);
997     Info.align.reset();
998     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
999 
1000     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1001     if (!Vol->isZero())
1002       Info.flags |= MachineMemOperand::MOVolatile;
1003 
1004     return true;
1005   }
1006   case Intrinsic::amdgcn_ds_gws_init:
1007   case Intrinsic::amdgcn_ds_gws_barrier:
1008   case Intrinsic::amdgcn_ds_gws_sema_v:
1009   case Intrinsic::amdgcn_ds_gws_sema_br:
1010   case Intrinsic::amdgcn_ds_gws_sema_p:
1011   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1012     Info.opc = ISD::INTRINSIC_VOID;
1013 
1014     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1015     Info.ptrVal =
1016         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1017 
1018     // This is an abstract access, but we need to specify a type and size.
1019     Info.memVT = MVT::i32;
1020     Info.size = 4;
1021     Info.align = Align(4);
1022 
1023     Info.flags = MachineMemOperand::MOStore;
1024     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1025       Info.flags = MachineMemOperand::MOLoad;
1026     return true;
1027   }
1028   default:
1029     return false;
1030   }
1031 }
1032 
1033 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1034                                             SmallVectorImpl<Value*> &Ops,
1035                                             Type *&AccessTy) const {
1036   switch (II->getIntrinsicID()) {
1037   case Intrinsic::amdgcn_atomic_inc:
1038   case Intrinsic::amdgcn_atomic_dec:
1039   case Intrinsic::amdgcn_ds_ordered_add:
1040   case Intrinsic::amdgcn_ds_ordered_swap:
1041   case Intrinsic::amdgcn_ds_fadd:
1042   case Intrinsic::amdgcn_ds_fmin:
1043   case Intrinsic::amdgcn_ds_fmax: {
1044     Value *Ptr = II->getArgOperand(0);
1045     AccessTy = II->getType();
1046     Ops.push_back(Ptr);
1047     return true;
1048   }
1049   default:
1050     return false;
1051   }
1052 }
1053 
1054 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1055   if (!Subtarget->hasFlatInstOffsets()) {
1056     // Flat instructions do not have offsets, and only have the register
1057     // address.
1058     return AM.BaseOffs == 0 && AM.Scale == 0;
1059   }
1060 
1061   return AM.Scale == 0 &&
1062          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1063                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1064                                   /*Signed=*/false));
1065 }
1066 
1067 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1068   if (Subtarget->hasFlatGlobalInsts())
1069     return AM.Scale == 0 &&
1070            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1071                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1072                                     /*Signed=*/true));
1073 
1074   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1075       // Assume the we will use FLAT for all global memory accesses
1076       // on VI.
1077       // FIXME: This assumption is currently wrong.  On VI we still use
1078       // MUBUF instructions for the r + i addressing mode.  As currently
1079       // implemented, the MUBUF instructions only work on buffer < 4GB.
1080       // It may be possible to support > 4GB buffers with MUBUF instructions,
1081       // by setting the stride value in the resource descriptor which would
1082       // increase the size limit to (stride * 4GB).  However, this is risky,
1083       // because it has never been validated.
1084     return isLegalFlatAddressingMode(AM);
1085   }
1086 
1087   return isLegalMUBUFAddressingMode(AM);
1088 }
1089 
1090 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1091   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1092   // additionally can do r + r + i with addr64. 32-bit has more addressing
1093   // mode options. Depending on the resource constant, it can also do
1094   // (i64 r0) + (i32 r1) * (i14 i).
1095   //
1096   // Private arrays end up using a scratch buffer most of the time, so also
1097   // assume those use MUBUF instructions. Scratch loads / stores are currently
1098   // implemented as mubuf instructions with offen bit set, so slightly
1099   // different than the normal addr64.
1100   if (!isUInt<12>(AM.BaseOffs))
1101     return false;
1102 
1103   // FIXME: Since we can split immediate into soffset and immediate offset,
1104   // would it make sense to allow any immediate?
1105 
1106   switch (AM.Scale) {
1107   case 0: // r + i or just i, depending on HasBaseReg.
1108     return true;
1109   case 1:
1110     return true; // We have r + r or r + i.
1111   case 2:
1112     if (AM.HasBaseReg) {
1113       // Reject 2 * r + r.
1114       return false;
1115     }
1116 
1117     // Allow 2 * r as r + r
1118     // Or  2 * r + i is allowed as r + r + i.
1119     return true;
1120   default: // Don't allow n * r
1121     return false;
1122   }
1123 }
1124 
1125 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1126                                              const AddrMode &AM, Type *Ty,
1127                                              unsigned AS, Instruction *I) const {
1128   // No global is ever allowed as a base.
1129   if (AM.BaseGV)
1130     return false;
1131 
1132   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1133     return isLegalGlobalAddressingMode(AM);
1134 
1135   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1136       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1137       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1138     // If the offset isn't a multiple of 4, it probably isn't going to be
1139     // correctly aligned.
1140     // FIXME: Can we get the real alignment here?
1141     if (AM.BaseOffs % 4 != 0)
1142       return isLegalMUBUFAddressingMode(AM);
1143 
1144     // There are no SMRD extloads, so if we have to do a small type access we
1145     // will use a MUBUF load.
1146     // FIXME?: We also need to do this if unaligned, but we don't know the
1147     // alignment here.
1148     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1149       return isLegalGlobalAddressingMode(AM);
1150 
1151     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1152       // SMRD instructions have an 8-bit, dword offset on SI.
1153       if (!isUInt<8>(AM.BaseOffs / 4))
1154         return false;
1155     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1156       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1157       // in 8-bits, it can use a smaller encoding.
1158       if (!isUInt<32>(AM.BaseOffs / 4))
1159         return false;
1160     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1161       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1162       if (!isUInt<20>(AM.BaseOffs))
1163         return false;
1164     } else
1165       llvm_unreachable("unhandled generation");
1166 
1167     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1168       return true;
1169 
1170     if (AM.Scale == 1 && AM.HasBaseReg)
1171       return true;
1172 
1173     return false;
1174 
1175   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1176     return isLegalMUBUFAddressingMode(AM);
1177   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1178              AS == AMDGPUAS::REGION_ADDRESS) {
1179     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1180     // field.
1181     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1182     // an 8-bit dword offset but we don't know the alignment here.
1183     if (!isUInt<16>(AM.BaseOffs))
1184       return false;
1185 
1186     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1187       return true;
1188 
1189     if (AM.Scale == 1 && AM.HasBaseReg)
1190       return true;
1191 
1192     return false;
1193   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1194              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1195     // For an unknown address space, this usually means that this is for some
1196     // reason being used for pure arithmetic, and not based on some addressing
1197     // computation. We don't have instructions that compute pointers with any
1198     // addressing modes, so treat them as having no offset like flat
1199     // instructions.
1200     return isLegalFlatAddressingMode(AM);
1201   } else {
1202     llvm_unreachable("unhandled address space");
1203   }
1204 }
1205 
1206 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1207                                         const SelectionDAG &DAG) const {
1208   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1209     return (MemVT.getSizeInBits() <= 4 * 32);
1210   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1211     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1212     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1213   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1214     return (MemVT.getSizeInBits() <= 2 * 32);
1215   }
1216   return true;
1217 }
1218 
1219 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1220     unsigned Size, unsigned AddrSpace, unsigned Align,
1221     MachineMemOperand::Flags Flags, bool *IsFast) const {
1222   if (IsFast)
1223     *IsFast = false;
1224 
1225   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1226       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1227     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1228     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1229     // with adjacent offsets.
1230     bool AlignedBy4 = (Align % 4 == 0);
1231     if (IsFast)
1232       *IsFast = AlignedBy4;
1233 
1234     return AlignedBy4;
1235   }
1236 
1237   // FIXME: We have to be conservative here and assume that flat operations
1238   // will access scratch.  If we had access to the IR function, then we
1239   // could determine if any private memory was used in the function.
1240   if (!Subtarget->hasUnalignedScratchAccess() &&
1241       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1242        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1243     bool AlignedBy4 = Align >= 4;
1244     if (IsFast)
1245       *IsFast = AlignedBy4;
1246 
1247     return AlignedBy4;
1248   }
1249 
1250   if (Subtarget->hasUnalignedBufferAccess()) {
1251     // If we have an uniform constant load, it still requires using a slow
1252     // buffer instruction if unaligned.
1253     if (IsFast) {
1254       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1255                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1256         (Align % 4 == 0) : true;
1257     }
1258 
1259     return true;
1260   }
1261 
1262   // Smaller than dword value must be aligned.
1263   if (Size < 32)
1264     return false;
1265 
1266   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1267   // byte-address are ignored, thus forcing Dword alignment.
1268   // This applies to private, global, and constant memory.
1269   if (IsFast)
1270     *IsFast = true;
1271 
1272   return Size >= 32 && Align >= 4;
1273 }
1274 
1275 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1276     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1277     bool *IsFast) const {
1278   if (IsFast)
1279     *IsFast = false;
1280 
1281   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1282   // which isn't a simple VT.
1283   // Until MVT is extended to handle this, simply check for the size and
1284   // rely on the condition below: allow accesses if the size is a multiple of 4.
1285   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1286                            VT.getStoreSize() > 16)) {
1287     return false;
1288   }
1289 
1290   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1291                                             Align, Flags, IsFast);
1292 }
1293 
1294 EVT SITargetLowering::getOptimalMemOpType(
1295     const MemOp &Op, const AttributeList &FuncAttributes) const {
1296   // FIXME: Should account for address space here.
1297 
1298   // The default fallback uses the private pointer size as a guess for a type to
1299   // use. Make sure we switch these to 64-bit accesses.
1300 
1301   if (Op.size() >= 16 &&
1302       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1303     return MVT::v4i32;
1304 
1305   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1306     return MVT::v2i32;
1307 
1308   // Use the default.
1309   return MVT::Other;
1310 }
1311 
1312 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1313                                            unsigned DestAS) const {
1314   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1315 }
1316 
1317 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1318   const MemSDNode *MemNode = cast<MemSDNode>(N);
1319   const Value *Ptr = MemNode->getMemOperand()->getValue();
1320   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1321   return I && I->getMetadata("amdgpu.noclobber");
1322 }
1323 
1324 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1325                                            unsigned DestAS) const {
1326   // Flat -> private/local is a simple truncate.
1327   // Flat -> global is no-op
1328   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1329     return true;
1330 
1331   return isNoopAddrSpaceCast(SrcAS, DestAS);
1332 }
1333 
1334 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1335   const MemSDNode *MemNode = cast<MemSDNode>(N);
1336 
1337   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1338 }
1339 
1340 TargetLoweringBase::LegalizeTypeAction
1341 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1342   int NumElts = VT.getVectorNumElements();
1343   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1344     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1345   return TargetLoweringBase::getPreferredVectorAction(VT);
1346 }
1347 
1348 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1349                                                          Type *Ty) const {
1350   // FIXME: Could be smarter if called for vector constants.
1351   return true;
1352 }
1353 
1354 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1355   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1356     switch (Op) {
1357     case ISD::LOAD:
1358     case ISD::STORE:
1359 
1360     // These operations are done with 32-bit instructions anyway.
1361     case ISD::AND:
1362     case ISD::OR:
1363     case ISD::XOR:
1364     case ISD::SELECT:
1365       // TODO: Extensions?
1366       return true;
1367     default:
1368       return false;
1369     }
1370   }
1371 
1372   // SimplifySetCC uses this function to determine whether or not it should
1373   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1374   if (VT == MVT::i1 && Op == ISD::SETCC)
1375     return false;
1376 
1377   return TargetLowering::isTypeDesirableForOp(Op, VT);
1378 }
1379 
1380 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1381                                                    const SDLoc &SL,
1382                                                    SDValue Chain,
1383                                                    uint64_t Offset) const {
1384   const DataLayout &DL = DAG.getDataLayout();
1385   MachineFunction &MF = DAG.getMachineFunction();
1386   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1387 
1388   const ArgDescriptor *InputPtrReg;
1389   const TargetRegisterClass *RC;
1390 
1391   std::tie(InputPtrReg, RC)
1392     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1393 
1394   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1395   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1396   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1397     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1398 
1399   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1400 }
1401 
1402 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1403                                             const SDLoc &SL) const {
1404   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1405                                                FIRST_IMPLICIT);
1406   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1407 }
1408 
1409 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1410                                          const SDLoc &SL, SDValue Val,
1411                                          bool Signed,
1412                                          const ISD::InputArg *Arg) const {
1413   // First, if it is a widened vector, narrow it.
1414   if (VT.isVector() &&
1415       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1416     EVT NarrowedVT =
1417         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1418                          VT.getVectorNumElements());
1419     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1420                       DAG.getConstant(0, SL, MVT::i32));
1421   }
1422 
1423   // Then convert the vector elements or scalar value.
1424   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1425       VT.bitsLT(MemVT)) {
1426     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1427     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1428   }
1429 
1430   if (MemVT.isFloatingPoint())
1431     Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1432   else if (Signed)
1433     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1434   else
1435     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1436 
1437   return Val;
1438 }
1439 
1440 SDValue SITargetLowering::lowerKernargMemParameter(
1441   SelectionDAG &DAG, EVT VT, EVT MemVT,
1442   const SDLoc &SL, SDValue Chain,
1443   uint64_t Offset, unsigned Align, bool Signed,
1444   const ISD::InputArg *Arg) const {
1445   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1446 
1447   // Try to avoid using an extload by loading earlier than the argument address,
1448   // and extracting the relevant bits. The load should hopefully be merged with
1449   // the previous argument.
1450   if (MemVT.getStoreSize() < 4 && Align < 4) {
1451     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1452     int64_t AlignDownOffset = alignDown(Offset, 4);
1453     int64_t OffsetDiff = Offset - AlignDownOffset;
1454 
1455     EVT IntVT = MemVT.changeTypeToInteger();
1456 
1457     // TODO: If we passed in the base kernel offset we could have a better
1458     // alignment than 4, but we don't really need it.
1459     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1460     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1461                                MachineMemOperand::MODereferenceable |
1462                                MachineMemOperand::MOInvariant);
1463 
1464     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1465     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1466 
1467     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1468     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1469     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1470 
1471 
1472     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1473   }
1474 
1475   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1476   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1477                              MachineMemOperand::MODereferenceable |
1478                              MachineMemOperand::MOInvariant);
1479 
1480   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1481   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1482 }
1483 
1484 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1485                                               const SDLoc &SL, SDValue Chain,
1486                                               const ISD::InputArg &Arg) const {
1487   MachineFunction &MF = DAG.getMachineFunction();
1488   MachineFrameInfo &MFI = MF.getFrameInfo();
1489 
1490   if (Arg.Flags.isByVal()) {
1491     unsigned Size = Arg.Flags.getByValSize();
1492     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1493     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1494   }
1495 
1496   unsigned ArgOffset = VA.getLocMemOffset();
1497   unsigned ArgSize = VA.getValVT().getStoreSize();
1498 
1499   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1500 
1501   // Create load nodes to retrieve arguments from the stack.
1502   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1503   SDValue ArgValue;
1504 
1505   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1506   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1507   MVT MemVT = VA.getValVT();
1508 
1509   switch (VA.getLocInfo()) {
1510   default:
1511     break;
1512   case CCValAssign::BCvt:
1513     MemVT = VA.getLocVT();
1514     break;
1515   case CCValAssign::SExt:
1516     ExtType = ISD::SEXTLOAD;
1517     break;
1518   case CCValAssign::ZExt:
1519     ExtType = ISD::ZEXTLOAD;
1520     break;
1521   case CCValAssign::AExt:
1522     ExtType = ISD::EXTLOAD;
1523     break;
1524   }
1525 
1526   ArgValue = DAG.getExtLoad(
1527     ExtType, SL, VA.getLocVT(), Chain, FIN,
1528     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1529     MemVT);
1530   return ArgValue;
1531 }
1532 
1533 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1534   const SIMachineFunctionInfo &MFI,
1535   EVT VT,
1536   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1537   const ArgDescriptor *Reg;
1538   const TargetRegisterClass *RC;
1539 
1540   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1541   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1542 }
1543 
1544 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1545                                    CallingConv::ID CallConv,
1546                                    ArrayRef<ISD::InputArg> Ins,
1547                                    BitVector &Skipped,
1548                                    FunctionType *FType,
1549                                    SIMachineFunctionInfo *Info) {
1550   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1551     const ISD::InputArg *Arg = &Ins[I];
1552 
1553     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1554            "vector type argument should have been split");
1555 
1556     // First check if it's a PS input addr.
1557     if (CallConv == CallingConv::AMDGPU_PS &&
1558         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1559       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1560 
1561       // Inconveniently only the first part of the split is marked as isSplit,
1562       // so skip to the end. We only want to increment PSInputNum once for the
1563       // entire split argument.
1564       if (Arg->Flags.isSplit()) {
1565         while (!Arg->Flags.isSplitEnd()) {
1566           assert((!Arg->VT.isVector() ||
1567                   Arg->VT.getScalarSizeInBits() == 16) &&
1568                  "unexpected vector split in ps argument type");
1569           if (!SkipArg)
1570             Splits.push_back(*Arg);
1571           Arg = &Ins[++I];
1572         }
1573       }
1574 
1575       if (SkipArg) {
1576         // We can safely skip PS inputs.
1577         Skipped.set(Arg->getOrigArgIndex());
1578         ++PSInputNum;
1579         continue;
1580       }
1581 
1582       Info->markPSInputAllocated(PSInputNum);
1583       if (Arg->Used)
1584         Info->markPSInputEnabled(PSInputNum);
1585 
1586       ++PSInputNum;
1587     }
1588 
1589     Splits.push_back(*Arg);
1590   }
1591 }
1592 
1593 // Allocate special inputs passed in VGPRs.
1594 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1595                                                       MachineFunction &MF,
1596                                                       const SIRegisterInfo &TRI,
1597                                                       SIMachineFunctionInfo &Info) const {
1598   const LLT S32 = LLT::scalar(32);
1599   MachineRegisterInfo &MRI = MF.getRegInfo();
1600 
1601   if (Info.hasWorkItemIDX()) {
1602     Register Reg = AMDGPU::VGPR0;
1603     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1604 
1605     CCInfo.AllocateReg(Reg);
1606     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1607   }
1608 
1609   if (Info.hasWorkItemIDY()) {
1610     Register Reg = AMDGPU::VGPR1;
1611     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1612 
1613     CCInfo.AllocateReg(Reg);
1614     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1615   }
1616 
1617   if (Info.hasWorkItemIDZ()) {
1618     Register Reg = AMDGPU::VGPR2;
1619     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1620 
1621     CCInfo.AllocateReg(Reg);
1622     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1623   }
1624 }
1625 
1626 // Try to allocate a VGPR at the end of the argument list, or if no argument
1627 // VGPRs are left allocating a stack slot.
1628 // If \p Mask is is given it indicates bitfield position in the register.
1629 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1630 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1631                                          ArgDescriptor Arg = ArgDescriptor()) {
1632   if (Arg.isSet())
1633     return ArgDescriptor::createArg(Arg, Mask);
1634 
1635   ArrayRef<MCPhysReg> ArgVGPRs
1636     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1637   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1638   if (RegIdx == ArgVGPRs.size()) {
1639     // Spill to stack required.
1640     int64_t Offset = CCInfo.AllocateStack(4, 4);
1641 
1642     return ArgDescriptor::createStack(Offset, Mask);
1643   }
1644 
1645   unsigned Reg = ArgVGPRs[RegIdx];
1646   Reg = CCInfo.AllocateReg(Reg);
1647   assert(Reg != AMDGPU::NoRegister);
1648 
1649   MachineFunction &MF = CCInfo.getMachineFunction();
1650   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1651   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1652   return ArgDescriptor::createRegister(Reg, Mask);
1653 }
1654 
1655 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1656                                              const TargetRegisterClass *RC,
1657                                              unsigned NumArgRegs) {
1658   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1659   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1660   if (RegIdx == ArgSGPRs.size())
1661     report_fatal_error("ran out of SGPRs for arguments");
1662 
1663   unsigned Reg = ArgSGPRs[RegIdx];
1664   Reg = CCInfo.AllocateReg(Reg);
1665   assert(Reg != AMDGPU::NoRegister);
1666 
1667   MachineFunction &MF = CCInfo.getMachineFunction();
1668   MF.addLiveIn(Reg, RC);
1669   return ArgDescriptor::createRegister(Reg);
1670 }
1671 
1672 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1673   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1674 }
1675 
1676 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1677   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1678 }
1679 
1680 void SITargetLowering::allocateSpecialInputVGPRs(CCState &CCInfo,
1681                                                  MachineFunction &MF,
1682                                                  const SIRegisterInfo &TRI,
1683                                                  SIMachineFunctionInfo &Info) const {
1684   const unsigned Mask = 0x3ff;
1685   ArgDescriptor Arg;
1686 
1687   if (Info.hasWorkItemIDX()) {
1688     Arg = allocateVGPR32Input(CCInfo, Mask);
1689     Info.setWorkItemIDX(Arg);
1690   }
1691 
1692   if (Info.hasWorkItemIDY()) {
1693     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1694     Info.setWorkItemIDY(Arg);
1695   }
1696 
1697   if (Info.hasWorkItemIDZ())
1698     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1699 }
1700 
1701 void SITargetLowering::allocateSpecialInputSGPRs(
1702   CCState &CCInfo,
1703   MachineFunction &MF,
1704   const SIRegisterInfo &TRI,
1705   SIMachineFunctionInfo &Info) const {
1706   auto &ArgInfo = Info.getArgInfo();
1707 
1708   // TODO: Unify handling with private memory pointers.
1709 
1710   if (Info.hasDispatchPtr())
1711     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1712 
1713   if (Info.hasQueuePtr())
1714     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1715 
1716   if (Info.hasKernargSegmentPtr())
1717     ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1718 
1719   if (Info.hasDispatchID())
1720     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1721 
1722   // flat_scratch_init is not applicable for non-kernel functions.
1723 
1724   if (Info.hasWorkGroupIDX())
1725     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1726 
1727   if (Info.hasWorkGroupIDY())
1728     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1729 
1730   if (Info.hasWorkGroupIDZ())
1731     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1732 
1733   if (Info.hasImplicitArgPtr())
1734     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1735 }
1736 
1737 // Allocate special inputs passed in user SGPRs.
1738 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1739                                             MachineFunction &MF,
1740                                             const SIRegisterInfo &TRI,
1741                                             SIMachineFunctionInfo &Info) const {
1742   if (Info.hasImplicitBufferPtr()) {
1743     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1744     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1745     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1746   }
1747 
1748   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1749   if (Info.hasPrivateSegmentBuffer()) {
1750     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1751     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1752     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1753   }
1754 
1755   if (Info.hasDispatchPtr()) {
1756     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1757     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1758     CCInfo.AllocateReg(DispatchPtrReg);
1759   }
1760 
1761   if (Info.hasQueuePtr()) {
1762     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1763     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1764     CCInfo.AllocateReg(QueuePtrReg);
1765   }
1766 
1767   if (Info.hasKernargSegmentPtr()) {
1768     MachineRegisterInfo &MRI = MF.getRegInfo();
1769     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1770     CCInfo.AllocateReg(InputPtrReg);
1771 
1772     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1773     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1774   }
1775 
1776   if (Info.hasDispatchID()) {
1777     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1778     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1779     CCInfo.AllocateReg(DispatchIDReg);
1780   }
1781 
1782   if (Info.hasFlatScratchInit()) {
1783     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1784     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1785     CCInfo.AllocateReg(FlatScratchInitReg);
1786   }
1787 
1788   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1789   // these from the dispatch pointer.
1790 }
1791 
1792 // Allocate special input registers that are initialized per-wave.
1793 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1794                                            MachineFunction &MF,
1795                                            SIMachineFunctionInfo &Info,
1796                                            CallingConv::ID CallConv,
1797                                            bool IsShader) const {
1798   if (Info.hasWorkGroupIDX()) {
1799     unsigned Reg = Info.addWorkGroupIDX();
1800     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1801     CCInfo.AllocateReg(Reg);
1802   }
1803 
1804   if (Info.hasWorkGroupIDY()) {
1805     unsigned Reg = Info.addWorkGroupIDY();
1806     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1807     CCInfo.AllocateReg(Reg);
1808   }
1809 
1810   if (Info.hasWorkGroupIDZ()) {
1811     unsigned Reg = Info.addWorkGroupIDZ();
1812     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1813     CCInfo.AllocateReg(Reg);
1814   }
1815 
1816   if (Info.hasWorkGroupInfo()) {
1817     unsigned Reg = Info.addWorkGroupInfo();
1818     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1819     CCInfo.AllocateReg(Reg);
1820   }
1821 
1822   if (Info.hasPrivateSegmentWaveByteOffset()) {
1823     // Scratch wave offset passed in system SGPR.
1824     unsigned PrivateSegmentWaveByteOffsetReg;
1825 
1826     if (IsShader) {
1827       PrivateSegmentWaveByteOffsetReg =
1828         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1829 
1830       // This is true if the scratch wave byte offset doesn't have a fixed
1831       // location.
1832       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1833         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1834         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1835       }
1836     } else
1837       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1838 
1839     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1840     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1841   }
1842 }
1843 
1844 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1845                                      MachineFunction &MF,
1846                                      const SIRegisterInfo &TRI,
1847                                      SIMachineFunctionInfo &Info) {
1848   // Now that we've figured out where the scratch register inputs are, see if
1849   // should reserve the arguments and use them directly.
1850   MachineFrameInfo &MFI = MF.getFrameInfo();
1851   bool HasStackObjects = MFI.hasStackObjects();
1852   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1853 
1854   // Record that we know we have non-spill stack objects so we don't need to
1855   // check all stack objects later.
1856   if (HasStackObjects)
1857     Info.setHasNonSpillStackObjects(true);
1858 
1859   // Everything live out of a block is spilled with fast regalloc, so it's
1860   // almost certain that spilling will be required.
1861   if (TM.getOptLevel() == CodeGenOpt::None)
1862     HasStackObjects = true;
1863 
1864   // For now assume stack access is needed in any callee functions, so we need
1865   // the scratch registers to pass in.
1866   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1867 
1868   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1869     // If we have stack objects, we unquestionably need the private buffer
1870     // resource. For the Code Object V2 ABI, this will be the first 4 user
1871     // SGPR inputs. We can reserve those and use them directly.
1872 
1873     Register PrivateSegmentBufferReg =
1874         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1875     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1876   } else {
1877     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1878     // We tentatively reserve the last registers (skipping the last registers
1879     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1880     // we'll replace these with the ones immediately after those which were
1881     // really allocated. In the prologue copies will be inserted from the
1882     // argument to these reserved registers.
1883 
1884     // Without HSA, relocations are used for the scratch pointer and the
1885     // buffer resource setup is always inserted in the prologue. Scratch wave
1886     // offset is still in an input SGPR.
1887     Info.setScratchRSrcReg(ReservedBufferReg);
1888   }
1889 
1890   // hasFP should be accurate for kernels even before the frame is finalized.
1891   if (ST.getFrameLowering()->hasFP(MF)) {
1892     MachineRegisterInfo &MRI = MF.getRegInfo();
1893 
1894     // Try to use s32 as the SP, but move it if it would interfere with input
1895     // arguments. This won't work with calls though.
1896     //
1897     // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1898     // registers.
1899     if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1900       Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1901     } else {
1902       assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1903 
1904       if (MFI.hasCalls())
1905         report_fatal_error("call in graphics shader with too many input SGPRs");
1906 
1907       for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1908         if (!MRI.isLiveIn(Reg)) {
1909           Info.setStackPtrOffsetReg(Reg);
1910           break;
1911         }
1912       }
1913 
1914       if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1915         report_fatal_error("failed to find register for SP");
1916     }
1917 
1918     if (MFI.hasCalls()) {
1919       Info.setScratchWaveOffsetReg(AMDGPU::SGPR33);
1920       Info.setFrameOffsetReg(AMDGPU::SGPR33);
1921     } else {
1922       unsigned ReservedOffsetReg =
1923         TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1924       Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1925       Info.setFrameOffsetReg(ReservedOffsetReg);
1926     }
1927   } else if (RequiresStackAccess) {
1928     assert(!MFI.hasCalls());
1929     // We know there are accesses and they will be done relative to SP, so just
1930     // pin it to the input.
1931     //
1932     // FIXME: Should not do this if inline asm is reading/writing these
1933     // registers.
1934     Register PreloadedSP = Info.getPreloadedReg(
1935         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1936 
1937     Info.setStackPtrOffsetReg(PreloadedSP);
1938     Info.setScratchWaveOffsetReg(PreloadedSP);
1939     Info.setFrameOffsetReg(PreloadedSP);
1940   } else {
1941     assert(!MFI.hasCalls());
1942 
1943     // There may not be stack access at all. There may still be spills, or
1944     // access of a constant pointer (in which cases an extra copy will be
1945     // emitted in the prolog).
1946     unsigned ReservedOffsetReg
1947       = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1948     Info.setStackPtrOffsetReg(ReservedOffsetReg);
1949     Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1950     Info.setFrameOffsetReg(ReservedOffsetReg);
1951   }
1952 }
1953 
1954 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1955   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1956   return !Info->isEntryFunction();
1957 }
1958 
1959 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1960 
1961 }
1962 
1963 void SITargetLowering::insertCopiesSplitCSR(
1964   MachineBasicBlock *Entry,
1965   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1966   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1967 
1968   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1969   if (!IStart)
1970     return;
1971 
1972   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1973   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1974   MachineBasicBlock::iterator MBBI = Entry->begin();
1975   for (const MCPhysReg *I = IStart; *I; ++I) {
1976     const TargetRegisterClass *RC = nullptr;
1977     if (AMDGPU::SReg_64RegClass.contains(*I))
1978       RC = &AMDGPU::SGPR_64RegClass;
1979     else if (AMDGPU::SReg_32RegClass.contains(*I))
1980       RC = &AMDGPU::SGPR_32RegClass;
1981     else
1982       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1983 
1984     Register NewVR = MRI->createVirtualRegister(RC);
1985     // Create copy from CSR to a virtual register.
1986     Entry->addLiveIn(*I);
1987     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1988       .addReg(*I);
1989 
1990     // Insert the copy-back instructions right before the terminator.
1991     for (auto *Exit : Exits)
1992       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1993               TII->get(TargetOpcode::COPY), *I)
1994         .addReg(NewVR);
1995   }
1996 }
1997 
1998 SDValue SITargetLowering::LowerFormalArguments(
1999     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2000     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2001     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2002   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2003 
2004   MachineFunction &MF = DAG.getMachineFunction();
2005   const Function &Fn = MF.getFunction();
2006   FunctionType *FType = MF.getFunction().getFunctionType();
2007   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2008 
2009   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2010     DiagnosticInfoUnsupported NoGraphicsHSA(
2011         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2012     DAG.getContext()->diagnose(NoGraphicsHSA);
2013     return DAG.getEntryNode();
2014   }
2015 
2016   SmallVector<ISD::InputArg, 16> Splits;
2017   SmallVector<CCValAssign, 16> ArgLocs;
2018   BitVector Skipped(Ins.size());
2019   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2020                  *DAG.getContext());
2021 
2022   bool IsShader = AMDGPU::isShader(CallConv);
2023   bool IsKernel = AMDGPU::isKernel(CallConv);
2024   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2025 
2026   if (IsShader) {
2027     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2028 
2029     // At least one interpolation mode must be enabled or else the GPU will
2030     // hang.
2031     //
2032     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2033     // set PSInputAddr, the user wants to enable some bits after the compilation
2034     // based on run-time states. Since we can't know what the final PSInputEna
2035     // will look like, so we shouldn't do anything here and the user should take
2036     // responsibility for the correct programming.
2037     //
2038     // Otherwise, the following restrictions apply:
2039     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2040     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2041     //   enabled too.
2042     if (CallConv == CallingConv::AMDGPU_PS) {
2043       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2044            ((Info->getPSInputAddr() & 0xF) == 0 &&
2045             Info->isPSInputAllocated(11))) {
2046         CCInfo.AllocateReg(AMDGPU::VGPR0);
2047         CCInfo.AllocateReg(AMDGPU::VGPR1);
2048         Info->markPSInputAllocated(0);
2049         Info->markPSInputEnabled(0);
2050       }
2051       if (Subtarget->isAmdPalOS()) {
2052         // For isAmdPalOS, the user does not enable some bits after compilation
2053         // based on run-time states; the register values being generated here are
2054         // the final ones set in hardware. Therefore we need to apply the
2055         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2056         // a bit is set in PSInputAddr but not PSInputEnable is where the
2057         // frontend set up an input arg for a particular interpolation mode, but
2058         // nothing uses that input arg. Really we should have an earlier pass
2059         // that removes such an arg.)
2060         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2061         if ((PsInputBits & 0x7F) == 0 ||
2062             ((PsInputBits & 0xF) == 0 &&
2063              (PsInputBits >> 11 & 1)))
2064           Info->markPSInputEnabled(
2065               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2066       }
2067     }
2068 
2069     assert(!Info->hasDispatchPtr() &&
2070            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2071            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2072            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2073            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2074            !Info->hasWorkItemIDZ());
2075   } else if (IsKernel) {
2076     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2077   } else {
2078     Splits.append(Ins.begin(), Ins.end());
2079   }
2080 
2081   if (IsEntryFunc) {
2082     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2083     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2084   }
2085 
2086   if (IsKernel) {
2087     analyzeFormalArgumentsCompute(CCInfo, Ins);
2088   } else {
2089     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2090     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2091   }
2092 
2093   SmallVector<SDValue, 16> Chains;
2094 
2095   // FIXME: This is the minimum kernel argument alignment. We should improve
2096   // this to the maximum alignment of the arguments.
2097   //
2098   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2099   // kern arg offset.
2100   const unsigned KernelArgBaseAlign = 16;
2101 
2102    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2103     const ISD::InputArg &Arg = Ins[i];
2104     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2105       InVals.push_back(DAG.getUNDEF(Arg.VT));
2106       continue;
2107     }
2108 
2109     CCValAssign &VA = ArgLocs[ArgIdx++];
2110     MVT VT = VA.getLocVT();
2111 
2112     if (IsEntryFunc && VA.isMemLoc()) {
2113       VT = Ins[i].VT;
2114       EVT MemVT = VA.getLocVT();
2115 
2116       const uint64_t Offset = VA.getLocMemOffset();
2117       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2118 
2119       SDValue Arg = lowerKernargMemParameter(
2120         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2121       Chains.push_back(Arg.getValue(1));
2122 
2123       auto *ParamTy =
2124         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2125       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2126           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2127                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2128         // On SI local pointers are just offsets into LDS, so they are always
2129         // less than 16-bits.  On CI and newer they could potentially be
2130         // real pointers, so we can't guarantee their size.
2131         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2132                           DAG.getValueType(MVT::i16));
2133       }
2134 
2135       InVals.push_back(Arg);
2136       continue;
2137     } else if (!IsEntryFunc && VA.isMemLoc()) {
2138       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2139       InVals.push_back(Val);
2140       if (!Arg.Flags.isByVal())
2141         Chains.push_back(Val.getValue(1));
2142       continue;
2143     }
2144 
2145     assert(VA.isRegLoc() && "Parameter must be in a register!");
2146 
2147     Register Reg = VA.getLocReg();
2148     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2149     EVT ValVT = VA.getValVT();
2150 
2151     Reg = MF.addLiveIn(Reg, RC);
2152     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2153 
2154     if (Arg.Flags.isSRet()) {
2155       // The return object should be reasonably addressable.
2156 
2157       // FIXME: This helps when the return is a real sret. If it is a
2158       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2159       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2160       unsigned NumBits
2161         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2162       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2163         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2164     }
2165 
2166     // If this is an 8 or 16-bit value, it is really passed promoted
2167     // to 32 bits. Insert an assert[sz]ext to capture this, then
2168     // truncate to the right size.
2169     switch (VA.getLocInfo()) {
2170     case CCValAssign::Full:
2171       break;
2172     case CCValAssign::BCvt:
2173       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2174       break;
2175     case CCValAssign::SExt:
2176       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2177                         DAG.getValueType(ValVT));
2178       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2179       break;
2180     case CCValAssign::ZExt:
2181       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2182                         DAG.getValueType(ValVT));
2183       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2184       break;
2185     case CCValAssign::AExt:
2186       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2187       break;
2188     default:
2189       llvm_unreachable("Unknown loc info!");
2190     }
2191 
2192     InVals.push_back(Val);
2193   }
2194 
2195   if (!IsEntryFunc) {
2196     // Special inputs come after user arguments.
2197     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2198   }
2199 
2200   // Start adding system SGPRs.
2201   if (IsEntryFunc) {
2202     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2203   } else {
2204     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2205     CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2206     CCInfo.AllocateReg(Info->getFrameOffsetReg());
2207     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2208   }
2209 
2210   auto &ArgUsageInfo =
2211     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2212   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2213 
2214   unsigned StackArgSize = CCInfo.getNextStackOffset();
2215   Info->setBytesInStackArgArea(StackArgSize);
2216 
2217   return Chains.empty() ? Chain :
2218     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2219 }
2220 
2221 // TODO: If return values can't fit in registers, we should return as many as
2222 // possible in registers before passing on stack.
2223 bool SITargetLowering::CanLowerReturn(
2224   CallingConv::ID CallConv,
2225   MachineFunction &MF, bool IsVarArg,
2226   const SmallVectorImpl<ISD::OutputArg> &Outs,
2227   LLVMContext &Context) const {
2228   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2229   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2230   // for shaders. Vector types should be explicitly handled by CC.
2231   if (AMDGPU::isEntryFunctionCC(CallConv))
2232     return true;
2233 
2234   SmallVector<CCValAssign, 16> RVLocs;
2235   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2236   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2237 }
2238 
2239 SDValue
2240 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2241                               bool isVarArg,
2242                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2243                               const SmallVectorImpl<SDValue> &OutVals,
2244                               const SDLoc &DL, SelectionDAG &DAG) const {
2245   MachineFunction &MF = DAG.getMachineFunction();
2246   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2247 
2248   if (AMDGPU::isKernel(CallConv)) {
2249     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2250                                              OutVals, DL, DAG);
2251   }
2252 
2253   bool IsShader = AMDGPU::isShader(CallConv);
2254 
2255   Info->setIfReturnsVoid(Outs.empty());
2256   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2257 
2258   // CCValAssign - represent the assignment of the return value to a location.
2259   SmallVector<CCValAssign, 48> RVLocs;
2260   SmallVector<ISD::OutputArg, 48> Splits;
2261 
2262   // CCState - Info about the registers and stack slots.
2263   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2264                  *DAG.getContext());
2265 
2266   // Analyze outgoing return values.
2267   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2268 
2269   SDValue Flag;
2270   SmallVector<SDValue, 48> RetOps;
2271   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2272 
2273   // Add return address for callable functions.
2274   if (!Info->isEntryFunction()) {
2275     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2276     SDValue ReturnAddrReg = CreateLiveInRegister(
2277       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2278 
2279     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2280         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2281         MVT::i64);
2282     Chain =
2283         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2284     Flag = Chain.getValue(1);
2285     RetOps.push_back(ReturnAddrVirtualReg);
2286   }
2287 
2288   // Copy the result values into the output registers.
2289   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2290        ++I, ++RealRVLocIdx) {
2291     CCValAssign &VA = RVLocs[I];
2292     assert(VA.isRegLoc() && "Can only return in registers!");
2293     // TODO: Partially return in registers if return values don't fit.
2294     SDValue Arg = OutVals[RealRVLocIdx];
2295 
2296     // Copied from other backends.
2297     switch (VA.getLocInfo()) {
2298     case CCValAssign::Full:
2299       break;
2300     case CCValAssign::BCvt:
2301       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2302       break;
2303     case CCValAssign::SExt:
2304       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2305       break;
2306     case CCValAssign::ZExt:
2307       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2308       break;
2309     case CCValAssign::AExt:
2310       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2311       break;
2312     default:
2313       llvm_unreachable("Unknown loc info!");
2314     }
2315 
2316     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2317     Flag = Chain.getValue(1);
2318     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2319   }
2320 
2321   // FIXME: Does sret work properly?
2322   if (!Info->isEntryFunction()) {
2323     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2324     const MCPhysReg *I =
2325       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2326     if (I) {
2327       for (; *I; ++I) {
2328         if (AMDGPU::SReg_64RegClass.contains(*I))
2329           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2330         else if (AMDGPU::SReg_32RegClass.contains(*I))
2331           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2332         else
2333           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2334       }
2335     }
2336   }
2337 
2338   // Update chain and glue.
2339   RetOps[0] = Chain;
2340   if (Flag.getNode())
2341     RetOps.push_back(Flag);
2342 
2343   unsigned Opc = AMDGPUISD::ENDPGM;
2344   if (!IsWaveEnd)
2345     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2346   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2347 }
2348 
2349 SDValue SITargetLowering::LowerCallResult(
2350     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2351     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2352     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2353     SDValue ThisVal) const {
2354   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2355 
2356   // Assign locations to each value returned by this call.
2357   SmallVector<CCValAssign, 16> RVLocs;
2358   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2359                  *DAG.getContext());
2360   CCInfo.AnalyzeCallResult(Ins, RetCC);
2361 
2362   // Copy all of the result registers out of their specified physreg.
2363   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2364     CCValAssign VA = RVLocs[i];
2365     SDValue Val;
2366 
2367     if (VA.isRegLoc()) {
2368       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2369       Chain = Val.getValue(1);
2370       InFlag = Val.getValue(2);
2371     } else if (VA.isMemLoc()) {
2372       report_fatal_error("TODO: return values in memory");
2373     } else
2374       llvm_unreachable("unknown argument location type");
2375 
2376     switch (VA.getLocInfo()) {
2377     case CCValAssign::Full:
2378       break;
2379     case CCValAssign::BCvt:
2380       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2381       break;
2382     case CCValAssign::ZExt:
2383       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2384                         DAG.getValueType(VA.getValVT()));
2385       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2386       break;
2387     case CCValAssign::SExt:
2388       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2389                         DAG.getValueType(VA.getValVT()));
2390       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2391       break;
2392     case CCValAssign::AExt:
2393       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2394       break;
2395     default:
2396       llvm_unreachable("Unknown loc info!");
2397     }
2398 
2399     InVals.push_back(Val);
2400   }
2401 
2402   return Chain;
2403 }
2404 
2405 // Add code to pass special inputs required depending on used features separate
2406 // from the explicit user arguments present in the IR.
2407 void SITargetLowering::passSpecialInputs(
2408     CallLoweringInfo &CLI,
2409     CCState &CCInfo,
2410     const SIMachineFunctionInfo &Info,
2411     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2412     SmallVectorImpl<SDValue> &MemOpChains,
2413     SDValue Chain) const {
2414   // If we don't have a call site, this was a call inserted by
2415   // legalization. These can never use special inputs.
2416   if (!CLI.CS)
2417     return;
2418 
2419   const Function *CalleeFunc = CLI.CS.getCalledFunction();
2420   assert(CalleeFunc);
2421 
2422   SelectionDAG &DAG = CLI.DAG;
2423   const SDLoc &DL = CLI.DL;
2424 
2425   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2426 
2427   auto &ArgUsageInfo =
2428     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2429   const AMDGPUFunctionArgInfo &CalleeArgInfo
2430     = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2431 
2432   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2433 
2434   // TODO: Unify with private memory register handling. This is complicated by
2435   // the fact that at least in kernels, the input argument is not necessarily
2436   // in the same location as the input.
2437   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2438     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2439     AMDGPUFunctionArgInfo::QUEUE_PTR,
2440     AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2441     AMDGPUFunctionArgInfo::DISPATCH_ID,
2442     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2443     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2444     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2445     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2446   };
2447 
2448   for (auto InputID : InputRegs) {
2449     const ArgDescriptor *OutgoingArg;
2450     const TargetRegisterClass *ArgRC;
2451 
2452     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2453     if (!OutgoingArg)
2454       continue;
2455 
2456     const ArgDescriptor *IncomingArg;
2457     const TargetRegisterClass *IncomingArgRC;
2458     std::tie(IncomingArg, IncomingArgRC)
2459       = CallerArgInfo.getPreloadedValue(InputID);
2460     assert(IncomingArgRC == ArgRC);
2461 
2462     // All special arguments are ints for now.
2463     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2464     SDValue InputReg;
2465 
2466     if (IncomingArg) {
2467       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2468     } else {
2469       // The implicit arg ptr is special because it doesn't have a corresponding
2470       // input for kernels, and is computed from the kernarg segment pointer.
2471       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2472       InputReg = getImplicitArgPtr(DAG, DL);
2473     }
2474 
2475     if (OutgoingArg->isRegister()) {
2476       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2477     } else {
2478       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2479       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2480                                               SpecialArgOffset);
2481       MemOpChains.push_back(ArgStore);
2482     }
2483   }
2484 
2485   // Pack workitem IDs into a single register or pass it as is if already
2486   // packed.
2487   const ArgDescriptor *OutgoingArg;
2488   const TargetRegisterClass *ArgRC;
2489 
2490   std::tie(OutgoingArg, ArgRC) =
2491     CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2492   if (!OutgoingArg)
2493     std::tie(OutgoingArg, ArgRC) =
2494       CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2495   if (!OutgoingArg)
2496     std::tie(OutgoingArg, ArgRC) =
2497       CalleeArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2498   if (!OutgoingArg)
2499     return;
2500 
2501   const ArgDescriptor *IncomingArgX
2502     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2503   const ArgDescriptor *IncomingArgY
2504     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2505   const ArgDescriptor *IncomingArgZ
2506     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2507 
2508   SDValue InputReg;
2509   SDLoc SL;
2510 
2511   // If incoming ids are not packed we need to pack them.
2512   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo.WorkItemIDX)
2513     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2514 
2515   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo.WorkItemIDY) {
2516     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2517     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2518                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2519     InputReg = InputReg.getNode() ?
2520                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2521   }
2522 
2523   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo.WorkItemIDZ) {
2524     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2525     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2526                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2527     InputReg = InputReg.getNode() ?
2528                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2529   }
2530 
2531   if (!InputReg.getNode()) {
2532     // Workitem ids are already packed, any of present incoming arguments
2533     // will carry all required fields.
2534     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2535       IncomingArgX ? *IncomingArgX :
2536       IncomingArgY ? *IncomingArgY :
2537                      *IncomingArgZ, ~0u);
2538     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2539   }
2540 
2541   if (OutgoingArg->isRegister()) {
2542     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2543   } else {
2544     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, 4);
2545     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2546                                             SpecialArgOffset);
2547     MemOpChains.push_back(ArgStore);
2548   }
2549 }
2550 
2551 static bool canGuaranteeTCO(CallingConv::ID CC) {
2552   return CC == CallingConv::Fast;
2553 }
2554 
2555 /// Return true if we might ever do TCO for calls with this calling convention.
2556 static bool mayTailCallThisCC(CallingConv::ID CC) {
2557   switch (CC) {
2558   case CallingConv::C:
2559     return true;
2560   default:
2561     return canGuaranteeTCO(CC);
2562   }
2563 }
2564 
2565 bool SITargetLowering::isEligibleForTailCallOptimization(
2566     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2567     const SmallVectorImpl<ISD::OutputArg> &Outs,
2568     const SmallVectorImpl<SDValue> &OutVals,
2569     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2570   if (!mayTailCallThisCC(CalleeCC))
2571     return false;
2572 
2573   MachineFunction &MF = DAG.getMachineFunction();
2574   const Function &CallerF = MF.getFunction();
2575   CallingConv::ID CallerCC = CallerF.getCallingConv();
2576   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2577   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2578 
2579   // Kernels aren't callable, and don't have a live in return address so it
2580   // doesn't make sense to do a tail call with entry functions.
2581   if (!CallerPreserved)
2582     return false;
2583 
2584   bool CCMatch = CallerCC == CalleeCC;
2585 
2586   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2587     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2588       return true;
2589     return false;
2590   }
2591 
2592   // TODO: Can we handle var args?
2593   if (IsVarArg)
2594     return false;
2595 
2596   for (const Argument &Arg : CallerF.args()) {
2597     if (Arg.hasByValAttr())
2598       return false;
2599   }
2600 
2601   LLVMContext &Ctx = *DAG.getContext();
2602 
2603   // Check that the call results are passed in the same way.
2604   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2605                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2606                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2607     return false;
2608 
2609   // The callee has to preserve all registers the caller needs to preserve.
2610   if (!CCMatch) {
2611     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2612     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2613       return false;
2614   }
2615 
2616   // Nothing more to check if the callee is taking no arguments.
2617   if (Outs.empty())
2618     return true;
2619 
2620   SmallVector<CCValAssign, 16> ArgLocs;
2621   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2622 
2623   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2624 
2625   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2626   // If the stack arguments for this call do not fit into our own save area then
2627   // the call cannot be made tail.
2628   // TODO: Is this really necessary?
2629   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2630     return false;
2631 
2632   const MachineRegisterInfo &MRI = MF.getRegInfo();
2633   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2634 }
2635 
2636 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2637   if (!CI->isTailCall())
2638     return false;
2639 
2640   const Function *ParentFn = CI->getParent()->getParent();
2641   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2642     return false;
2643   return true;
2644 }
2645 
2646 // The wave scratch offset register is used as the global base pointer.
2647 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2648                                     SmallVectorImpl<SDValue> &InVals) const {
2649   SelectionDAG &DAG = CLI.DAG;
2650   const SDLoc &DL = CLI.DL;
2651   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2652   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2653   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2654   SDValue Chain = CLI.Chain;
2655   SDValue Callee = CLI.Callee;
2656   bool &IsTailCall = CLI.IsTailCall;
2657   CallingConv::ID CallConv = CLI.CallConv;
2658   bool IsVarArg = CLI.IsVarArg;
2659   bool IsSibCall = false;
2660   bool IsThisReturn = false;
2661   MachineFunction &MF = DAG.getMachineFunction();
2662 
2663   if (Callee.isUndef() || isNullConstant(Callee)) {
2664     if (!CLI.IsTailCall) {
2665       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2666         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2667     }
2668 
2669     return Chain;
2670   }
2671 
2672   if (IsVarArg) {
2673     return lowerUnhandledCall(CLI, InVals,
2674                               "unsupported call to variadic function ");
2675   }
2676 
2677   if (!CLI.CS.getInstruction())
2678     report_fatal_error("unsupported libcall legalization");
2679 
2680   if (!CLI.CS.getCalledFunction()) {
2681     return lowerUnhandledCall(CLI, InVals,
2682                               "unsupported indirect call to function ");
2683   }
2684 
2685   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2686     return lowerUnhandledCall(CLI, InVals,
2687                               "unsupported required tail call to function ");
2688   }
2689 
2690   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2691     // Note the issue is with the CC of the calling function, not of the call
2692     // itself.
2693     return lowerUnhandledCall(CLI, InVals,
2694                           "unsupported call from graphics shader of function ");
2695   }
2696 
2697   if (IsTailCall) {
2698     IsTailCall = isEligibleForTailCallOptimization(
2699       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2700     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2701       report_fatal_error("failed to perform tail call elimination on a call "
2702                          "site marked musttail");
2703     }
2704 
2705     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2706 
2707     // A sibling call is one where we're under the usual C ABI and not planning
2708     // to change that but can still do a tail call:
2709     if (!TailCallOpt && IsTailCall)
2710       IsSibCall = true;
2711 
2712     if (IsTailCall)
2713       ++NumTailCalls;
2714   }
2715 
2716   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2717 
2718   // Analyze operands of the call, assigning locations to each operand.
2719   SmallVector<CCValAssign, 16> ArgLocs;
2720   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2721   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2722 
2723   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2724 
2725   // Get a count of how many bytes are to be pushed on the stack.
2726   unsigned NumBytes = CCInfo.getNextStackOffset();
2727 
2728   if (IsSibCall) {
2729     // Since we're not changing the ABI to make this a tail call, the memory
2730     // operands are already available in the caller's incoming argument space.
2731     NumBytes = 0;
2732   }
2733 
2734   // FPDiff is the byte offset of the call's argument area from the callee's.
2735   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2736   // by this amount for a tail call. In a sibling call it must be 0 because the
2737   // caller will deallocate the entire stack and the callee still expects its
2738   // arguments to begin at SP+0. Completely unused for non-tail calls.
2739   int32_t FPDiff = 0;
2740   MachineFrameInfo &MFI = MF.getFrameInfo();
2741   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2742 
2743   // Adjust the stack pointer for the new arguments...
2744   // These operations are automatically eliminated by the prolog/epilog pass
2745   if (!IsSibCall) {
2746     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2747 
2748     SmallVector<SDValue, 4> CopyFromChains;
2749 
2750     // In the HSA case, this should be an identity copy.
2751     SDValue ScratchRSrcReg
2752       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2753     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2754     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2755     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2756   }
2757 
2758   SmallVector<SDValue, 8> MemOpChains;
2759   MVT PtrVT = MVT::i32;
2760 
2761   // Walk the register/memloc assignments, inserting copies/loads.
2762   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2763     CCValAssign &VA = ArgLocs[i];
2764     SDValue Arg = OutVals[i];
2765 
2766     // Promote the value if needed.
2767     switch (VA.getLocInfo()) {
2768     case CCValAssign::Full:
2769       break;
2770     case CCValAssign::BCvt:
2771       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2772       break;
2773     case CCValAssign::ZExt:
2774       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2775       break;
2776     case CCValAssign::SExt:
2777       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2778       break;
2779     case CCValAssign::AExt:
2780       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2781       break;
2782     case CCValAssign::FPExt:
2783       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2784       break;
2785     default:
2786       llvm_unreachable("Unknown loc info!");
2787     }
2788 
2789     if (VA.isRegLoc()) {
2790       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2791     } else {
2792       assert(VA.isMemLoc());
2793 
2794       SDValue DstAddr;
2795       MachinePointerInfo DstInfo;
2796 
2797       unsigned LocMemOffset = VA.getLocMemOffset();
2798       int32_t Offset = LocMemOffset;
2799 
2800       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2801       MaybeAlign Alignment;
2802 
2803       if (IsTailCall) {
2804         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2805         unsigned OpSize = Flags.isByVal() ?
2806           Flags.getByValSize() : VA.getValVT().getStoreSize();
2807 
2808         // FIXME: We can have better than the minimum byval required alignment.
2809         Alignment =
2810             Flags.isByVal()
2811                 ? Flags.getNonZeroByValAlign()
2812                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2813 
2814         Offset = Offset + FPDiff;
2815         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2816 
2817         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2818         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2819 
2820         // Make sure any stack arguments overlapping with where we're storing
2821         // are loaded before this eventual operation. Otherwise they'll be
2822         // clobbered.
2823 
2824         // FIXME: Why is this really necessary? This seems to just result in a
2825         // lot of code to copy the stack and write them back to the same
2826         // locations, which are supposed to be immutable?
2827         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2828       } else {
2829         DstAddr = PtrOff;
2830         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2831         Alignment =
2832             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2833       }
2834 
2835       if (Outs[i].Flags.isByVal()) {
2836         SDValue SizeNode =
2837             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2838         SDValue Cpy =
2839             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2840                           Outs[i].Flags.getNonZeroByValAlign(),
2841                           /*isVol = */ false, /*AlwaysInline = */ true,
2842                           /*isTailCall = */ false, DstInfo,
2843                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2844 
2845         MemOpChains.push_back(Cpy);
2846       } else {
2847         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2848                                      Alignment ? Alignment->value() : 0);
2849         MemOpChains.push_back(Store);
2850       }
2851     }
2852   }
2853 
2854   // Copy special input registers after user input arguments.
2855   passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2856 
2857   if (!MemOpChains.empty())
2858     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2859 
2860   // Build a sequence of copy-to-reg nodes chained together with token chain
2861   // and flag operands which copy the outgoing args into the appropriate regs.
2862   SDValue InFlag;
2863   for (auto &RegToPass : RegsToPass) {
2864     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2865                              RegToPass.second, InFlag);
2866     InFlag = Chain.getValue(1);
2867   }
2868 
2869 
2870   SDValue PhysReturnAddrReg;
2871   if (IsTailCall) {
2872     // Since the return is being combined with the call, we need to pass on the
2873     // return address.
2874 
2875     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2876     SDValue ReturnAddrReg = CreateLiveInRegister(
2877       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2878 
2879     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2880                                         MVT::i64);
2881     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2882     InFlag = Chain.getValue(1);
2883   }
2884 
2885   // We don't usually want to end the call-sequence here because we would tidy
2886   // the frame up *after* the call, however in the ABI-changing tail-call case
2887   // we've carefully laid out the parameters so that when sp is reset they'll be
2888   // in the correct location.
2889   if (IsTailCall && !IsSibCall) {
2890     Chain = DAG.getCALLSEQ_END(Chain,
2891                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2892                                DAG.getTargetConstant(0, DL, MVT::i32),
2893                                InFlag, DL);
2894     InFlag = Chain.getValue(1);
2895   }
2896 
2897   std::vector<SDValue> Ops;
2898   Ops.push_back(Chain);
2899   Ops.push_back(Callee);
2900   // Add a redundant copy of the callee global which will not be legalized, as
2901   // we need direct access to the callee later.
2902   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee);
2903   const GlobalValue *GV = GSD->getGlobal();
2904   Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2905 
2906   if (IsTailCall) {
2907     // Each tail call may have to adjust the stack by a different amount, so
2908     // this information must travel along with the operation for eventual
2909     // consumption by emitEpilogue.
2910     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2911 
2912     Ops.push_back(PhysReturnAddrReg);
2913   }
2914 
2915   // Add argument registers to the end of the list so that they are known live
2916   // into the call.
2917   for (auto &RegToPass : RegsToPass) {
2918     Ops.push_back(DAG.getRegister(RegToPass.first,
2919                                   RegToPass.second.getValueType()));
2920   }
2921 
2922   // Add a register mask operand representing the call-preserved registers.
2923 
2924   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2925   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2926   assert(Mask && "Missing call preserved mask for calling convention");
2927   Ops.push_back(DAG.getRegisterMask(Mask));
2928 
2929   if (InFlag.getNode())
2930     Ops.push_back(InFlag);
2931 
2932   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2933 
2934   // If we're doing a tall call, use a TC_RETURN here rather than an
2935   // actual call instruction.
2936   if (IsTailCall) {
2937     MFI.setHasTailCall();
2938     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2939   }
2940 
2941   // Returns a chain and a flag for retval copy to use.
2942   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2943   Chain = Call.getValue(0);
2944   InFlag = Call.getValue(1);
2945 
2946   uint64_t CalleePopBytes = NumBytes;
2947   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2948                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2949                              InFlag, DL);
2950   if (!Ins.empty())
2951     InFlag = Chain.getValue(1);
2952 
2953   // Handle result values, copying them out of physregs into vregs that we
2954   // return.
2955   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2956                          InVals, IsThisReturn,
2957                          IsThisReturn ? OutVals[0] : SDValue());
2958 }
2959 
2960 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
2961                                              const MachineFunction &MF) const {
2962   Register Reg = StringSwitch<Register>(RegName)
2963     .Case("m0", AMDGPU::M0)
2964     .Case("exec", AMDGPU::EXEC)
2965     .Case("exec_lo", AMDGPU::EXEC_LO)
2966     .Case("exec_hi", AMDGPU::EXEC_HI)
2967     .Case("flat_scratch", AMDGPU::FLAT_SCR)
2968     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2969     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2970     .Default(Register());
2971 
2972   if (Reg == AMDGPU::NoRegister) {
2973     report_fatal_error(Twine("invalid register name \""
2974                              + StringRef(RegName)  + "\"."));
2975 
2976   }
2977 
2978   if (!Subtarget->hasFlatScrRegister() &&
2979        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2980     report_fatal_error(Twine("invalid register \""
2981                              + StringRef(RegName)  + "\" for subtarget."));
2982   }
2983 
2984   switch (Reg) {
2985   case AMDGPU::M0:
2986   case AMDGPU::EXEC_LO:
2987   case AMDGPU::EXEC_HI:
2988   case AMDGPU::FLAT_SCR_LO:
2989   case AMDGPU::FLAT_SCR_HI:
2990     if (VT.getSizeInBits() == 32)
2991       return Reg;
2992     break;
2993   case AMDGPU::EXEC:
2994   case AMDGPU::FLAT_SCR:
2995     if (VT.getSizeInBits() == 64)
2996       return Reg;
2997     break;
2998   default:
2999     llvm_unreachable("missing register type checking");
3000   }
3001 
3002   report_fatal_error(Twine("invalid type for register \""
3003                            + StringRef(RegName) + "\"."));
3004 }
3005 
3006 // If kill is not the last instruction, split the block so kill is always a
3007 // proper terminator.
3008 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3009                                                     MachineBasicBlock *BB) const {
3010   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3011 
3012   MachineBasicBlock::iterator SplitPoint(&MI);
3013   ++SplitPoint;
3014 
3015   if (SplitPoint == BB->end()) {
3016     // Don't bother with a new block.
3017     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3018     return BB;
3019   }
3020 
3021   MachineFunction *MF = BB->getParent();
3022   MachineBasicBlock *SplitBB
3023     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3024 
3025   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3026   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3027 
3028   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3029   BB->addSuccessor(SplitBB);
3030 
3031   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3032   return SplitBB;
3033 }
3034 
3035 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3036 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3037 // be the first instruction in the remainder block.
3038 //
3039 /// \returns { LoopBody, Remainder }
3040 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3041 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3042   MachineFunction *MF = MBB.getParent();
3043   MachineBasicBlock::iterator I(&MI);
3044 
3045   // To insert the loop we need to split the block. Move everything after this
3046   // point to a new block, and insert a new empty block between the two.
3047   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3048   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3049   MachineFunction::iterator MBBI(MBB);
3050   ++MBBI;
3051 
3052   MF->insert(MBBI, LoopBB);
3053   MF->insert(MBBI, RemainderBB);
3054 
3055   LoopBB->addSuccessor(LoopBB);
3056   LoopBB->addSuccessor(RemainderBB);
3057 
3058   // Move the rest of the block into a new block.
3059   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3060 
3061   if (InstInLoop) {
3062     auto Next = std::next(I);
3063 
3064     // Move instruction to loop body.
3065     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3066 
3067     // Move the rest of the block.
3068     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3069   } else {
3070     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3071   }
3072 
3073   MBB.addSuccessor(LoopBB);
3074 
3075   return std::make_pair(LoopBB, RemainderBB);
3076 }
3077 
3078 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3079 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3080   MachineBasicBlock *MBB = MI.getParent();
3081   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3082   auto I = MI.getIterator();
3083   auto E = std::next(I);
3084 
3085   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3086     .addImm(0);
3087 
3088   MIBundleBuilder Bundler(*MBB, I, E);
3089   finalizeBundle(*MBB, Bundler.begin());
3090 }
3091 
3092 MachineBasicBlock *
3093 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3094                                          MachineBasicBlock *BB) const {
3095   const DebugLoc &DL = MI.getDebugLoc();
3096 
3097   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3098 
3099   MachineBasicBlock *LoopBB;
3100   MachineBasicBlock *RemainderBB;
3101   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3102 
3103   // Apparently kill flags are only valid if the def is in the same block?
3104   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3105     Src->setIsKill(false);
3106 
3107   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3108 
3109   MachineBasicBlock::iterator I = LoopBB->end();
3110 
3111   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3112     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3113 
3114   // Clear TRAP_STS.MEM_VIOL
3115   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3116     .addImm(0)
3117     .addImm(EncodedReg);
3118 
3119   bundleInstWithWaitcnt(MI);
3120 
3121   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3122 
3123   // Load and check TRAP_STS.MEM_VIOL
3124   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3125     .addImm(EncodedReg);
3126 
3127   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3128   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3129     .addReg(Reg, RegState::Kill)
3130     .addImm(0);
3131   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3132     .addMBB(LoopBB);
3133 
3134   return RemainderBB;
3135 }
3136 
3137 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3138 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3139 // will only do one iteration. In the worst case, this will loop 64 times.
3140 //
3141 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3142 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3143   const SIInstrInfo *TII,
3144   MachineRegisterInfo &MRI,
3145   MachineBasicBlock &OrigBB,
3146   MachineBasicBlock &LoopBB,
3147   const DebugLoc &DL,
3148   const MachineOperand &IdxReg,
3149   unsigned InitReg,
3150   unsigned ResultReg,
3151   unsigned PhiReg,
3152   unsigned InitSaveExecReg,
3153   int Offset,
3154   bool UseGPRIdxMode,
3155   bool IsIndirectSrc) {
3156   MachineFunction *MF = OrigBB.getParent();
3157   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3158   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3159   MachineBasicBlock::iterator I = LoopBB.begin();
3160 
3161   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3162   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3163   Register NewExec = MRI.createVirtualRegister(BoolRC);
3164   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3165   Register CondReg = MRI.createVirtualRegister(BoolRC);
3166 
3167   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3168     .addReg(InitReg)
3169     .addMBB(&OrigBB)
3170     .addReg(ResultReg)
3171     .addMBB(&LoopBB);
3172 
3173   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3174     .addReg(InitSaveExecReg)
3175     .addMBB(&OrigBB)
3176     .addReg(NewExec)
3177     .addMBB(&LoopBB);
3178 
3179   // Read the next variant <- also loop target.
3180   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3181     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3182 
3183   // Compare the just read M0 value to all possible Idx values.
3184   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3185     .addReg(CurrentIdxReg)
3186     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3187 
3188   // Update EXEC, save the original EXEC value to VCC.
3189   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3190                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3191           NewExec)
3192     .addReg(CondReg, RegState::Kill);
3193 
3194   MRI.setSimpleHint(NewExec, CondReg);
3195 
3196   if (UseGPRIdxMode) {
3197     unsigned IdxReg;
3198     if (Offset == 0) {
3199       IdxReg = CurrentIdxReg;
3200     } else {
3201       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3202       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3203         .addReg(CurrentIdxReg, RegState::Kill)
3204         .addImm(Offset);
3205     }
3206     unsigned IdxMode = IsIndirectSrc ?
3207       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3208     MachineInstr *SetOn =
3209       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3210       .addReg(IdxReg, RegState::Kill)
3211       .addImm(IdxMode);
3212     SetOn->getOperand(3).setIsUndef();
3213   } else {
3214     // Move index from VCC into M0
3215     if (Offset == 0) {
3216       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3217         .addReg(CurrentIdxReg, RegState::Kill);
3218     } else {
3219       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3220         .addReg(CurrentIdxReg, RegState::Kill)
3221         .addImm(Offset);
3222     }
3223   }
3224 
3225   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3226   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3227   MachineInstr *InsertPt =
3228     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3229                                                   : AMDGPU::S_XOR_B64_term), Exec)
3230       .addReg(Exec)
3231       .addReg(NewExec);
3232 
3233   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3234   // s_cbranch_scc0?
3235 
3236   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3237   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3238     .addMBB(&LoopBB);
3239 
3240   return InsertPt->getIterator();
3241 }
3242 
3243 // This has slightly sub-optimal regalloc when the source vector is killed by
3244 // the read. The register allocator does not understand that the kill is
3245 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3246 // subregister from it, using 1 more VGPR than necessary. This was saved when
3247 // this was expanded after register allocation.
3248 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3249                                                   MachineBasicBlock &MBB,
3250                                                   MachineInstr &MI,
3251                                                   unsigned InitResultReg,
3252                                                   unsigned PhiReg,
3253                                                   int Offset,
3254                                                   bool UseGPRIdxMode,
3255                                                   bool IsIndirectSrc) {
3256   MachineFunction *MF = MBB.getParent();
3257   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3258   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3259   MachineRegisterInfo &MRI = MF->getRegInfo();
3260   const DebugLoc &DL = MI.getDebugLoc();
3261   MachineBasicBlock::iterator I(&MI);
3262 
3263   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3264   Register DstReg = MI.getOperand(0).getReg();
3265   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3266   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3267   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3268   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3269 
3270   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3271 
3272   // Save the EXEC mask
3273   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3274     .addReg(Exec);
3275 
3276   MachineBasicBlock *LoopBB;
3277   MachineBasicBlock *RemainderBB;
3278   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3279 
3280   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3281 
3282   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3283                                       InitResultReg, DstReg, PhiReg, TmpExec,
3284                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3285 
3286   MachineBasicBlock::iterator First = RemainderBB->begin();
3287   BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec)
3288     .addReg(SaveExec);
3289 
3290   return InsPt;
3291 }
3292 
3293 // Returns subreg index, offset
3294 static std::pair<unsigned, int>
3295 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3296                             const TargetRegisterClass *SuperRC,
3297                             unsigned VecReg,
3298                             int Offset) {
3299   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3300 
3301   // Skip out of bounds offsets, or else we would end up using an undefined
3302   // register.
3303   if (Offset >= NumElts || Offset < 0)
3304     return std::make_pair(AMDGPU::sub0, Offset);
3305 
3306   return std::make_pair(AMDGPURegisterInfo::getSubRegFromChannel(Offset), 0);
3307 }
3308 
3309 // Return true if the index is an SGPR and was set.
3310 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3311                                  MachineRegisterInfo &MRI,
3312                                  MachineInstr &MI,
3313                                  int Offset,
3314                                  bool UseGPRIdxMode,
3315                                  bool IsIndirectSrc) {
3316   MachineBasicBlock *MBB = MI.getParent();
3317   const DebugLoc &DL = MI.getDebugLoc();
3318   MachineBasicBlock::iterator I(&MI);
3319 
3320   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3321   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3322 
3323   assert(Idx->getReg() != AMDGPU::NoRegister);
3324 
3325   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3326     return false;
3327 
3328   if (UseGPRIdxMode) {
3329     unsigned IdxMode = IsIndirectSrc ?
3330       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3331     if (Offset == 0) {
3332       MachineInstr *SetOn =
3333           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3334               .add(*Idx)
3335               .addImm(IdxMode);
3336 
3337       SetOn->getOperand(3).setIsUndef();
3338     } else {
3339       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3340       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3341           .add(*Idx)
3342           .addImm(Offset);
3343       MachineInstr *SetOn =
3344         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3345         .addReg(Tmp, RegState::Kill)
3346         .addImm(IdxMode);
3347 
3348       SetOn->getOperand(3).setIsUndef();
3349     }
3350 
3351     return true;
3352   }
3353 
3354   if (Offset == 0) {
3355     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3356       .add(*Idx);
3357   } else {
3358     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3359       .add(*Idx)
3360       .addImm(Offset);
3361   }
3362 
3363   return true;
3364 }
3365 
3366 // Control flow needs to be inserted if indexing with a VGPR.
3367 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3368                                           MachineBasicBlock &MBB,
3369                                           const GCNSubtarget &ST) {
3370   const SIInstrInfo *TII = ST.getInstrInfo();
3371   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3372   MachineFunction *MF = MBB.getParent();
3373   MachineRegisterInfo &MRI = MF->getRegInfo();
3374 
3375   Register Dst = MI.getOperand(0).getReg();
3376   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3377   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3378 
3379   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3380 
3381   unsigned SubReg;
3382   std::tie(SubReg, Offset)
3383     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3384 
3385   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3386 
3387   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3388     MachineBasicBlock::iterator I(&MI);
3389     const DebugLoc &DL = MI.getDebugLoc();
3390 
3391     if (UseGPRIdxMode) {
3392       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3393       // to avoid interfering with other uses, so probably requires a new
3394       // optimization pass.
3395       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3396         .addReg(SrcReg, RegState::Undef, SubReg)
3397         .addReg(SrcReg, RegState::Implicit)
3398         .addReg(AMDGPU::M0, RegState::Implicit);
3399       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3400     } else {
3401       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3402         .addReg(SrcReg, RegState::Undef, SubReg)
3403         .addReg(SrcReg, RegState::Implicit);
3404     }
3405 
3406     MI.eraseFromParent();
3407 
3408     return &MBB;
3409   }
3410 
3411   const DebugLoc &DL = MI.getDebugLoc();
3412   MachineBasicBlock::iterator I(&MI);
3413 
3414   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3415   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3416 
3417   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3418 
3419   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3420                               Offset, UseGPRIdxMode, true);
3421   MachineBasicBlock *LoopBB = InsPt->getParent();
3422 
3423   if (UseGPRIdxMode) {
3424     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3425       .addReg(SrcReg, RegState::Undef, SubReg)
3426       .addReg(SrcReg, RegState::Implicit)
3427       .addReg(AMDGPU::M0, RegState::Implicit);
3428     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3429   } else {
3430     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3431       .addReg(SrcReg, RegState::Undef, SubReg)
3432       .addReg(SrcReg, RegState::Implicit);
3433   }
3434 
3435   MI.eraseFromParent();
3436 
3437   return LoopBB;
3438 }
3439 
3440 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3441                                           MachineBasicBlock &MBB,
3442                                           const GCNSubtarget &ST) {
3443   const SIInstrInfo *TII = ST.getInstrInfo();
3444   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3445   MachineFunction *MF = MBB.getParent();
3446   MachineRegisterInfo &MRI = MF->getRegInfo();
3447 
3448   Register Dst = MI.getOperand(0).getReg();
3449   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3450   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3451   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3452   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3453   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3454 
3455   // This can be an immediate, but will be folded later.
3456   assert(Val->getReg());
3457 
3458   unsigned SubReg;
3459   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3460                                                          SrcVec->getReg(),
3461                                                          Offset);
3462   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3463 
3464   if (Idx->getReg() == AMDGPU::NoRegister) {
3465     MachineBasicBlock::iterator I(&MI);
3466     const DebugLoc &DL = MI.getDebugLoc();
3467 
3468     assert(Offset == 0);
3469 
3470     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3471         .add(*SrcVec)
3472         .add(*Val)
3473         .addImm(SubReg);
3474 
3475     MI.eraseFromParent();
3476     return &MBB;
3477   }
3478 
3479   const MCInstrDesc &MovRelDesc
3480     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3481 
3482   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3483     MachineBasicBlock::iterator I(&MI);
3484     const DebugLoc &DL = MI.getDebugLoc();
3485     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3486       .addReg(SrcVec->getReg())
3487       .add(*Val)
3488       .addImm(SubReg);
3489     if (UseGPRIdxMode)
3490       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3491 
3492     MI.eraseFromParent();
3493     return &MBB;
3494   }
3495 
3496   if (Val->isReg())
3497     MRI.clearKillFlags(Val->getReg());
3498 
3499   const DebugLoc &DL = MI.getDebugLoc();
3500 
3501   Register PhiReg = MRI.createVirtualRegister(VecRC);
3502 
3503   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3504                               Offset, UseGPRIdxMode, false);
3505   MachineBasicBlock *LoopBB = InsPt->getParent();
3506 
3507   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3508     .addReg(PhiReg)
3509     .add(*Val)
3510     .addImm(AMDGPU::sub0);
3511   if (UseGPRIdxMode)
3512     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3513 
3514   MI.eraseFromParent();
3515   return LoopBB;
3516 }
3517 
3518 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3519   MachineInstr &MI, MachineBasicBlock *BB) const {
3520 
3521   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3522   MachineFunction *MF = BB->getParent();
3523   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3524 
3525   if (TII->isMIMG(MI)) {
3526     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3527       report_fatal_error("missing mem operand from MIMG instruction");
3528     }
3529     // Add a memoperand for mimg instructions so that they aren't assumed to
3530     // be ordered memory instuctions.
3531 
3532     return BB;
3533   }
3534 
3535   switch (MI.getOpcode()) {
3536   case AMDGPU::S_ADD_U64_PSEUDO:
3537   case AMDGPU::S_SUB_U64_PSEUDO: {
3538     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3539     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3540     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3541     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3542     const DebugLoc &DL = MI.getDebugLoc();
3543 
3544     MachineOperand &Dest = MI.getOperand(0);
3545     MachineOperand &Src0 = MI.getOperand(1);
3546     MachineOperand &Src1 = MI.getOperand(2);
3547 
3548     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3549     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3550 
3551     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3552      Src0, BoolRC, AMDGPU::sub0,
3553      &AMDGPU::SReg_32RegClass);
3554     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3555       Src0, BoolRC, AMDGPU::sub1,
3556       &AMDGPU::SReg_32RegClass);
3557 
3558     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3559       Src1, BoolRC, AMDGPU::sub0,
3560       &AMDGPU::SReg_32RegClass);
3561     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3562       Src1, BoolRC, AMDGPU::sub1,
3563       &AMDGPU::SReg_32RegClass);
3564 
3565     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3566 
3567     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3568     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3569     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3570       .add(Src0Sub0)
3571       .add(Src1Sub0);
3572     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3573       .add(Src0Sub1)
3574       .add(Src1Sub1);
3575     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3576       .addReg(DestSub0)
3577       .addImm(AMDGPU::sub0)
3578       .addReg(DestSub1)
3579       .addImm(AMDGPU::sub1);
3580     MI.eraseFromParent();
3581     return BB;
3582   }
3583   case AMDGPU::SI_INIT_M0: {
3584     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3585             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3586         .add(MI.getOperand(0));
3587     MI.eraseFromParent();
3588     return BB;
3589   }
3590   case AMDGPU::SI_INIT_EXEC:
3591     // This should be before all vector instructions.
3592     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3593             AMDGPU::EXEC)
3594         .addImm(MI.getOperand(0).getImm());
3595     MI.eraseFromParent();
3596     return BB;
3597 
3598   case AMDGPU::SI_INIT_EXEC_LO:
3599     // This should be before all vector instructions.
3600     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3601             AMDGPU::EXEC_LO)
3602         .addImm(MI.getOperand(0).getImm());
3603     MI.eraseFromParent();
3604     return BB;
3605 
3606   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3607     // Extract the thread count from an SGPR input and set EXEC accordingly.
3608     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3609     //
3610     // S_BFE_U32 count, input, {shift, 7}
3611     // S_BFM_B64 exec, count, 0
3612     // S_CMP_EQ_U32 count, 64
3613     // S_CMOV_B64 exec, -1
3614     MachineInstr *FirstMI = &*BB->begin();
3615     MachineRegisterInfo &MRI = MF->getRegInfo();
3616     Register InputReg = MI.getOperand(0).getReg();
3617     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3618     bool Found = false;
3619 
3620     // Move the COPY of the input reg to the beginning, so that we can use it.
3621     for (auto I = BB->begin(); I != &MI; I++) {
3622       if (I->getOpcode() != TargetOpcode::COPY ||
3623           I->getOperand(0).getReg() != InputReg)
3624         continue;
3625 
3626       if (I == FirstMI) {
3627         FirstMI = &*++BB->begin();
3628       } else {
3629         I->removeFromParent();
3630         BB->insert(FirstMI, &*I);
3631       }
3632       Found = true;
3633       break;
3634     }
3635     assert(Found);
3636     (void)Found;
3637 
3638     // This should be before all vector instructions.
3639     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3640     bool isWave32 = getSubtarget()->isWave32();
3641     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3642     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3643         .addReg(InputReg)
3644         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3645     BuildMI(*BB, FirstMI, DebugLoc(),
3646             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3647             Exec)
3648         .addReg(CountReg)
3649         .addImm(0);
3650     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3651         .addReg(CountReg, RegState::Kill)
3652         .addImm(getSubtarget()->getWavefrontSize());
3653     BuildMI(*BB, FirstMI, DebugLoc(),
3654             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3655             Exec)
3656         .addImm(-1);
3657     MI.eraseFromParent();
3658     return BB;
3659   }
3660 
3661   case AMDGPU::GET_GROUPSTATICSIZE: {
3662     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3663            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3664     DebugLoc DL = MI.getDebugLoc();
3665     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3666         .add(MI.getOperand(0))
3667         .addImm(MFI->getLDSSize());
3668     MI.eraseFromParent();
3669     return BB;
3670   }
3671   case AMDGPU::SI_INDIRECT_SRC_V1:
3672   case AMDGPU::SI_INDIRECT_SRC_V2:
3673   case AMDGPU::SI_INDIRECT_SRC_V4:
3674   case AMDGPU::SI_INDIRECT_SRC_V8:
3675   case AMDGPU::SI_INDIRECT_SRC_V16:
3676     return emitIndirectSrc(MI, *BB, *getSubtarget());
3677   case AMDGPU::SI_INDIRECT_DST_V1:
3678   case AMDGPU::SI_INDIRECT_DST_V2:
3679   case AMDGPU::SI_INDIRECT_DST_V4:
3680   case AMDGPU::SI_INDIRECT_DST_V8:
3681   case AMDGPU::SI_INDIRECT_DST_V16:
3682     return emitIndirectDst(MI, *BB, *getSubtarget());
3683   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3684   case AMDGPU::SI_KILL_I1_PSEUDO:
3685     return splitKillBlock(MI, BB);
3686   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3687     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3688     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3689     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3690 
3691     Register Dst = MI.getOperand(0).getReg();
3692     Register Src0 = MI.getOperand(1).getReg();
3693     Register Src1 = MI.getOperand(2).getReg();
3694     const DebugLoc &DL = MI.getDebugLoc();
3695     Register SrcCond = MI.getOperand(3).getReg();
3696 
3697     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3698     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3699     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3700     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
3701 
3702     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3703       .addReg(SrcCond);
3704     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3705       .addImm(0)
3706       .addReg(Src0, 0, AMDGPU::sub0)
3707       .addImm(0)
3708       .addReg(Src1, 0, AMDGPU::sub0)
3709       .addReg(SrcCondCopy);
3710     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3711       .addImm(0)
3712       .addReg(Src0, 0, AMDGPU::sub1)
3713       .addImm(0)
3714       .addReg(Src1, 0, AMDGPU::sub1)
3715       .addReg(SrcCondCopy);
3716 
3717     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3718       .addReg(DstLo)
3719       .addImm(AMDGPU::sub0)
3720       .addReg(DstHi)
3721       .addImm(AMDGPU::sub1);
3722     MI.eraseFromParent();
3723     return BB;
3724   }
3725   case AMDGPU::SI_BR_UNDEF: {
3726     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3727     const DebugLoc &DL = MI.getDebugLoc();
3728     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3729                            .add(MI.getOperand(0));
3730     Br->getOperand(1).setIsUndef(true); // read undef SCC
3731     MI.eraseFromParent();
3732     return BB;
3733   }
3734   case AMDGPU::ADJCALLSTACKUP:
3735   case AMDGPU::ADJCALLSTACKDOWN: {
3736     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3737     MachineInstrBuilder MIB(*MF, &MI);
3738 
3739     // Add an implicit use of the frame offset reg to prevent the restore copy
3740     // inserted after the call from being reorderd after stack operations in the
3741     // the caller's frame.
3742     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3743         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3744         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3745     return BB;
3746   }
3747   case AMDGPU::SI_CALL_ISEL: {
3748     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3749     const DebugLoc &DL = MI.getDebugLoc();
3750 
3751     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3752 
3753     MachineInstrBuilder MIB;
3754     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3755 
3756     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3757       MIB.add(MI.getOperand(I));
3758 
3759     MIB.cloneMemRefs(MI);
3760     MI.eraseFromParent();
3761     return BB;
3762   }
3763   case AMDGPU::V_ADD_I32_e32:
3764   case AMDGPU::V_SUB_I32_e32:
3765   case AMDGPU::V_SUBREV_I32_e32: {
3766     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3767     const DebugLoc &DL = MI.getDebugLoc();
3768     unsigned Opc = MI.getOpcode();
3769 
3770     bool NeedClampOperand = false;
3771     if (TII->pseudoToMCOpcode(Opc) == -1) {
3772       Opc = AMDGPU::getVOPe64(Opc);
3773       NeedClampOperand = true;
3774     }
3775 
3776     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3777     if (TII->isVOP3(*I)) {
3778       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3779       const SIRegisterInfo *TRI = ST.getRegisterInfo();
3780       I.addReg(TRI->getVCC(), RegState::Define);
3781     }
3782     I.add(MI.getOperand(1))
3783      .add(MI.getOperand(2));
3784     if (NeedClampOperand)
3785       I.addImm(0); // clamp bit for e64 encoding
3786 
3787     TII->legalizeOperands(*I);
3788 
3789     MI.eraseFromParent();
3790     return BB;
3791   }
3792   case AMDGPU::DS_GWS_INIT:
3793   case AMDGPU::DS_GWS_SEMA_V:
3794   case AMDGPU::DS_GWS_SEMA_BR:
3795   case AMDGPU::DS_GWS_SEMA_P:
3796   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
3797   case AMDGPU::DS_GWS_BARRIER:
3798     // A s_waitcnt 0 is required to be the instruction immediately following.
3799     if (getSubtarget()->hasGWSAutoReplay()) {
3800       bundleInstWithWaitcnt(MI);
3801       return BB;
3802     }
3803 
3804     return emitGWSMemViolTestLoop(MI, BB);
3805   default:
3806     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3807   }
3808 }
3809 
3810 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3811   return isTypeLegal(VT.getScalarType());
3812 }
3813 
3814 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3815   // This currently forces unfolding various combinations of fsub into fma with
3816   // free fneg'd operands. As long as we have fast FMA (controlled by
3817   // isFMAFasterThanFMulAndFAdd), we should perform these.
3818 
3819   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3820   // most of these combines appear to be cycle neutral but save on instruction
3821   // count / code size.
3822   return true;
3823 }
3824 
3825 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3826                                          EVT VT) const {
3827   if (!VT.isVector()) {
3828     return MVT::i1;
3829   }
3830   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3831 }
3832 
3833 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3834   // TODO: Should i16 be used always if legal? For now it would force VALU
3835   // shifts.
3836   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3837 }
3838 
3839 // Answering this is somewhat tricky and depends on the specific device which
3840 // have different rates for fma or all f64 operations.
3841 //
3842 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3843 // regardless of which device (although the number of cycles differs between
3844 // devices), so it is always profitable for f64.
3845 //
3846 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3847 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3848 // which we can always do even without fused FP ops since it returns the same
3849 // result as the separate operations and since it is always full
3850 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3851 // however does not support denormals, so we do report fma as faster if we have
3852 // a fast fma device and require denormals.
3853 //
3854 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
3855                                                   EVT VT) const {
3856   VT = VT.getScalarType();
3857 
3858   switch (VT.getSimpleVT().SimpleTy) {
3859   case MVT::f32: {
3860     // This is as fast on some subtargets. However, we always have full rate f32
3861     // mad available which returns the same result as the separate operations
3862     // which we should prefer over fma. We can't use this if we want to support
3863     // denormals, so only report this in these cases.
3864     if (hasFP32Denormals(MF))
3865       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3866 
3867     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3868     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3869   }
3870   case MVT::f64:
3871     return true;
3872   case MVT::f16:
3873     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
3874   default:
3875     break;
3876   }
3877 
3878   return false;
3879 }
3880 
3881 bool SITargetLowering::isFMADLegalForFAddFSub(const SelectionDAG &DAG,
3882                                               const SDNode *N) const {
3883   // TODO: Check future ftz flag
3884   // v_mad_f32/v_mac_f32 do not support denormals.
3885   EVT VT = N->getValueType(0);
3886   if (VT == MVT::f32)
3887     return !hasFP32Denormals(DAG.getMachineFunction());
3888   if (VT == MVT::f16) {
3889     return Subtarget->hasMadF16() &&
3890            !hasFP64FP16Denormals(DAG.getMachineFunction());
3891   }
3892 
3893   return false;
3894 }
3895 
3896 //===----------------------------------------------------------------------===//
3897 // Custom DAG Lowering Operations
3898 //===----------------------------------------------------------------------===//
3899 
3900 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3901 // wider vector type is legal.
3902 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3903                                              SelectionDAG &DAG) const {
3904   unsigned Opc = Op.getOpcode();
3905   EVT VT = Op.getValueType();
3906   assert(VT == MVT::v4f16);
3907 
3908   SDValue Lo, Hi;
3909   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3910 
3911   SDLoc SL(Op);
3912   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3913                              Op->getFlags());
3914   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3915                              Op->getFlags());
3916 
3917   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3918 }
3919 
3920 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3921 // wider vector type is legal.
3922 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3923                                               SelectionDAG &DAG) const {
3924   unsigned Opc = Op.getOpcode();
3925   EVT VT = Op.getValueType();
3926   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3927 
3928   SDValue Lo0, Hi0;
3929   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3930   SDValue Lo1, Hi1;
3931   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3932 
3933   SDLoc SL(Op);
3934 
3935   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3936                              Op->getFlags());
3937   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3938                              Op->getFlags());
3939 
3940   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3941 }
3942 
3943 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
3944                                               SelectionDAG &DAG) const {
3945   unsigned Opc = Op.getOpcode();
3946   EVT VT = Op.getValueType();
3947   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3948 
3949   SDValue Lo0, Hi0;
3950   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3951   SDValue Lo1, Hi1;
3952   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3953   SDValue Lo2, Hi2;
3954   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
3955 
3956   SDLoc SL(Op);
3957 
3958   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
3959                              Op->getFlags());
3960   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
3961                              Op->getFlags());
3962 
3963   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3964 }
3965 
3966 
3967 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3968   switch (Op.getOpcode()) {
3969   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3970   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3971   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
3972   case ISD::LOAD: {
3973     SDValue Result = LowerLOAD(Op, DAG);
3974     assert((!Result.getNode() ||
3975             Result.getNode()->getNumValues() == 2) &&
3976            "Load should return a value and a chain");
3977     return Result;
3978   }
3979 
3980   case ISD::FSIN:
3981   case ISD::FCOS:
3982     return LowerTrig(Op, DAG);
3983   case ISD::SELECT: return LowerSELECT(Op, DAG);
3984   case ISD::FDIV: return LowerFDIV(Op, DAG);
3985   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3986   case ISD::STORE: return LowerSTORE(Op, DAG);
3987   case ISD::GlobalAddress: {
3988     MachineFunction &MF = DAG.getMachineFunction();
3989     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3990     return LowerGlobalAddress(MFI, Op, DAG);
3991   }
3992   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3993   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3994   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3995   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3996   case ISD::INSERT_SUBVECTOR:
3997     return lowerINSERT_SUBVECTOR(Op, DAG);
3998   case ISD::INSERT_VECTOR_ELT:
3999     return lowerINSERT_VECTOR_ELT(Op, DAG);
4000   case ISD::EXTRACT_VECTOR_ELT:
4001     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4002   case ISD::VECTOR_SHUFFLE:
4003     return lowerVECTOR_SHUFFLE(Op, DAG);
4004   case ISD::BUILD_VECTOR:
4005     return lowerBUILD_VECTOR(Op, DAG);
4006   case ISD::FP_ROUND:
4007     return lowerFP_ROUND(Op, DAG);
4008   case ISD::TRAP:
4009     return lowerTRAP(Op, DAG);
4010   case ISD::DEBUGTRAP:
4011     return lowerDEBUGTRAP(Op, DAG);
4012   case ISD::FABS:
4013   case ISD::FNEG:
4014   case ISD::FCANONICALIZE:
4015     return splitUnaryVectorOp(Op, DAG);
4016   case ISD::FMINNUM:
4017   case ISD::FMAXNUM:
4018     return lowerFMINNUM_FMAXNUM(Op, DAG);
4019   case ISD::FMA:
4020     return splitTernaryVectorOp(Op, DAG);
4021   case ISD::SHL:
4022   case ISD::SRA:
4023   case ISD::SRL:
4024   case ISD::ADD:
4025   case ISD::SUB:
4026   case ISD::MUL:
4027   case ISD::SMIN:
4028   case ISD::SMAX:
4029   case ISD::UMIN:
4030   case ISD::UMAX:
4031   case ISD::FADD:
4032   case ISD::FMUL:
4033   case ISD::FMINNUM_IEEE:
4034   case ISD::FMAXNUM_IEEE:
4035     return splitBinaryVectorOp(Op, DAG);
4036   }
4037   return SDValue();
4038 }
4039 
4040 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4041                                        const SDLoc &DL,
4042                                        SelectionDAG &DAG, bool Unpacked) {
4043   if (!LoadVT.isVector())
4044     return Result;
4045 
4046   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4047     // Truncate to v2i16/v4i16.
4048     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4049 
4050     // Workaround legalizer not scalarizing truncate after vector op
4051     // legalization byt not creating intermediate vector trunc.
4052     SmallVector<SDValue, 4> Elts;
4053     DAG.ExtractVectorElements(Result, Elts);
4054     for (SDValue &Elt : Elts)
4055       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4056 
4057     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4058 
4059     // Bitcast to original type (v2f16/v4f16).
4060     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4061   }
4062 
4063   // Cast back to the original packed type.
4064   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4065 }
4066 
4067 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4068                                               MemSDNode *M,
4069                                               SelectionDAG &DAG,
4070                                               ArrayRef<SDValue> Ops,
4071                                               bool IsIntrinsic) const {
4072   SDLoc DL(M);
4073 
4074   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4075   EVT LoadVT = M->getValueType(0);
4076 
4077   EVT EquivLoadVT = LoadVT;
4078   if (Unpacked && LoadVT.isVector()) {
4079     EquivLoadVT = LoadVT.isVector() ?
4080       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4081                        LoadVT.getVectorNumElements()) : LoadVT;
4082   }
4083 
4084   // Change from v4f16/v2f16 to EquivLoadVT.
4085   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4086 
4087   SDValue Load
4088     = DAG.getMemIntrinsicNode(
4089       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4090       VTList, Ops, M->getMemoryVT(),
4091       M->getMemOperand());
4092   if (!Unpacked) // Just adjusted the opcode.
4093     return Load;
4094 
4095   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4096 
4097   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4098 }
4099 
4100 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4101                                              SelectionDAG &DAG,
4102                                              ArrayRef<SDValue> Ops) const {
4103   SDLoc DL(M);
4104   EVT LoadVT = M->getValueType(0);
4105   EVT EltType = LoadVT.getScalarType();
4106   EVT IntVT = LoadVT.changeTypeToInteger();
4107 
4108   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4109 
4110   unsigned Opc =
4111       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4112 
4113   if (IsD16) {
4114     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4115   }
4116 
4117   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4118   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4119     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4120 
4121   if (isTypeLegal(LoadVT)) {
4122     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4123                                M->getMemOperand(), DAG);
4124   }
4125 
4126   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4127   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4128   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4129                                         M->getMemOperand(), DAG);
4130   return DAG.getMergeValues(
4131       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4132       DL);
4133 }
4134 
4135 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4136                                   SDNode *N, SelectionDAG &DAG) {
4137   EVT VT = N->getValueType(0);
4138   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4139   int CondCode = CD->getSExtValue();
4140   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4141       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4142     return DAG.getUNDEF(VT);
4143 
4144   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4145 
4146   SDValue LHS = N->getOperand(1);
4147   SDValue RHS = N->getOperand(2);
4148 
4149   SDLoc DL(N);
4150 
4151   EVT CmpVT = LHS.getValueType();
4152   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4153     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4154       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4155     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4156     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4157   }
4158 
4159   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4160 
4161   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4162   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4163 
4164   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4165                               DAG.getCondCode(CCOpcode));
4166   if (VT.bitsEq(CCVT))
4167     return SetCC;
4168   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4169 }
4170 
4171 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4172                                   SDNode *N, SelectionDAG &DAG) {
4173   EVT VT = N->getValueType(0);
4174   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4175 
4176   int CondCode = CD->getSExtValue();
4177   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4178       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4179     return DAG.getUNDEF(VT);
4180   }
4181 
4182   SDValue Src0 = N->getOperand(1);
4183   SDValue Src1 = N->getOperand(2);
4184   EVT CmpVT = Src0.getValueType();
4185   SDLoc SL(N);
4186 
4187   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4188     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4189     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4190   }
4191 
4192   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4193   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4194   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4195   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4196   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4197                               Src1, DAG.getCondCode(CCOpcode));
4198   if (VT.bitsEq(CCVT))
4199     return SetCC;
4200   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4201 }
4202 
4203 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4204                                           SmallVectorImpl<SDValue> &Results,
4205                                           SelectionDAG &DAG) const {
4206   switch (N->getOpcode()) {
4207   case ISD::INSERT_VECTOR_ELT: {
4208     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4209       Results.push_back(Res);
4210     return;
4211   }
4212   case ISD::EXTRACT_VECTOR_ELT: {
4213     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4214       Results.push_back(Res);
4215     return;
4216   }
4217   case ISD::INTRINSIC_WO_CHAIN: {
4218     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4219     switch (IID) {
4220     case Intrinsic::amdgcn_cvt_pkrtz: {
4221       SDValue Src0 = N->getOperand(1);
4222       SDValue Src1 = N->getOperand(2);
4223       SDLoc SL(N);
4224       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4225                                 Src0, Src1);
4226       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4227       return;
4228     }
4229     case Intrinsic::amdgcn_cvt_pknorm_i16:
4230     case Intrinsic::amdgcn_cvt_pknorm_u16:
4231     case Intrinsic::amdgcn_cvt_pk_i16:
4232     case Intrinsic::amdgcn_cvt_pk_u16: {
4233       SDValue Src0 = N->getOperand(1);
4234       SDValue Src1 = N->getOperand(2);
4235       SDLoc SL(N);
4236       unsigned Opcode;
4237 
4238       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4239         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4240       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4241         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4242       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4243         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4244       else
4245         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4246 
4247       EVT VT = N->getValueType(0);
4248       if (isTypeLegal(VT))
4249         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4250       else {
4251         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4252         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4253       }
4254       return;
4255     }
4256     }
4257     break;
4258   }
4259   case ISD::INTRINSIC_W_CHAIN: {
4260     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4261       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4262         // FIXME: Hacky
4263         Results.push_back(Res.getOperand(0));
4264         Results.push_back(Res.getOperand(1));
4265       } else {
4266         Results.push_back(Res);
4267         Results.push_back(Res.getValue(1));
4268       }
4269       return;
4270     }
4271 
4272     break;
4273   }
4274   case ISD::SELECT: {
4275     SDLoc SL(N);
4276     EVT VT = N->getValueType(0);
4277     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4278     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4279     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4280 
4281     EVT SelectVT = NewVT;
4282     if (NewVT.bitsLT(MVT::i32)) {
4283       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4284       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4285       SelectVT = MVT::i32;
4286     }
4287 
4288     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4289                                     N->getOperand(0), LHS, RHS);
4290 
4291     if (NewVT != SelectVT)
4292       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4293     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4294     return;
4295   }
4296   case ISD::FNEG: {
4297     if (N->getValueType(0) != MVT::v2f16)
4298       break;
4299 
4300     SDLoc SL(N);
4301     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4302 
4303     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4304                              BC,
4305                              DAG.getConstant(0x80008000, SL, MVT::i32));
4306     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4307     return;
4308   }
4309   case ISD::FABS: {
4310     if (N->getValueType(0) != MVT::v2f16)
4311       break;
4312 
4313     SDLoc SL(N);
4314     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4315 
4316     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4317                              BC,
4318                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4319     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4320     return;
4321   }
4322   default:
4323     break;
4324   }
4325 }
4326 
4327 /// Helper function for LowerBRCOND
4328 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4329 
4330   SDNode *Parent = Value.getNode();
4331   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4332        I != E; ++I) {
4333 
4334     if (I.getUse().get() != Value)
4335       continue;
4336 
4337     if (I->getOpcode() == Opcode)
4338       return *I;
4339   }
4340   return nullptr;
4341 }
4342 
4343 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4344   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4345     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4346     case Intrinsic::amdgcn_if:
4347       return AMDGPUISD::IF;
4348     case Intrinsic::amdgcn_else:
4349       return AMDGPUISD::ELSE;
4350     case Intrinsic::amdgcn_loop:
4351       return AMDGPUISD::LOOP;
4352     case Intrinsic::amdgcn_end_cf:
4353       llvm_unreachable("should not occur");
4354     default:
4355       return 0;
4356     }
4357   }
4358 
4359   // break, if_break, else_break are all only used as inputs to loop, not
4360   // directly as branch conditions.
4361   return 0;
4362 }
4363 
4364 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4365   const Triple &TT = getTargetMachine().getTargetTriple();
4366   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4367           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4368          AMDGPU::shouldEmitConstantsToTextSection(TT);
4369 }
4370 
4371 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4372   // FIXME: Either avoid relying on address space here or change the default
4373   // address space for functions to avoid the explicit check.
4374   return (GV->getValueType()->isFunctionTy() ||
4375           GV->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4376           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4377           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4378          !shouldEmitFixup(GV) &&
4379          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4380 }
4381 
4382 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4383   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4384 }
4385 
4386 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4387   if (!GV->hasExternalLinkage())
4388     return true;
4389 
4390   const auto OS = getTargetMachine().getTargetTriple().getOS();
4391   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4392 }
4393 
4394 /// This transforms the control flow intrinsics to get the branch destination as
4395 /// last parameter, also switches branch target with BR if the need arise
4396 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4397                                       SelectionDAG &DAG) const {
4398   SDLoc DL(BRCOND);
4399 
4400   SDNode *Intr = BRCOND.getOperand(1).getNode();
4401   SDValue Target = BRCOND.getOperand(2);
4402   SDNode *BR = nullptr;
4403   SDNode *SetCC = nullptr;
4404 
4405   if (Intr->getOpcode() == ISD::SETCC) {
4406     // As long as we negate the condition everything is fine
4407     SetCC = Intr;
4408     Intr = SetCC->getOperand(0).getNode();
4409 
4410   } else {
4411     // Get the target from BR if we don't negate the condition
4412     BR = findUser(BRCOND, ISD::BR);
4413     Target = BR->getOperand(1);
4414   }
4415 
4416   // FIXME: This changes the types of the intrinsics instead of introducing new
4417   // nodes with the correct types.
4418   // e.g. llvm.amdgcn.loop
4419 
4420   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4421   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4422 
4423   unsigned CFNode = isCFIntrinsic(Intr);
4424   if (CFNode == 0) {
4425     // This is a uniform branch so we don't need to legalize.
4426     return BRCOND;
4427   }
4428 
4429   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4430                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4431 
4432   assert(!SetCC ||
4433         (SetCC->getConstantOperandVal(1) == 1 &&
4434          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4435                                                              ISD::SETNE));
4436 
4437   // operands of the new intrinsic call
4438   SmallVector<SDValue, 4> Ops;
4439   if (HaveChain)
4440     Ops.push_back(BRCOND.getOperand(0));
4441 
4442   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4443   Ops.push_back(Target);
4444 
4445   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4446 
4447   // build the new intrinsic call
4448   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4449 
4450   if (!HaveChain) {
4451     SDValue Ops[] =  {
4452       SDValue(Result, 0),
4453       BRCOND.getOperand(0)
4454     };
4455 
4456     Result = DAG.getMergeValues(Ops, DL).getNode();
4457   }
4458 
4459   if (BR) {
4460     // Give the branch instruction our target
4461     SDValue Ops[] = {
4462       BR->getOperand(0),
4463       BRCOND.getOperand(2)
4464     };
4465     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4466     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4467     BR = NewBR.getNode();
4468   }
4469 
4470   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4471 
4472   // Copy the intrinsic results to registers
4473   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4474     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4475     if (!CopyToReg)
4476       continue;
4477 
4478     Chain = DAG.getCopyToReg(
4479       Chain, DL,
4480       CopyToReg->getOperand(1),
4481       SDValue(Result, i - 1),
4482       SDValue());
4483 
4484     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4485   }
4486 
4487   // Remove the old intrinsic from the chain
4488   DAG.ReplaceAllUsesOfValueWith(
4489     SDValue(Intr, Intr->getNumValues() - 1),
4490     Intr->getOperand(0));
4491 
4492   return Chain;
4493 }
4494 
4495 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4496                                           SelectionDAG &DAG) const {
4497   MVT VT = Op.getSimpleValueType();
4498   SDLoc DL(Op);
4499   // Checking the depth
4500   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4501     return DAG.getConstant(0, DL, VT);
4502 
4503   MachineFunction &MF = DAG.getMachineFunction();
4504   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4505   // Check for kernel and shader functions
4506   if (Info->isEntryFunction())
4507     return DAG.getConstant(0, DL, VT);
4508 
4509   MachineFrameInfo &MFI = MF.getFrameInfo();
4510   // There is a call to @llvm.returnaddress in this function
4511   MFI.setReturnAddressIsTaken(true);
4512 
4513   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4514   // Get the return address reg and mark it as an implicit live-in
4515   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4516 
4517   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4518 }
4519 
4520 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4521                                             SDValue Op,
4522                                             const SDLoc &DL,
4523                                             EVT VT) const {
4524   return Op.getValueType().bitsLE(VT) ?
4525       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4526       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4527 }
4528 
4529 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4530   assert(Op.getValueType() == MVT::f16 &&
4531          "Do not know how to custom lower FP_ROUND for non-f16 type");
4532 
4533   SDValue Src = Op.getOperand(0);
4534   EVT SrcVT = Src.getValueType();
4535   if (SrcVT != MVT::f64)
4536     return Op;
4537 
4538   SDLoc DL(Op);
4539 
4540   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4541   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4542   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4543 }
4544 
4545 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4546                                                SelectionDAG &DAG) const {
4547   EVT VT = Op.getValueType();
4548   const MachineFunction &MF = DAG.getMachineFunction();
4549   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4550   bool IsIEEEMode = Info->getMode().IEEE;
4551 
4552   // FIXME: Assert during eslection that this is only selected for
4553   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4554   // mode functions, but this happens to be OK since it's only done in cases
4555   // where there is known no sNaN.
4556   if (IsIEEEMode)
4557     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4558 
4559   if (VT == MVT::v4f16)
4560     return splitBinaryVectorOp(Op, DAG);
4561   return Op;
4562 }
4563 
4564 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4565   SDLoc SL(Op);
4566   SDValue Chain = Op.getOperand(0);
4567 
4568   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4569       !Subtarget->isTrapHandlerEnabled())
4570     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4571 
4572   MachineFunction &MF = DAG.getMachineFunction();
4573   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4574   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4575   assert(UserSGPR != AMDGPU::NoRegister);
4576   SDValue QueuePtr = CreateLiveInRegister(
4577     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4578   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4579   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4580                                    QueuePtr, SDValue());
4581   SDValue Ops[] = {
4582     ToReg,
4583     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4584     SGPR01,
4585     ToReg.getValue(1)
4586   };
4587   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4588 }
4589 
4590 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4591   SDLoc SL(Op);
4592   SDValue Chain = Op.getOperand(0);
4593   MachineFunction &MF = DAG.getMachineFunction();
4594 
4595   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4596       !Subtarget->isTrapHandlerEnabled()) {
4597     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4598                                      "debugtrap handler not supported",
4599                                      Op.getDebugLoc(),
4600                                      DS_Warning);
4601     LLVMContext &Ctx = MF.getFunction().getContext();
4602     Ctx.diagnose(NoTrap);
4603     return Chain;
4604   }
4605 
4606   SDValue Ops[] = {
4607     Chain,
4608     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4609   };
4610   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4611 }
4612 
4613 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4614                                              SelectionDAG &DAG) const {
4615   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4616   if (Subtarget->hasApertureRegs()) {
4617     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4618         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4619         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4620     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4621         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4622         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4623     unsigned Encoding =
4624         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4625         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4626         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4627 
4628     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4629     SDValue ApertureReg = SDValue(
4630         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4631     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4632     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4633   }
4634 
4635   MachineFunction &MF = DAG.getMachineFunction();
4636   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4637   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4638   assert(UserSGPR != AMDGPU::NoRegister);
4639 
4640   SDValue QueuePtr = CreateLiveInRegister(
4641     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4642 
4643   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4644   // private_segment_aperture_base_hi.
4645   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4646 
4647   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4648 
4649   // TODO: Use custom target PseudoSourceValue.
4650   // TODO: We should use the value from the IR intrinsic call, but it might not
4651   // be available and how do we get it?
4652   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
4653   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4654                      MinAlign(64, StructOffset),
4655                      MachineMemOperand::MODereferenceable |
4656                          MachineMemOperand::MOInvariant);
4657 }
4658 
4659 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4660                                              SelectionDAG &DAG) const {
4661   SDLoc SL(Op);
4662   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4663 
4664   SDValue Src = ASC->getOperand(0);
4665   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4666 
4667   const AMDGPUTargetMachine &TM =
4668     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4669 
4670   // flat -> local/private
4671   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4672     unsigned DestAS = ASC->getDestAddressSpace();
4673 
4674     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4675         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4676       unsigned NullVal = TM.getNullPointerValue(DestAS);
4677       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4678       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4679       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4680 
4681       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4682                          NonNull, Ptr, SegmentNullPtr);
4683     }
4684   }
4685 
4686   // local/private -> flat
4687   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4688     unsigned SrcAS = ASC->getSrcAddressSpace();
4689 
4690     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4691         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4692       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4693       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4694 
4695       SDValue NonNull
4696         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4697 
4698       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4699       SDValue CvtPtr
4700         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4701 
4702       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4703                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4704                          FlatNullPtr);
4705     }
4706   }
4707 
4708   // global <-> flat are no-ops and never emitted.
4709 
4710   const MachineFunction &MF = DAG.getMachineFunction();
4711   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4712     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4713   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4714 
4715   return DAG.getUNDEF(ASC->getValueType(0));
4716 }
4717 
4718 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
4719 // the small vector and inserting them into the big vector. That is better than
4720 // the default expansion of doing it via a stack slot. Even though the use of
4721 // the stack slot would be optimized away afterwards, the stack slot itself
4722 // remains.
4723 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
4724                                                 SelectionDAG &DAG) const {
4725   SDValue Vec = Op.getOperand(0);
4726   SDValue Ins = Op.getOperand(1);
4727   SDValue Idx = Op.getOperand(2);
4728   EVT VecVT = Vec.getValueType();
4729   EVT InsVT = Ins.getValueType();
4730   EVT EltVT = VecVT.getVectorElementType();
4731   unsigned InsNumElts = InsVT.getVectorNumElements();
4732   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
4733   SDLoc SL(Op);
4734 
4735   for (unsigned I = 0; I != InsNumElts; ++I) {
4736     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
4737                               DAG.getConstant(I, SL, MVT::i32));
4738     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
4739                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
4740   }
4741   return Vec;
4742 }
4743 
4744 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4745                                                  SelectionDAG &DAG) const {
4746   SDValue Vec = Op.getOperand(0);
4747   SDValue InsVal = Op.getOperand(1);
4748   SDValue Idx = Op.getOperand(2);
4749   EVT VecVT = Vec.getValueType();
4750   EVT EltVT = VecVT.getVectorElementType();
4751   unsigned VecSize = VecVT.getSizeInBits();
4752   unsigned EltSize = EltVT.getSizeInBits();
4753 
4754 
4755   assert(VecSize <= 64);
4756 
4757   unsigned NumElts = VecVT.getVectorNumElements();
4758   SDLoc SL(Op);
4759   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4760 
4761   if (NumElts == 4 && EltSize == 16 && KIdx) {
4762     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4763 
4764     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4765                                  DAG.getConstant(0, SL, MVT::i32));
4766     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4767                                  DAG.getConstant(1, SL, MVT::i32));
4768 
4769     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4770     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4771 
4772     unsigned Idx = KIdx->getZExtValue();
4773     bool InsertLo = Idx < 2;
4774     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4775       InsertLo ? LoVec : HiVec,
4776       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4777       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4778 
4779     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4780 
4781     SDValue Concat = InsertLo ?
4782       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4783       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4784 
4785     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4786   }
4787 
4788   if (isa<ConstantSDNode>(Idx))
4789     return SDValue();
4790 
4791   MVT IntVT = MVT::getIntegerVT(VecSize);
4792 
4793   // Avoid stack access for dynamic indexing.
4794   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4795 
4796   // Create a congruent vector with the target value in each element so that
4797   // the required element can be masked and ORed into the target vector.
4798   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4799                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
4800 
4801   assert(isPowerOf2_32(EltSize));
4802   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4803 
4804   // Convert vector index to bit-index.
4805   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4806 
4807   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4808   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4809                             DAG.getConstant(0xffff, SL, IntVT),
4810                             ScaledIdx);
4811 
4812   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4813   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4814                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4815 
4816   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4817   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4818 }
4819 
4820 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4821                                                   SelectionDAG &DAG) const {
4822   SDLoc SL(Op);
4823 
4824   EVT ResultVT = Op.getValueType();
4825   SDValue Vec = Op.getOperand(0);
4826   SDValue Idx = Op.getOperand(1);
4827   EVT VecVT = Vec.getValueType();
4828   unsigned VecSize = VecVT.getSizeInBits();
4829   EVT EltVT = VecVT.getVectorElementType();
4830   assert(VecSize <= 64);
4831 
4832   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4833 
4834   // Make sure we do any optimizations that will make it easier to fold
4835   // source modifiers before obscuring it with bit operations.
4836 
4837   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4838   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4839     return Combined;
4840 
4841   unsigned EltSize = EltVT.getSizeInBits();
4842   assert(isPowerOf2_32(EltSize));
4843 
4844   MVT IntVT = MVT::getIntegerVT(VecSize);
4845   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4846 
4847   // Convert vector index to bit-index (* EltSize)
4848   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4849 
4850   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4851   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4852 
4853   if (ResultVT == MVT::f16) {
4854     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4855     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4856   }
4857 
4858   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4859 }
4860 
4861 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
4862   assert(Elt % 2 == 0);
4863   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
4864 }
4865 
4866 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
4867                                               SelectionDAG &DAG) const {
4868   SDLoc SL(Op);
4869   EVT ResultVT = Op.getValueType();
4870   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
4871 
4872   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
4873   EVT EltVT = PackVT.getVectorElementType();
4874   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
4875 
4876   // vector_shuffle <0,1,6,7> lhs, rhs
4877   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
4878   //
4879   // vector_shuffle <6,7,2,3> lhs, rhs
4880   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
4881   //
4882   // vector_shuffle <6,7,0,1> lhs, rhs
4883   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
4884 
4885   // Avoid scalarizing when both halves are reading from consecutive elements.
4886   SmallVector<SDValue, 4> Pieces;
4887   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
4888     if (elementPairIsContiguous(SVN->getMask(), I)) {
4889       const int Idx = SVN->getMaskElt(I);
4890       int VecIdx = Idx < SrcNumElts ? 0 : 1;
4891       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
4892       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
4893                                     PackVT, SVN->getOperand(VecIdx),
4894                                     DAG.getConstant(EltIdx, SL, MVT::i32));
4895       Pieces.push_back(SubVec);
4896     } else {
4897       const int Idx0 = SVN->getMaskElt(I);
4898       const int Idx1 = SVN->getMaskElt(I + 1);
4899       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
4900       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
4901       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
4902       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
4903 
4904       SDValue Vec0 = SVN->getOperand(VecIdx0);
4905       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4906                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
4907 
4908       SDValue Vec1 = SVN->getOperand(VecIdx1);
4909       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
4910                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
4911       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
4912     }
4913   }
4914 
4915   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
4916 }
4917 
4918 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4919                                             SelectionDAG &DAG) const {
4920   SDLoc SL(Op);
4921   EVT VT = Op.getValueType();
4922 
4923   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4924     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4925 
4926     // Turn into pair of packed build_vectors.
4927     // TODO: Special case for constants that can be materialized with s_mov_b64.
4928     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4929                                     { Op.getOperand(0), Op.getOperand(1) });
4930     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4931                                     { Op.getOperand(2), Op.getOperand(3) });
4932 
4933     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4934     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4935 
4936     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4937     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4938   }
4939 
4940   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4941   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
4942 
4943   SDValue Lo = Op.getOperand(0);
4944   SDValue Hi = Op.getOperand(1);
4945 
4946   // Avoid adding defined bits with the zero_extend.
4947   if (Hi.isUndef()) {
4948     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4949     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
4950     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
4951   }
4952 
4953   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4954   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4955 
4956   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4957                               DAG.getConstant(16, SL, MVT::i32));
4958   if (Lo.isUndef())
4959     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
4960 
4961   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4962   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4963 
4964   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4965   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4966 }
4967 
4968 bool
4969 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4970   // We can fold offsets for anything that doesn't require a GOT relocation.
4971   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4972           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4973           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4974          !shouldEmitGOTReloc(GA->getGlobal());
4975 }
4976 
4977 static SDValue
4978 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4979                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
4980                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
4981   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4982   // lowered to the following code sequence:
4983   //
4984   // For constant address space:
4985   //   s_getpc_b64 s[0:1]
4986   //   s_add_u32 s0, s0, $symbol
4987   //   s_addc_u32 s1, s1, 0
4988   //
4989   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4990   //   a fixup or relocation is emitted to replace $symbol with a literal
4991   //   constant, which is a pc-relative offset from the encoding of the $symbol
4992   //   operand to the global variable.
4993   //
4994   // For global address space:
4995   //   s_getpc_b64 s[0:1]
4996   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4997   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4998   //
4999   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5000   //   fixups or relocations are emitted to replace $symbol@*@lo and
5001   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5002   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5003   //   operand to the global variable.
5004   //
5005   // What we want here is an offset from the value returned by s_getpc
5006   // (which is the address of the s_add_u32 instruction) to the global
5007   // variable, but since the encoding of $symbol starts 4 bytes after the start
5008   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5009   // small. This requires us to add 4 to the global variable offset in order to
5010   // compute the correct address.
5011   SDValue PtrLo =
5012       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5013   SDValue PtrHi;
5014   if (GAFlags == SIInstrInfo::MO_NONE) {
5015     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5016   } else {
5017     PtrHi =
5018         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5019   }
5020   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5021 }
5022 
5023 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5024                                              SDValue Op,
5025                                              SelectionDAG &DAG) const {
5026   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5027   const GlobalValue *GV = GSD->getGlobal();
5028   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5029        shouldUseLDSConstAddress(GV)) ||
5030       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5031       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5032     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5033 
5034   SDLoc DL(GSD);
5035   EVT PtrVT = Op.getValueType();
5036 
5037   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5038     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5039                                             SIInstrInfo::MO_ABS32_LO);
5040     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5041   }
5042 
5043   if (shouldEmitFixup(GV))
5044     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5045   else if (shouldEmitPCReloc(GV))
5046     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5047                                    SIInstrInfo::MO_REL32);
5048 
5049   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5050                                             SIInstrInfo::MO_GOTPCREL32);
5051 
5052   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5053   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5054   const DataLayout &DataLayout = DAG.getDataLayout();
5055   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5056   MachinePointerInfo PtrInfo
5057     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5058 
5059   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5060                      MachineMemOperand::MODereferenceable |
5061                          MachineMemOperand::MOInvariant);
5062 }
5063 
5064 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5065                                    const SDLoc &DL, SDValue V) const {
5066   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5067   // the destination register.
5068   //
5069   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5070   // so we will end up with redundant moves to m0.
5071   //
5072   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5073 
5074   // A Null SDValue creates a glue result.
5075   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5076                                   V, Chain);
5077   return SDValue(M0, 0);
5078 }
5079 
5080 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5081                                                  SDValue Op,
5082                                                  MVT VT,
5083                                                  unsigned Offset) const {
5084   SDLoc SL(Op);
5085   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5086                                            DAG.getEntryNode(), Offset, 4, false);
5087   // The local size values will have the hi 16-bits as zero.
5088   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5089                      DAG.getValueType(VT));
5090 }
5091 
5092 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5093                                         EVT VT) {
5094   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5095                                       "non-hsa intrinsic with hsa target",
5096                                       DL.getDebugLoc());
5097   DAG.getContext()->diagnose(BadIntrin);
5098   return DAG.getUNDEF(VT);
5099 }
5100 
5101 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5102                                          EVT VT) {
5103   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5104                                       "intrinsic not supported on subtarget",
5105                                       DL.getDebugLoc());
5106   DAG.getContext()->diagnose(BadIntrin);
5107   return DAG.getUNDEF(VT);
5108 }
5109 
5110 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5111                                     ArrayRef<SDValue> Elts) {
5112   assert(!Elts.empty());
5113   MVT Type;
5114   unsigned NumElts;
5115 
5116   if (Elts.size() == 1) {
5117     Type = MVT::f32;
5118     NumElts = 1;
5119   } else if (Elts.size() == 2) {
5120     Type = MVT::v2f32;
5121     NumElts = 2;
5122   } else if (Elts.size() == 3) {
5123     Type = MVT::v3f32;
5124     NumElts = 3;
5125   } else if (Elts.size() <= 4) {
5126     Type = MVT::v4f32;
5127     NumElts = 4;
5128   } else if (Elts.size() <= 8) {
5129     Type = MVT::v8f32;
5130     NumElts = 8;
5131   } else {
5132     assert(Elts.size() <= 16);
5133     Type = MVT::v16f32;
5134     NumElts = 16;
5135   }
5136 
5137   SmallVector<SDValue, 16> VecElts(NumElts);
5138   for (unsigned i = 0; i < Elts.size(); ++i) {
5139     SDValue Elt = Elts[i];
5140     if (Elt.getValueType() != MVT::f32)
5141       Elt = DAG.getBitcast(MVT::f32, Elt);
5142     VecElts[i] = Elt;
5143   }
5144   for (unsigned i = Elts.size(); i < NumElts; ++i)
5145     VecElts[i] = DAG.getUNDEF(MVT::f32);
5146 
5147   if (NumElts == 1)
5148     return VecElts[0];
5149   return DAG.getBuildVector(Type, DL, VecElts);
5150 }
5151 
5152 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5153                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5154   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5155 
5156   uint64_t Value = CachePolicyConst->getZExtValue();
5157   SDLoc DL(CachePolicy);
5158   if (GLC) {
5159     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5160     Value &= ~(uint64_t)0x1;
5161   }
5162   if (SLC) {
5163     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5164     Value &= ~(uint64_t)0x2;
5165   }
5166   if (DLC) {
5167     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5168     Value &= ~(uint64_t)0x4;
5169   }
5170 
5171   return Value == 0;
5172 }
5173 
5174 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5175                               SDValue Src, int ExtraElts) {
5176   EVT SrcVT = Src.getValueType();
5177 
5178   SmallVector<SDValue, 8> Elts;
5179 
5180   if (SrcVT.isVector())
5181     DAG.ExtractVectorElements(Src, Elts);
5182   else
5183     Elts.push_back(Src);
5184 
5185   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5186   while (ExtraElts--)
5187     Elts.push_back(Undef);
5188 
5189   return DAG.getBuildVector(CastVT, DL, Elts);
5190 }
5191 
5192 // Re-construct the required return value for a image load intrinsic.
5193 // This is more complicated due to the optional use TexFailCtrl which means the required
5194 // return type is an aggregate
5195 static SDValue constructRetValue(SelectionDAG &DAG,
5196                                  MachineSDNode *Result,
5197                                  ArrayRef<EVT> ResultTypes,
5198                                  bool IsTexFail, bool Unpacked, bool IsD16,
5199                                  int DMaskPop, int NumVDataDwords,
5200                                  const SDLoc &DL, LLVMContext &Context) {
5201   // Determine the required return type. This is the same regardless of IsTexFail flag
5202   EVT ReqRetVT = ResultTypes[0];
5203   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5204   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5205     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5206 
5207   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5208     DMaskPop : (DMaskPop + 1) / 2;
5209 
5210   MVT DataDwordVT = NumDataDwords == 1 ?
5211     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5212 
5213   MVT MaskPopVT = MaskPopDwords == 1 ?
5214     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5215 
5216   SDValue Data(Result, 0);
5217   SDValue TexFail;
5218 
5219   if (IsTexFail) {
5220     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5221     if (MaskPopVT.isVector()) {
5222       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5223                          SDValue(Result, 0), ZeroIdx);
5224     } else {
5225       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5226                          SDValue(Result, 0), ZeroIdx);
5227     }
5228 
5229     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5230                           SDValue(Result, 0),
5231                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5232   }
5233 
5234   if (DataDwordVT.isVector())
5235     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5236                           NumDataDwords - MaskPopDwords);
5237 
5238   if (IsD16)
5239     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5240 
5241   if (!ReqRetVT.isVector())
5242     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5243 
5244   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5245 
5246   if (TexFail)
5247     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5248 
5249   if (Result->getNumValues() == 1)
5250     return Data;
5251 
5252   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5253 }
5254 
5255 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5256                          SDValue *LWE, bool &IsTexFail) {
5257   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5258 
5259   uint64_t Value = TexFailCtrlConst->getZExtValue();
5260   if (Value) {
5261     IsTexFail = true;
5262   }
5263 
5264   SDLoc DL(TexFailCtrlConst);
5265   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5266   Value &= ~(uint64_t)0x1;
5267   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5268   Value &= ~(uint64_t)0x2;
5269 
5270   return Value == 0;
5271 }
5272 
5273 SDValue SITargetLowering::lowerImage(SDValue Op,
5274                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5275                                      SelectionDAG &DAG) const {
5276   SDLoc DL(Op);
5277   MachineFunction &MF = DAG.getMachineFunction();
5278   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5279   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5280       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5281   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5282   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5283       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5284   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5285       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5286   unsigned IntrOpcode = Intr->BaseOpcode;
5287   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5288 
5289   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5290   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5291   bool IsD16 = false;
5292   bool IsA16 = false;
5293   SDValue VData;
5294   int NumVDataDwords;
5295   bool AdjustRetType = false;
5296 
5297   unsigned AddrIdx; // Index of first address argument
5298   unsigned DMask;
5299   unsigned DMaskLanes = 0;
5300 
5301   if (BaseOpcode->Atomic) {
5302     VData = Op.getOperand(2);
5303 
5304     bool Is64Bit = VData.getValueType() == MVT::i64;
5305     if (BaseOpcode->AtomicX2) {
5306       SDValue VData2 = Op.getOperand(3);
5307       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5308                                  {VData, VData2});
5309       if (Is64Bit)
5310         VData = DAG.getBitcast(MVT::v4i32, VData);
5311 
5312       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5313       DMask = Is64Bit ? 0xf : 0x3;
5314       NumVDataDwords = Is64Bit ? 4 : 2;
5315       AddrIdx = 4;
5316     } else {
5317       DMask = Is64Bit ? 0x3 : 0x1;
5318       NumVDataDwords = Is64Bit ? 2 : 1;
5319       AddrIdx = 3;
5320     }
5321   } else {
5322     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5323     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5324     DMask = DMaskConst->getZExtValue();
5325     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5326 
5327     if (BaseOpcode->Store) {
5328       VData = Op.getOperand(2);
5329 
5330       MVT StoreVT = VData.getSimpleValueType();
5331       if (StoreVT.getScalarType() == MVT::f16) {
5332         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5333           return Op; // D16 is unsupported for this instruction
5334 
5335         IsD16 = true;
5336         VData = handleD16VData(VData, DAG);
5337       }
5338 
5339       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5340     } else {
5341       // Work out the num dwords based on the dmask popcount and underlying type
5342       // and whether packing is supported.
5343       MVT LoadVT = ResultTypes[0].getSimpleVT();
5344       if (LoadVT.getScalarType() == MVT::f16) {
5345         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5346           return Op; // D16 is unsupported for this instruction
5347 
5348         IsD16 = true;
5349       }
5350 
5351       // Confirm that the return type is large enough for the dmask specified
5352       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5353           (!LoadVT.isVector() && DMaskLanes > 1))
5354           return Op;
5355 
5356       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5357         NumVDataDwords = (DMaskLanes + 1) / 2;
5358       else
5359         NumVDataDwords = DMaskLanes;
5360 
5361       AdjustRetType = true;
5362     }
5363 
5364     AddrIdx = DMaskIdx + 1;
5365   }
5366 
5367   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5368   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5369   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5370   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5371                        NumCoords + NumLCM;
5372   unsigned NumMIVAddrs = NumVAddrs;
5373 
5374   SmallVector<SDValue, 4> VAddrs;
5375 
5376   // Optimize _L to _LZ when _L is zero
5377   if (LZMappingInfo) {
5378     if (auto ConstantLod =
5379          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5380       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5381         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5382         NumMIVAddrs--;               // remove 'lod'
5383       }
5384     }
5385   }
5386 
5387   // Optimize _mip away, when 'lod' is zero
5388   if (MIPMappingInfo) {
5389     if (auto ConstantLod =
5390          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5391       if (ConstantLod->isNullValue()) {
5392         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5393         NumMIVAddrs--;               // remove 'lod'
5394       }
5395     }
5396   }
5397 
5398   // Check for 16 bit addresses and pack if true.
5399   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5400   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5401   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5402   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) {
5403     // Illegal to use a16 images
5404     if (!ST->hasFeature(AMDGPU::FeatureR128A16))
5405       return Op;
5406 
5407     IsA16 = true;
5408     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5409     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5410       SDValue AddrLo;
5411       // Push back extra arguments.
5412       if (i < DimIdx) {
5413         AddrLo = Op.getOperand(i);
5414       } else {
5415         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5416         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5417         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5418             ((NumGradients / 2) % 2 == 1 &&
5419             (i == DimIdx + (NumGradients / 2) - 1 ||
5420              i == DimIdx + NumGradients - 1))) {
5421           AddrLo = Op.getOperand(i);
5422           if (AddrLo.getValueType() != MVT::i16)
5423             AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i));
5424           AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo);
5425         } else {
5426           AddrLo = DAG.getBuildVector(VectorVT, DL,
5427                                       {Op.getOperand(i), Op.getOperand(i + 1)});
5428           i++;
5429         }
5430         AddrLo = DAG.getBitcast(MVT::f32, AddrLo);
5431       }
5432       VAddrs.push_back(AddrLo);
5433     }
5434   } else {
5435     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5436       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5437   }
5438 
5439   // If the register allocator cannot place the address registers contiguously
5440   // without introducing moves, then using the non-sequential address encoding
5441   // is always preferable, since it saves VALU instructions and is usually a
5442   // wash in terms of code size or even better.
5443   //
5444   // However, we currently have no way of hinting to the register allocator that
5445   // MIMG addresses should be placed contiguously when it is possible to do so,
5446   // so force non-NSA for the common 2-address case as a heuristic.
5447   //
5448   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5449   // allocation when possible.
5450   bool UseNSA =
5451       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5452   SDValue VAddr;
5453   if (!UseNSA)
5454     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5455 
5456   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5457   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5458   unsigned CtrlIdx; // Index of texfailctrl argument
5459   SDValue Unorm;
5460   if (!BaseOpcode->Sampler) {
5461     Unorm = True;
5462     CtrlIdx = AddrIdx + NumVAddrs + 1;
5463   } else {
5464     auto UnormConst =
5465         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5466 
5467     Unorm = UnormConst->getZExtValue() ? True : False;
5468     CtrlIdx = AddrIdx + NumVAddrs + 3;
5469   }
5470 
5471   SDValue TFE;
5472   SDValue LWE;
5473   SDValue TexFail = Op.getOperand(CtrlIdx);
5474   bool IsTexFail = false;
5475   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5476     return Op;
5477 
5478   if (IsTexFail) {
5479     if (!DMaskLanes) {
5480       // Expecting to get an error flag since TFC is on - and dmask is 0
5481       // Force dmask to be at least 1 otherwise the instruction will fail
5482       DMask = 0x1;
5483       DMaskLanes = 1;
5484       NumVDataDwords = 1;
5485     }
5486     NumVDataDwords += 1;
5487     AdjustRetType = true;
5488   }
5489 
5490   // Has something earlier tagged that the return type needs adjusting
5491   // This happens if the instruction is a load or has set TexFailCtrl flags
5492   if (AdjustRetType) {
5493     // NumVDataDwords reflects the true number of dwords required in the return type
5494     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5495       // This is a no-op load. This can be eliminated
5496       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5497       if (isa<MemSDNode>(Op))
5498         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5499       return Undef;
5500     }
5501 
5502     EVT NewVT = NumVDataDwords > 1 ?
5503                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
5504                 : MVT::i32;
5505 
5506     ResultTypes[0] = NewVT;
5507     if (ResultTypes.size() == 3) {
5508       // Original result was aggregate type used for TexFailCtrl results
5509       // The actual instruction returns as a vector type which has now been
5510       // created. Remove the aggregate result.
5511       ResultTypes.erase(&ResultTypes[1]);
5512     }
5513   }
5514 
5515   SDValue GLC;
5516   SDValue SLC;
5517   SDValue DLC;
5518   if (BaseOpcode->Atomic) {
5519     GLC = True; // TODO no-return optimization
5520     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5521                           IsGFX10 ? &DLC : nullptr))
5522       return Op;
5523   } else {
5524     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5525                           IsGFX10 ? &DLC : nullptr))
5526       return Op;
5527   }
5528 
5529   SmallVector<SDValue, 26> Ops;
5530   if (BaseOpcode->Store || BaseOpcode->Atomic)
5531     Ops.push_back(VData); // vdata
5532   if (UseNSA) {
5533     for (const SDValue &Addr : VAddrs)
5534       Ops.push_back(Addr);
5535   } else {
5536     Ops.push_back(VAddr);
5537   }
5538   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5539   if (BaseOpcode->Sampler)
5540     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5541   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5542   if (IsGFX10)
5543     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5544   Ops.push_back(Unorm);
5545   if (IsGFX10)
5546     Ops.push_back(DLC);
5547   Ops.push_back(GLC);
5548   Ops.push_back(SLC);
5549   Ops.push_back(IsA16 &&  // a16 or r128
5550                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5551   Ops.push_back(TFE); // tfe
5552   Ops.push_back(LWE); // lwe
5553   if (!IsGFX10)
5554     Ops.push_back(DimInfo->DA ? True : False);
5555   if (BaseOpcode->HasD16)
5556     Ops.push_back(IsD16 ? True : False);
5557   if (isa<MemSDNode>(Op))
5558     Ops.push_back(Op.getOperand(0)); // chain
5559 
5560   int NumVAddrDwords =
5561       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5562   int Opcode = -1;
5563 
5564   if (IsGFX10) {
5565     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5566                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5567                                           : AMDGPU::MIMGEncGfx10Default,
5568                                    NumVDataDwords, NumVAddrDwords);
5569   } else {
5570     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5571       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5572                                      NumVDataDwords, NumVAddrDwords);
5573     if (Opcode == -1)
5574       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5575                                      NumVDataDwords, NumVAddrDwords);
5576   }
5577   assert(Opcode != -1);
5578 
5579   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5580   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5581     MachineMemOperand *MemRef = MemOp->getMemOperand();
5582     DAG.setNodeMemRefs(NewNode, {MemRef});
5583   }
5584 
5585   if (BaseOpcode->AtomicX2) {
5586     SmallVector<SDValue, 1> Elt;
5587     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5588     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5589   } else if (!BaseOpcode->Store) {
5590     return constructRetValue(DAG, NewNode,
5591                              OrigResultTypes, IsTexFail,
5592                              Subtarget->hasUnpackedD16VMem(), IsD16,
5593                              DMaskLanes, NumVDataDwords, DL,
5594                              *DAG.getContext());
5595   }
5596 
5597   return SDValue(NewNode, 0);
5598 }
5599 
5600 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5601                                        SDValue Offset, SDValue CachePolicy,
5602                                        SelectionDAG &DAG) const {
5603   MachineFunction &MF = DAG.getMachineFunction();
5604 
5605   const DataLayout &DataLayout = DAG.getDataLayout();
5606   unsigned Align =
5607       DataLayout.getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5608 
5609   MachineMemOperand *MMO = MF.getMachineMemOperand(
5610       MachinePointerInfo(),
5611       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5612           MachineMemOperand::MOInvariant,
5613       VT.getStoreSize(), Align);
5614 
5615   if (!Offset->isDivergent()) {
5616     SDValue Ops[] = {
5617         Rsrc,
5618         Offset, // Offset
5619         CachePolicy
5620     };
5621 
5622     // Widen vec3 load to vec4.
5623     if (VT.isVector() && VT.getVectorNumElements() == 3) {
5624       EVT WidenedVT =
5625           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
5626       auto WidenedOp = DAG.getMemIntrinsicNode(
5627           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
5628           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
5629       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
5630                                    DAG.getVectorIdxConstant(0, DL));
5631       return Subvector;
5632     }
5633 
5634     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5635                                    DAG.getVTList(VT), Ops, VT, MMO);
5636   }
5637 
5638   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5639   // assume that the buffer is unswizzled.
5640   SmallVector<SDValue, 4> Loads;
5641   unsigned NumLoads = 1;
5642   MVT LoadVT = VT.getSimpleVT();
5643   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5644   assert((LoadVT.getScalarType() == MVT::i32 ||
5645           LoadVT.getScalarType() == MVT::f32));
5646 
5647   if (NumElts == 8 || NumElts == 16) {
5648     NumLoads = NumElts / 4;
5649     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
5650   }
5651 
5652   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5653   SDValue Ops[] = {
5654       DAG.getEntryNode(),                               // Chain
5655       Rsrc,                                             // rsrc
5656       DAG.getConstant(0, DL, MVT::i32),                 // vindex
5657       {},                                               // voffset
5658       {},                                               // soffset
5659       {},                                               // offset
5660       CachePolicy,                                      // cachepolicy
5661       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
5662   };
5663 
5664   // Use the alignment to ensure that the required offsets will fit into the
5665   // immediate offsets.
5666   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5667 
5668   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5669   for (unsigned i = 0; i < NumLoads; ++i) {
5670     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
5671     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
5672                                         LoadVT, MMO, DAG));
5673   }
5674 
5675   if (NumElts == 8 || NumElts == 16)
5676     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5677 
5678   return Loads[0];
5679 }
5680 
5681 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5682                                                   SelectionDAG &DAG) const {
5683   MachineFunction &MF = DAG.getMachineFunction();
5684   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5685 
5686   EVT VT = Op.getValueType();
5687   SDLoc DL(Op);
5688   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5689 
5690   // TODO: Should this propagate fast-math-flags?
5691 
5692   switch (IntrinsicID) {
5693   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5694     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5695       return emitNonHSAIntrinsicError(DAG, DL, VT);
5696     return getPreloadedValue(DAG, *MFI, VT,
5697                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5698   }
5699   case Intrinsic::amdgcn_dispatch_ptr:
5700   case Intrinsic::amdgcn_queue_ptr: {
5701     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5702       DiagnosticInfoUnsupported BadIntrin(
5703           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5704           DL.getDebugLoc());
5705       DAG.getContext()->diagnose(BadIntrin);
5706       return DAG.getUNDEF(VT);
5707     }
5708 
5709     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5710       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5711     return getPreloadedValue(DAG, *MFI, VT, RegID);
5712   }
5713   case Intrinsic::amdgcn_implicitarg_ptr: {
5714     if (MFI->isEntryFunction())
5715       return getImplicitArgPtr(DAG, DL);
5716     return getPreloadedValue(DAG, *MFI, VT,
5717                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5718   }
5719   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5720     return getPreloadedValue(DAG, *MFI, VT,
5721                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5722   }
5723   case Intrinsic::amdgcn_dispatch_id: {
5724     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5725   }
5726   case Intrinsic::amdgcn_rcp:
5727     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5728   case Intrinsic::amdgcn_rsq:
5729     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5730   case Intrinsic::amdgcn_rsq_legacy:
5731     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5732       return emitRemovedIntrinsicError(DAG, DL, VT);
5733 
5734     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5735   case Intrinsic::amdgcn_rcp_legacy:
5736     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5737       return emitRemovedIntrinsicError(DAG, DL, VT);
5738     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5739   case Intrinsic::amdgcn_rsq_clamp: {
5740     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5741       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5742 
5743     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5744     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5745     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5746 
5747     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5748     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5749                               DAG.getConstantFP(Max, DL, VT));
5750     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5751                        DAG.getConstantFP(Min, DL, VT));
5752   }
5753   case Intrinsic::r600_read_ngroups_x:
5754     if (Subtarget->isAmdHsaOS())
5755       return emitNonHSAIntrinsicError(DAG, DL, VT);
5756 
5757     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5758                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
5759   case Intrinsic::r600_read_ngroups_y:
5760     if (Subtarget->isAmdHsaOS())
5761       return emitNonHSAIntrinsicError(DAG, DL, VT);
5762 
5763     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5764                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5765   case Intrinsic::r600_read_ngroups_z:
5766     if (Subtarget->isAmdHsaOS())
5767       return emitNonHSAIntrinsicError(DAG, DL, VT);
5768 
5769     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5770                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5771   case Intrinsic::r600_read_global_size_x:
5772     if (Subtarget->isAmdHsaOS())
5773       return emitNonHSAIntrinsicError(DAG, DL, VT);
5774 
5775     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5776                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5777   case Intrinsic::r600_read_global_size_y:
5778     if (Subtarget->isAmdHsaOS())
5779       return emitNonHSAIntrinsicError(DAG, DL, VT);
5780 
5781     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5782                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5783   case Intrinsic::r600_read_global_size_z:
5784     if (Subtarget->isAmdHsaOS())
5785       return emitNonHSAIntrinsicError(DAG, DL, VT);
5786 
5787     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5788                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5789   case Intrinsic::r600_read_local_size_x:
5790     if (Subtarget->isAmdHsaOS())
5791       return emitNonHSAIntrinsicError(DAG, DL, VT);
5792 
5793     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5794                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
5795   case Intrinsic::r600_read_local_size_y:
5796     if (Subtarget->isAmdHsaOS())
5797       return emitNonHSAIntrinsicError(DAG, DL, VT);
5798 
5799     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5800                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
5801   case Intrinsic::r600_read_local_size_z:
5802     if (Subtarget->isAmdHsaOS())
5803       return emitNonHSAIntrinsicError(DAG, DL, VT);
5804 
5805     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5806                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
5807   case Intrinsic::amdgcn_workgroup_id_x:
5808   case Intrinsic::r600_read_tgid_x:
5809     return getPreloadedValue(DAG, *MFI, VT,
5810                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5811   case Intrinsic::amdgcn_workgroup_id_y:
5812   case Intrinsic::r600_read_tgid_y:
5813     return getPreloadedValue(DAG, *MFI, VT,
5814                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5815   case Intrinsic::amdgcn_workgroup_id_z:
5816   case Intrinsic::r600_read_tgid_z:
5817     return getPreloadedValue(DAG, *MFI, VT,
5818                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5819   case Intrinsic::amdgcn_workitem_id_x:
5820   case Intrinsic::r600_read_tidig_x:
5821     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5822                           SDLoc(DAG.getEntryNode()),
5823                           MFI->getArgInfo().WorkItemIDX);
5824   case Intrinsic::amdgcn_workitem_id_y:
5825   case Intrinsic::r600_read_tidig_y:
5826     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5827                           SDLoc(DAG.getEntryNode()),
5828                           MFI->getArgInfo().WorkItemIDY);
5829   case Intrinsic::amdgcn_workitem_id_z:
5830   case Intrinsic::r600_read_tidig_z:
5831     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5832                           SDLoc(DAG.getEntryNode()),
5833                           MFI->getArgInfo().WorkItemIDZ);
5834   case Intrinsic::amdgcn_wavefrontsize:
5835     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
5836                            SDLoc(Op), MVT::i32);
5837   case Intrinsic::amdgcn_s_buffer_load: {
5838     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5839     SDValue GLC;
5840     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5841     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5842                           IsGFX10 ? &DLC : nullptr))
5843       return Op;
5844     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5845                         DAG);
5846   }
5847   case Intrinsic::amdgcn_fdiv_fast:
5848     return lowerFDIV_FAST(Op, DAG);
5849   case Intrinsic::amdgcn_sin:
5850     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5851 
5852   case Intrinsic::amdgcn_cos:
5853     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5854 
5855   case Intrinsic::amdgcn_mul_u24:
5856     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5857   case Intrinsic::amdgcn_mul_i24:
5858     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
5859 
5860   case Intrinsic::amdgcn_log_clamp: {
5861     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5862       return SDValue();
5863 
5864     DiagnosticInfoUnsupported BadIntrin(
5865       MF.getFunction(), "intrinsic not supported on subtarget",
5866       DL.getDebugLoc());
5867       DAG.getContext()->diagnose(BadIntrin);
5868       return DAG.getUNDEF(VT);
5869   }
5870   case Intrinsic::amdgcn_ldexp:
5871     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5872                        Op.getOperand(1), Op.getOperand(2));
5873 
5874   case Intrinsic::amdgcn_fract:
5875     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5876 
5877   case Intrinsic::amdgcn_class:
5878     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5879                        Op.getOperand(1), Op.getOperand(2));
5880   case Intrinsic::amdgcn_div_fmas:
5881     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5882                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5883                        Op.getOperand(4));
5884 
5885   case Intrinsic::amdgcn_div_fixup:
5886     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5887                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5888 
5889   case Intrinsic::amdgcn_trig_preop:
5890     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5891                        Op.getOperand(1), Op.getOperand(2));
5892   case Intrinsic::amdgcn_div_scale: {
5893     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5894 
5895     // Translate to the operands expected by the machine instruction. The
5896     // first parameter must be the same as the first instruction.
5897     SDValue Numerator = Op.getOperand(1);
5898     SDValue Denominator = Op.getOperand(2);
5899 
5900     // Note this order is opposite of the machine instruction's operations,
5901     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
5902     // intrinsic has the numerator as the first operand to match a normal
5903     // division operation.
5904 
5905     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
5906 
5907     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
5908                        Denominator, Numerator);
5909   }
5910   case Intrinsic::amdgcn_icmp: {
5911     // There is a Pat that handles this variant, so return it as-is.
5912     if (Op.getOperand(1).getValueType() == MVT::i1 &&
5913         Op.getConstantOperandVal(2) == 0 &&
5914         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
5915       return Op;
5916     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
5917   }
5918   case Intrinsic::amdgcn_fcmp: {
5919     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
5920   }
5921   case Intrinsic::amdgcn_fmed3:
5922     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
5923                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5924   case Intrinsic::amdgcn_fdot2:
5925     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
5926                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5927                        Op.getOperand(4));
5928   case Intrinsic::amdgcn_fmul_legacy:
5929     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
5930                        Op.getOperand(1), Op.getOperand(2));
5931   case Intrinsic::amdgcn_sffbh:
5932     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
5933   case Intrinsic::amdgcn_sbfe:
5934     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
5935                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5936   case Intrinsic::amdgcn_ubfe:
5937     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
5938                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5939   case Intrinsic::amdgcn_cvt_pkrtz:
5940   case Intrinsic::amdgcn_cvt_pknorm_i16:
5941   case Intrinsic::amdgcn_cvt_pknorm_u16:
5942   case Intrinsic::amdgcn_cvt_pk_i16:
5943   case Intrinsic::amdgcn_cvt_pk_u16: {
5944     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
5945     EVT VT = Op.getValueType();
5946     unsigned Opcode;
5947 
5948     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
5949       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
5950     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
5951       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5952     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
5953       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5954     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
5955       Opcode = AMDGPUISD::CVT_PK_I16_I32;
5956     else
5957       Opcode = AMDGPUISD::CVT_PK_U16_U32;
5958 
5959     if (isTypeLegal(VT))
5960       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
5961 
5962     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
5963                                Op.getOperand(1), Op.getOperand(2));
5964     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
5965   }
5966   case Intrinsic::amdgcn_fmad_ftz:
5967     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
5968                        Op.getOperand(2), Op.getOperand(3));
5969 
5970   case Intrinsic::amdgcn_if_break:
5971     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
5972                                       Op->getOperand(1), Op->getOperand(2)), 0);
5973 
5974   case Intrinsic::amdgcn_groupstaticsize: {
5975     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
5976     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
5977       return Op;
5978 
5979     const Module *M = MF.getFunction().getParent();
5980     const GlobalValue *GV =
5981         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
5982     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
5983                                             SIInstrInfo::MO_ABS32_LO);
5984     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
5985   }
5986   case Intrinsic::amdgcn_is_shared:
5987   case Intrinsic::amdgcn_is_private: {
5988     SDLoc SL(Op);
5989     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
5990       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
5991     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
5992     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
5993                                  Op.getOperand(1));
5994 
5995     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
5996                                 DAG.getConstant(1, SL, MVT::i32));
5997     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
5998   }
5999   default:
6000     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6001             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6002       return lowerImage(Op, ImageDimIntr, DAG);
6003 
6004     return Op;
6005   }
6006 }
6007 
6008 // This function computes an appropriate offset to pass to
6009 // MachineMemOperand::setOffset() based on the offset inputs to
6010 // an intrinsic.  If any of the offsets are non-contstant or
6011 // if VIndex is non-zero then this function returns 0.  Otherwise,
6012 // it returns the sum of VOffset, SOffset, and Offset.
6013 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6014                                       SDValue SOffset,
6015                                       SDValue Offset,
6016                                       SDValue VIndex = SDValue()) {
6017 
6018   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6019       !isa<ConstantSDNode>(Offset))
6020     return 0;
6021 
6022   if (VIndex) {
6023     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6024       return 0;
6025   }
6026 
6027   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6028          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6029          cast<ConstantSDNode>(Offset)->getSExtValue();
6030 }
6031 
6032 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6033   switch (MF.getFunction().getCallingConv()) {
6034   case CallingConv::AMDGPU_PS:
6035     return 1;
6036   case CallingConv::AMDGPU_VS:
6037     return 2;
6038   case CallingConv::AMDGPU_GS:
6039     return 3;
6040   case CallingConv::AMDGPU_HS:
6041   case CallingConv::AMDGPU_LS:
6042   case CallingConv::AMDGPU_ES:
6043     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6044   case CallingConv::AMDGPU_CS:
6045   case CallingConv::AMDGPU_KERNEL:
6046   case CallingConv::C:
6047   case CallingConv::Fast:
6048   default:
6049     // Assume other calling conventions are various compute callable functions
6050     return 0;
6051   }
6052 }
6053 
6054 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6055                                                  SelectionDAG &DAG) const {
6056   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6057   SDLoc DL(Op);
6058 
6059   switch (IntrID) {
6060   case Intrinsic::amdgcn_ds_ordered_add:
6061   case Intrinsic::amdgcn_ds_ordered_swap: {
6062     MemSDNode *M = cast<MemSDNode>(Op);
6063     SDValue Chain = M->getOperand(0);
6064     SDValue M0 = M->getOperand(2);
6065     SDValue Value = M->getOperand(3);
6066     unsigned IndexOperand = M->getConstantOperandVal(7);
6067     unsigned WaveRelease = M->getConstantOperandVal(8);
6068     unsigned WaveDone = M->getConstantOperandVal(9);
6069 
6070     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6071     IndexOperand &= ~0x3f;
6072     unsigned CountDw = 0;
6073 
6074     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6075       CountDw = (IndexOperand >> 24) & 0xf;
6076       IndexOperand &= ~(0xf << 24);
6077 
6078       if (CountDw < 1 || CountDw > 4) {
6079         report_fatal_error(
6080             "ds_ordered_count: dword count must be between 1 and 4");
6081       }
6082     }
6083 
6084     if (IndexOperand)
6085       report_fatal_error("ds_ordered_count: bad index operand");
6086 
6087     if (WaveDone && !WaveRelease)
6088       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6089 
6090     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6091     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6092     unsigned Offset0 = OrderedCountIndex << 2;
6093     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6094                        (Instruction << 4);
6095 
6096     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6097       Offset1 |= (CountDw - 1) << 6;
6098 
6099     unsigned Offset = Offset0 | (Offset1 << 8);
6100 
6101     SDValue Ops[] = {
6102       Chain,
6103       Value,
6104       DAG.getTargetConstant(Offset, DL, MVT::i16),
6105       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6106     };
6107     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6108                                    M->getVTList(), Ops, M->getMemoryVT(),
6109                                    M->getMemOperand());
6110   }
6111   case Intrinsic::amdgcn_ds_fadd: {
6112     MemSDNode *M = cast<MemSDNode>(Op);
6113     unsigned Opc;
6114     switch (IntrID) {
6115     case Intrinsic::amdgcn_ds_fadd:
6116       Opc = ISD::ATOMIC_LOAD_FADD;
6117       break;
6118     }
6119 
6120     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6121                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6122                          M->getMemOperand());
6123   }
6124   case Intrinsic::amdgcn_atomic_inc:
6125   case Intrinsic::amdgcn_atomic_dec:
6126   case Intrinsic::amdgcn_ds_fmin:
6127   case Intrinsic::amdgcn_ds_fmax: {
6128     MemSDNode *M = cast<MemSDNode>(Op);
6129     unsigned Opc;
6130     switch (IntrID) {
6131     case Intrinsic::amdgcn_atomic_inc:
6132       Opc = AMDGPUISD::ATOMIC_INC;
6133       break;
6134     case Intrinsic::amdgcn_atomic_dec:
6135       Opc = AMDGPUISD::ATOMIC_DEC;
6136       break;
6137     case Intrinsic::amdgcn_ds_fmin:
6138       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6139       break;
6140     case Intrinsic::amdgcn_ds_fmax:
6141       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6142       break;
6143     default:
6144       llvm_unreachable("Unknown intrinsic!");
6145     }
6146     SDValue Ops[] = {
6147       M->getOperand(0), // Chain
6148       M->getOperand(2), // Ptr
6149       M->getOperand(3)  // Value
6150     };
6151 
6152     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6153                                    M->getMemoryVT(), M->getMemOperand());
6154   }
6155   case Intrinsic::amdgcn_buffer_load:
6156   case Intrinsic::amdgcn_buffer_load_format: {
6157     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6158     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6159     unsigned IdxEn = 1;
6160     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6161       IdxEn = Idx->getZExtValue() != 0;
6162     SDValue Ops[] = {
6163       Op.getOperand(0), // Chain
6164       Op.getOperand(2), // rsrc
6165       Op.getOperand(3), // vindex
6166       SDValue(),        // voffset -- will be set by setBufferOffsets
6167       SDValue(),        // soffset -- will be set by setBufferOffsets
6168       SDValue(),        // offset -- will be set by setBufferOffsets
6169       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6170       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6171     };
6172 
6173     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6174     // We don't know the offset if vindex is non-zero, so clear it.
6175     if (IdxEn)
6176       Offset = 0;
6177 
6178     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6179         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6180 
6181     EVT VT = Op.getValueType();
6182     EVT IntVT = VT.changeTypeToInteger();
6183     auto *M = cast<MemSDNode>(Op);
6184     M->getMemOperand()->setOffset(Offset);
6185     EVT LoadVT = Op.getValueType();
6186 
6187     if (LoadVT.getScalarType() == MVT::f16)
6188       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6189                                  M, DAG, Ops);
6190 
6191     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6192     if (LoadVT.getScalarType() == MVT::i8 ||
6193         LoadVT.getScalarType() == MVT::i16)
6194       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6195 
6196     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6197                                M->getMemOperand(), DAG);
6198   }
6199   case Intrinsic::amdgcn_raw_buffer_load:
6200   case Intrinsic::amdgcn_raw_buffer_load_format: {
6201     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6202 
6203     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6204     SDValue Ops[] = {
6205       Op.getOperand(0), // Chain
6206       Op.getOperand(2), // rsrc
6207       DAG.getConstant(0, DL, MVT::i32), // vindex
6208       Offsets.first,    // voffset
6209       Op.getOperand(4), // soffset
6210       Offsets.second,   // offset
6211       Op.getOperand(5), // cachepolicy, swizzled buffer
6212       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6213     };
6214 
6215     auto *M = cast<MemSDNode>(Op);
6216     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6217     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6218   }
6219   case Intrinsic::amdgcn_struct_buffer_load:
6220   case Intrinsic::amdgcn_struct_buffer_load_format: {
6221     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6222 
6223     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6224     SDValue Ops[] = {
6225       Op.getOperand(0), // Chain
6226       Op.getOperand(2), // rsrc
6227       Op.getOperand(3), // vindex
6228       Offsets.first,    // voffset
6229       Op.getOperand(5), // soffset
6230       Offsets.second,   // offset
6231       Op.getOperand(6), // cachepolicy, swizzled buffer
6232       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6233     };
6234 
6235     auto *M = cast<MemSDNode>(Op);
6236     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6237                                                         Ops[2]));
6238     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6239   }
6240   case Intrinsic::amdgcn_tbuffer_load: {
6241     MemSDNode *M = cast<MemSDNode>(Op);
6242     EVT LoadVT = Op.getValueType();
6243 
6244     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6245     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6246     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6247     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6248     unsigned IdxEn = 1;
6249     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6250       IdxEn = Idx->getZExtValue() != 0;
6251     SDValue Ops[] = {
6252       Op.getOperand(0),  // Chain
6253       Op.getOperand(2),  // rsrc
6254       Op.getOperand(3),  // vindex
6255       Op.getOperand(4),  // voffset
6256       Op.getOperand(5),  // soffset
6257       Op.getOperand(6),  // offset
6258       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6259       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6260       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6261     };
6262 
6263     if (LoadVT.getScalarType() == MVT::f16)
6264       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6265                                  M, DAG, Ops);
6266     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6267                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6268                                DAG);
6269   }
6270   case Intrinsic::amdgcn_raw_tbuffer_load: {
6271     MemSDNode *M = cast<MemSDNode>(Op);
6272     EVT LoadVT = Op.getValueType();
6273     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6274 
6275     SDValue Ops[] = {
6276       Op.getOperand(0),  // Chain
6277       Op.getOperand(2),  // rsrc
6278       DAG.getConstant(0, DL, MVT::i32), // vindex
6279       Offsets.first,     // voffset
6280       Op.getOperand(4),  // soffset
6281       Offsets.second,    // offset
6282       Op.getOperand(5),  // format
6283       Op.getOperand(6),  // cachepolicy, swizzled buffer
6284       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6285     };
6286 
6287     if (LoadVT.getScalarType() == MVT::f16)
6288       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6289                                  M, DAG, Ops);
6290     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6291                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6292                                DAG);
6293   }
6294   case Intrinsic::amdgcn_struct_tbuffer_load: {
6295     MemSDNode *M = cast<MemSDNode>(Op);
6296     EVT LoadVT = Op.getValueType();
6297     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6298 
6299     SDValue Ops[] = {
6300       Op.getOperand(0),  // Chain
6301       Op.getOperand(2),  // rsrc
6302       Op.getOperand(3),  // vindex
6303       Offsets.first,     // voffset
6304       Op.getOperand(5),  // soffset
6305       Offsets.second,    // offset
6306       Op.getOperand(6),  // format
6307       Op.getOperand(7),  // cachepolicy, swizzled buffer
6308       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6309     };
6310 
6311     if (LoadVT.getScalarType() == MVT::f16)
6312       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6313                                  M, DAG, Ops);
6314     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6315                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6316                                DAG);
6317   }
6318   case Intrinsic::amdgcn_buffer_atomic_swap:
6319   case Intrinsic::amdgcn_buffer_atomic_add:
6320   case Intrinsic::amdgcn_buffer_atomic_sub:
6321   case Intrinsic::amdgcn_buffer_atomic_smin:
6322   case Intrinsic::amdgcn_buffer_atomic_umin:
6323   case Intrinsic::amdgcn_buffer_atomic_smax:
6324   case Intrinsic::amdgcn_buffer_atomic_umax:
6325   case Intrinsic::amdgcn_buffer_atomic_and:
6326   case Intrinsic::amdgcn_buffer_atomic_or:
6327   case Intrinsic::amdgcn_buffer_atomic_xor: {
6328     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6329     unsigned IdxEn = 1;
6330     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6331       IdxEn = Idx->getZExtValue() != 0;
6332     SDValue Ops[] = {
6333       Op.getOperand(0), // Chain
6334       Op.getOperand(2), // vdata
6335       Op.getOperand(3), // rsrc
6336       Op.getOperand(4), // vindex
6337       SDValue(),        // voffset -- will be set by setBufferOffsets
6338       SDValue(),        // soffset -- will be set by setBufferOffsets
6339       SDValue(),        // offset -- will be set by setBufferOffsets
6340       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6341       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6342     };
6343     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6344     // We don't know the offset if vindex is non-zero, so clear it.
6345     if (IdxEn)
6346       Offset = 0;
6347     EVT VT = Op.getValueType();
6348 
6349     auto *M = cast<MemSDNode>(Op);
6350     M->getMemOperand()->setOffset(Offset);
6351     unsigned Opcode = 0;
6352 
6353     switch (IntrID) {
6354     case Intrinsic::amdgcn_buffer_atomic_swap:
6355       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6356       break;
6357     case Intrinsic::amdgcn_buffer_atomic_add:
6358       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6359       break;
6360     case Intrinsic::amdgcn_buffer_atomic_sub:
6361       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6362       break;
6363     case Intrinsic::amdgcn_buffer_atomic_smin:
6364       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6365       break;
6366     case Intrinsic::amdgcn_buffer_atomic_umin:
6367       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6368       break;
6369     case Intrinsic::amdgcn_buffer_atomic_smax:
6370       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6371       break;
6372     case Intrinsic::amdgcn_buffer_atomic_umax:
6373       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6374       break;
6375     case Intrinsic::amdgcn_buffer_atomic_and:
6376       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6377       break;
6378     case Intrinsic::amdgcn_buffer_atomic_or:
6379       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6380       break;
6381     case Intrinsic::amdgcn_buffer_atomic_xor:
6382       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6383       break;
6384     default:
6385       llvm_unreachable("unhandled atomic opcode");
6386     }
6387 
6388     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6389                                    M->getMemOperand());
6390   }
6391   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6392   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6393   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6394   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6395   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6396   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6397   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6398   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6399   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6400   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6401   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6402   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6403     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6404     SDValue Ops[] = {
6405       Op.getOperand(0), // Chain
6406       Op.getOperand(2), // vdata
6407       Op.getOperand(3), // rsrc
6408       DAG.getConstant(0, DL, MVT::i32), // vindex
6409       Offsets.first,    // voffset
6410       Op.getOperand(5), // soffset
6411       Offsets.second,   // offset
6412       Op.getOperand(6), // cachepolicy
6413       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6414     };
6415     EVT VT = Op.getValueType();
6416 
6417     auto *M = cast<MemSDNode>(Op);
6418     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6419     unsigned Opcode = 0;
6420 
6421     switch (IntrID) {
6422     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6423       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6424       break;
6425     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6426       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6427       break;
6428     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6429       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6430       break;
6431     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6432       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6433       break;
6434     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6435       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6436       break;
6437     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6438       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6439       break;
6440     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6441       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6442       break;
6443     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6444       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6445       break;
6446     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6447       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6448       break;
6449     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6450       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6451       break;
6452     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6453       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6454       break;
6455     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6456       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6457       break;
6458     default:
6459       llvm_unreachable("unhandled atomic opcode");
6460     }
6461 
6462     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6463                                    M->getMemOperand());
6464   }
6465   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6466   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6467   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6468   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6469   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6470   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6471   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6472   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6473   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6474   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6475   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6476   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6477     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6478     SDValue Ops[] = {
6479       Op.getOperand(0), // Chain
6480       Op.getOperand(2), // vdata
6481       Op.getOperand(3), // rsrc
6482       Op.getOperand(4), // vindex
6483       Offsets.first,    // voffset
6484       Op.getOperand(6), // soffset
6485       Offsets.second,   // offset
6486       Op.getOperand(7), // cachepolicy
6487       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6488     };
6489     EVT VT = Op.getValueType();
6490 
6491     auto *M = cast<MemSDNode>(Op);
6492     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6493                                                         Ops[3]));
6494     unsigned Opcode = 0;
6495 
6496     switch (IntrID) {
6497     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6498       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6499       break;
6500     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6501       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6502       break;
6503     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6504       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6505       break;
6506     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6507       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6508       break;
6509     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6510       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6511       break;
6512     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6513       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6514       break;
6515     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6516       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6517       break;
6518     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6519       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6520       break;
6521     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6522       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6523       break;
6524     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6525       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6526       break;
6527     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6528       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6529       break;
6530     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
6531       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6532       break;
6533     default:
6534       llvm_unreachable("unhandled atomic opcode");
6535     }
6536 
6537     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6538                                    M->getMemOperand());
6539   }
6540   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6541     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6542     unsigned IdxEn = 1;
6543     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6544       IdxEn = Idx->getZExtValue() != 0;
6545     SDValue Ops[] = {
6546       Op.getOperand(0), // Chain
6547       Op.getOperand(2), // src
6548       Op.getOperand(3), // cmp
6549       Op.getOperand(4), // rsrc
6550       Op.getOperand(5), // vindex
6551       SDValue(),        // voffset -- will be set by setBufferOffsets
6552       SDValue(),        // soffset -- will be set by setBufferOffsets
6553       SDValue(),        // offset -- will be set by setBufferOffsets
6554       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6555       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6556     };
6557     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6558     // We don't know the offset if vindex is non-zero, so clear it.
6559     if (IdxEn)
6560       Offset = 0;
6561     EVT VT = Op.getValueType();
6562     auto *M = cast<MemSDNode>(Op);
6563     M->getMemOperand()->setOffset(Offset);
6564 
6565     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6566                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6567   }
6568   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6569     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6570     SDValue Ops[] = {
6571       Op.getOperand(0), // Chain
6572       Op.getOperand(2), // src
6573       Op.getOperand(3), // cmp
6574       Op.getOperand(4), // rsrc
6575       DAG.getConstant(0, DL, MVT::i32), // vindex
6576       Offsets.first,    // voffset
6577       Op.getOperand(6), // soffset
6578       Offsets.second,   // offset
6579       Op.getOperand(7), // cachepolicy
6580       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6581     };
6582     EVT VT = Op.getValueType();
6583     auto *M = cast<MemSDNode>(Op);
6584     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
6585 
6586     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6587                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6588   }
6589   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6590     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6591     SDValue Ops[] = {
6592       Op.getOperand(0), // Chain
6593       Op.getOperand(2), // src
6594       Op.getOperand(3), // cmp
6595       Op.getOperand(4), // rsrc
6596       Op.getOperand(5), // vindex
6597       Offsets.first,    // voffset
6598       Op.getOperand(7), // soffset
6599       Offsets.second,   // offset
6600       Op.getOperand(8), // cachepolicy
6601       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6602     };
6603     EVT VT = Op.getValueType();
6604     auto *M = cast<MemSDNode>(Op);
6605     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
6606                                                         Ops[4]));
6607 
6608     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6609                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6610   }
6611 
6612   default:
6613     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6614             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6615       return lowerImage(Op, ImageDimIntr, DAG);
6616 
6617     return SDValue();
6618   }
6619 }
6620 
6621 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6622 // dwordx4 if on SI.
6623 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6624                                               SDVTList VTList,
6625                                               ArrayRef<SDValue> Ops, EVT MemVT,
6626                                               MachineMemOperand *MMO,
6627                                               SelectionDAG &DAG) const {
6628   EVT VT = VTList.VTs[0];
6629   EVT WidenedVT = VT;
6630   EVT WidenedMemVT = MemVT;
6631   if (!Subtarget->hasDwordx3LoadStores() &&
6632       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6633     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6634                                  WidenedVT.getVectorElementType(), 4);
6635     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6636                                     WidenedMemVT.getVectorElementType(), 4);
6637     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6638   }
6639 
6640   assert(VTList.NumVTs == 2);
6641   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6642 
6643   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6644                                        WidenedMemVT, MMO);
6645   if (WidenedVT != VT) {
6646     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6647                                DAG.getVectorIdxConstant(0, DL));
6648     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6649   }
6650   return NewOp;
6651 }
6652 
6653 SDValue SITargetLowering::handleD16VData(SDValue VData,
6654                                          SelectionDAG &DAG) const {
6655   EVT StoreVT = VData.getValueType();
6656 
6657   // No change for f16 and legal vector D16 types.
6658   if (!StoreVT.isVector())
6659     return VData;
6660 
6661   SDLoc DL(VData);
6662   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6663 
6664   if (Subtarget->hasUnpackedD16VMem()) {
6665     // We need to unpack the packed data to store.
6666     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6667     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6668 
6669     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6670                                         StoreVT.getVectorNumElements());
6671     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6672     return DAG.UnrollVectorOp(ZExt.getNode());
6673   }
6674 
6675   assert(isTypeLegal(StoreVT));
6676   return VData;
6677 }
6678 
6679 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6680                                               SelectionDAG &DAG) const {
6681   SDLoc DL(Op);
6682   SDValue Chain = Op.getOperand(0);
6683   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6684   MachineFunction &MF = DAG.getMachineFunction();
6685 
6686   switch (IntrinsicID) {
6687   case Intrinsic::amdgcn_exp_compr: {
6688     SDValue Src0 = Op.getOperand(4);
6689     SDValue Src1 = Op.getOperand(5);
6690     // Hack around illegal type on SI by directly selecting it.
6691     if (isTypeLegal(Src0.getValueType()))
6692       return SDValue();
6693 
6694     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6695     SDValue Undef = DAG.getUNDEF(MVT::f32);
6696     const SDValue Ops[] = {
6697       Op.getOperand(2), // tgt
6698       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
6699       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
6700       Undef, // src2
6701       Undef, // src3
6702       Op.getOperand(7), // vm
6703       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6704       Op.getOperand(3), // en
6705       Op.getOperand(0) // Chain
6706     };
6707 
6708     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
6709     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
6710   }
6711   case Intrinsic::amdgcn_s_barrier: {
6712     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6713       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6714       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6715       if (WGSize <= ST.getWavefrontSize())
6716         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6717                                           Op.getOperand(0)), 0);
6718     }
6719     return SDValue();
6720   };
6721   case Intrinsic::amdgcn_tbuffer_store: {
6722     SDValue VData = Op.getOperand(2);
6723     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6724     if (IsD16)
6725       VData = handleD16VData(VData, DAG);
6726     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6727     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6728     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6729     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6730     unsigned IdxEn = 1;
6731     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6732       IdxEn = Idx->getZExtValue() != 0;
6733     SDValue Ops[] = {
6734       Chain,
6735       VData,             // vdata
6736       Op.getOperand(3),  // rsrc
6737       Op.getOperand(4),  // vindex
6738       Op.getOperand(5),  // voffset
6739       Op.getOperand(6),  // soffset
6740       Op.getOperand(7),  // offset
6741       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6742       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6743       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
6744     };
6745     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6746                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6747     MemSDNode *M = cast<MemSDNode>(Op);
6748     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6749                                    M->getMemoryVT(), M->getMemOperand());
6750   }
6751 
6752   case Intrinsic::amdgcn_struct_tbuffer_store: {
6753     SDValue VData = Op.getOperand(2);
6754     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6755     if (IsD16)
6756       VData = handleD16VData(VData, DAG);
6757     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6758     SDValue Ops[] = {
6759       Chain,
6760       VData,             // vdata
6761       Op.getOperand(3),  // rsrc
6762       Op.getOperand(4),  // vindex
6763       Offsets.first,     // voffset
6764       Op.getOperand(6),  // soffset
6765       Offsets.second,    // offset
6766       Op.getOperand(7),  // format
6767       Op.getOperand(8),  // cachepolicy, swizzled buffer
6768       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
6769     };
6770     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6771                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6772     MemSDNode *M = cast<MemSDNode>(Op);
6773     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6774                                    M->getMemoryVT(), M->getMemOperand());
6775   }
6776 
6777   case Intrinsic::amdgcn_raw_tbuffer_store: {
6778     SDValue VData = Op.getOperand(2);
6779     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6780     if (IsD16)
6781       VData = handleD16VData(VData, DAG);
6782     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6783     SDValue Ops[] = {
6784       Chain,
6785       VData,             // vdata
6786       Op.getOperand(3),  // rsrc
6787       DAG.getConstant(0, DL, MVT::i32), // vindex
6788       Offsets.first,     // voffset
6789       Op.getOperand(5),  // soffset
6790       Offsets.second,    // offset
6791       Op.getOperand(6),  // format
6792       Op.getOperand(7),  // cachepolicy, swizzled buffer
6793       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
6794     };
6795     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6796                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6797     MemSDNode *M = cast<MemSDNode>(Op);
6798     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6799                                    M->getMemoryVT(), M->getMemOperand());
6800   }
6801 
6802   case Intrinsic::amdgcn_buffer_store:
6803   case Intrinsic::amdgcn_buffer_store_format: {
6804     SDValue VData = Op.getOperand(2);
6805     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6806     if (IsD16)
6807       VData = handleD16VData(VData, DAG);
6808     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6809     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6810     unsigned IdxEn = 1;
6811     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6812       IdxEn = Idx->getZExtValue() != 0;
6813     SDValue Ops[] = {
6814       Chain,
6815       VData,
6816       Op.getOperand(3), // rsrc
6817       Op.getOperand(4), // vindex
6818       SDValue(), // voffset -- will be set by setBufferOffsets
6819       SDValue(), // soffset -- will be set by setBufferOffsets
6820       SDValue(), // offset -- will be set by setBufferOffsets
6821       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6822       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6823     };
6824     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6825     // We don't know the offset if vindex is non-zero, so clear it.
6826     if (IdxEn)
6827       Offset = 0;
6828     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6829                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6830     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6831     MemSDNode *M = cast<MemSDNode>(Op);
6832     M->getMemOperand()->setOffset(Offset);
6833 
6834     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6835     EVT VDataType = VData.getValueType().getScalarType();
6836     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6837       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6838 
6839     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6840                                    M->getMemoryVT(), M->getMemOperand());
6841   }
6842 
6843   case Intrinsic::amdgcn_raw_buffer_store:
6844   case Intrinsic::amdgcn_raw_buffer_store_format: {
6845     const bool IsFormat =
6846         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
6847 
6848     SDValue VData = Op.getOperand(2);
6849     EVT VDataVT = VData.getValueType();
6850     EVT EltType = VDataVT.getScalarType();
6851     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6852     if (IsD16)
6853       VData = handleD16VData(VData, DAG);
6854 
6855     if (!isTypeLegal(VDataVT)) {
6856       VData =
6857           DAG.getNode(ISD::BITCAST, DL,
6858                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6859     }
6860 
6861     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6862     SDValue Ops[] = {
6863       Chain,
6864       VData,
6865       Op.getOperand(3), // rsrc
6866       DAG.getConstant(0, DL, MVT::i32), // vindex
6867       Offsets.first,    // voffset
6868       Op.getOperand(5), // soffset
6869       Offsets.second,   // offset
6870       Op.getOperand(6), // cachepolicy, swizzled buffer
6871       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6872     };
6873     unsigned Opc =
6874         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
6875     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6876     MemSDNode *M = cast<MemSDNode>(Op);
6877     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6878 
6879     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6880     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
6881       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
6882 
6883     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6884                                    M->getMemoryVT(), M->getMemOperand());
6885   }
6886 
6887   case Intrinsic::amdgcn_struct_buffer_store:
6888   case Intrinsic::amdgcn_struct_buffer_store_format: {
6889     const bool IsFormat =
6890         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
6891 
6892     SDValue VData = Op.getOperand(2);
6893     EVT VDataVT = VData.getValueType();
6894     EVT EltType = VDataVT.getScalarType();
6895     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
6896 
6897     if (IsD16)
6898       VData = handleD16VData(VData, DAG);
6899 
6900     if (!isTypeLegal(VDataVT)) {
6901       VData =
6902           DAG.getNode(ISD::BITCAST, DL,
6903                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
6904     }
6905 
6906     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6907     SDValue Ops[] = {
6908       Chain,
6909       VData,
6910       Op.getOperand(3), // rsrc
6911       Op.getOperand(4), // vindex
6912       Offsets.first,    // voffset
6913       Op.getOperand(6), // soffset
6914       Offsets.second,   // offset
6915       Op.getOperand(7), // cachepolicy, swizzled buffer
6916       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6917     };
6918     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
6919                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6920     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6921     MemSDNode *M = cast<MemSDNode>(Op);
6922     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6923                                                         Ops[3]));
6924 
6925     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6926     EVT VDataType = VData.getValueType().getScalarType();
6927     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
6928       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6929 
6930     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6931                                    M->getMemoryVT(), M->getMemOperand());
6932   }
6933 
6934   case Intrinsic::amdgcn_buffer_atomic_fadd: {
6935     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6936     unsigned IdxEn = 1;
6937     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6938       IdxEn = Idx->getZExtValue() != 0;
6939     SDValue Ops[] = {
6940       Chain,
6941       Op.getOperand(2), // vdata
6942       Op.getOperand(3), // rsrc
6943       Op.getOperand(4), // vindex
6944       SDValue(),        // voffset -- will be set by setBufferOffsets
6945       SDValue(),        // soffset -- will be set by setBufferOffsets
6946       SDValue(),        // offset -- will be set by setBufferOffsets
6947       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6948       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6949     };
6950     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6951     // We don't know the offset if vindex is non-zero, so clear it.
6952     if (IdxEn)
6953       Offset = 0;
6954     EVT VT = Op.getOperand(2).getValueType();
6955 
6956     auto *M = cast<MemSDNode>(Op);
6957     M->getMemOperand()->setOffset(Offset);
6958     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
6959                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
6960 
6961     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6962                                    M->getMemOperand());
6963   }
6964 
6965   case Intrinsic::amdgcn_global_atomic_fadd: {
6966     SDValue Ops[] = {
6967       Chain,
6968       Op.getOperand(2), // ptr
6969       Op.getOperand(3)  // vdata
6970     };
6971     EVT VT = Op.getOperand(3).getValueType();
6972 
6973     auto *M = cast<MemSDNode>(Op);
6974     if (VT.isVector()) {
6975       return DAG.getMemIntrinsicNode(
6976         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
6977         M->getMemOperand());
6978     }
6979 
6980     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
6981                          DAG.getVTList(VT, MVT::Other), Ops,
6982                          M->getMemOperand()).getValue(1);
6983   }
6984   case Intrinsic::amdgcn_end_cf:
6985     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
6986                                       Op->getOperand(2), Chain), 0);
6987 
6988   default: {
6989     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6990             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6991       return lowerImage(Op, ImageDimIntr, DAG);
6992 
6993     return Op;
6994   }
6995   }
6996 }
6997 
6998 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
6999 // offset (the offset that is included in bounds checking and swizzling, to be
7000 // split between the instruction's voffset and immoffset fields) and soffset
7001 // (the offset that is excluded from bounds checking and swizzling, to go in
7002 // the instruction's soffset field).  This function takes the first kind of
7003 // offset and figures out how to split it between voffset and immoffset.
7004 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7005     SDValue Offset, SelectionDAG &DAG) const {
7006   SDLoc DL(Offset);
7007   const unsigned MaxImm = 4095;
7008   SDValue N0 = Offset;
7009   ConstantSDNode *C1 = nullptr;
7010 
7011   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7012     N0 = SDValue();
7013   else if (DAG.isBaseWithConstantOffset(N0)) {
7014     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7015     N0 = N0.getOperand(0);
7016   }
7017 
7018   if (C1) {
7019     unsigned ImmOffset = C1->getZExtValue();
7020     // If the immediate value is too big for the immoffset field, put the value
7021     // and -4096 into the immoffset field so that the value that is copied/added
7022     // for the voffset field is a multiple of 4096, and it stands more chance
7023     // of being CSEd with the copy/add for another similar load/store.
7024     // However, do not do that rounding down to a multiple of 4096 if that is a
7025     // negative number, as it appears to be illegal to have a negative offset
7026     // in the vgpr, even if adding the immediate offset makes it positive.
7027     unsigned Overflow = ImmOffset & ~MaxImm;
7028     ImmOffset -= Overflow;
7029     if ((int32_t)Overflow < 0) {
7030       Overflow += ImmOffset;
7031       ImmOffset = 0;
7032     }
7033     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7034     if (Overflow) {
7035       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7036       if (!N0)
7037         N0 = OverflowVal;
7038       else {
7039         SDValue Ops[] = { N0, OverflowVal };
7040         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7041       }
7042     }
7043   }
7044   if (!N0)
7045     N0 = DAG.getConstant(0, DL, MVT::i32);
7046   if (!C1)
7047     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7048   return {N0, SDValue(C1, 0)};
7049 }
7050 
7051 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7052 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7053 // pointed to by Offsets.
7054 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7055                                         SelectionDAG &DAG, SDValue *Offsets,
7056                                         unsigned Align) const {
7057   SDLoc DL(CombinedOffset);
7058   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7059     uint32_t Imm = C->getZExtValue();
7060     uint32_t SOffset, ImmOffset;
7061     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7062       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7063       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7064       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7065       return SOffset + ImmOffset;
7066     }
7067   }
7068   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7069     SDValue N0 = CombinedOffset.getOperand(0);
7070     SDValue N1 = CombinedOffset.getOperand(1);
7071     uint32_t SOffset, ImmOffset;
7072     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7073     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7074                                                 Subtarget, Align)) {
7075       Offsets[0] = N0;
7076       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7077       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7078       return 0;
7079     }
7080   }
7081   Offsets[0] = CombinedOffset;
7082   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7083   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7084   return 0;
7085 }
7086 
7087 // Handle 8 bit and 16 bit buffer loads
7088 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7089                                                      EVT LoadVT, SDLoc DL,
7090                                                      ArrayRef<SDValue> Ops,
7091                                                      MemSDNode *M) const {
7092   EVT IntVT = LoadVT.changeTypeToInteger();
7093   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7094          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7095 
7096   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7097   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7098                                                Ops, IntVT,
7099                                                M->getMemOperand());
7100   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7101   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7102 
7103   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7104 }
7105 
7106 // Handle 8 bit and 16 bit buffer stores
7107 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7108                                                       EVT VDataType, SDLoc DL,
7109                                                       SDValue Ops[],
7110                                                       MemSDNode *M) const {
7111   if (VDataType == MVT::f16)
7112     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7113 
7114   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7115   Ops[1] = BufferStoreExt;
7116   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7117                                  AMDGPUISD::BUFFER_STORE_SHORT;
7118   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7119   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7120                                      M->getMemOperand());
7121 }
7122 
7123 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7124                                  ISD::LoadExtType ExtType, SDValue Op,
7125                                  const SDLoc &SL, EVT VT) {
7126   if (VT.bitsLT(Op.getValueType()))
7127     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7128 
7129   switch (ExtType) {
7130   case ISD::SEXTLOAD:
7131     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7132   case ISD::ZEXTLOAD:
7133     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7134   case ISD::EXTLOAD:
7135     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7136   case ISD::NON_EXTLOAD:
7137     return Op;
7138   }
7139 
7140   llvm_unreachable("invalid ext type");
7141 }
7142 
7143 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7144   SelectionDAG &DAG = DCI.DAG;
7145   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7146     return SDValue();
7147 
7148   // FIXME: Constant loads should all be marked invariant.
7149   unsigned AS = Ld->getAddressSpace();
7150   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7151       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7152       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7153     return SDValue();
7154 
7155   // Don't do this early, since it may interfere with adjacent load merging for
7156   // illegal types. We can avoid losing alignment information for exotic types
7157   // pre-legalize.
7158   EVT MemVT = Ld->getMemoryVT();
7159   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7160       MemVT.getSizeInBits() >= 32)
7161     return SDValue();
7162 
7163   SDLoc SL(Ld);
7164 
7165   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7166          "unexpected vector extload");
7167 
7168   // TODO: Drop only high part of range.
7169   SDValue Ptr = Ld->getBasePtr();
7170   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7171                                 MVT::i32, SL, Ld->getChain(), Ptr,
7172                                 Ld->getOffset(),
7173                                 Ld->getPointerInfo(), MVT::i32,
7174                                 Ld->getAlignment(),
7175                                 Ld->getMemOperand()->getFlags(),
7176                                 Ld->getAAInfo(),
7177                                 nullptr); // Drop ranges
7178 
7179   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7180   if (MemVT.isFloatingPoint()) {
7181     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7182            "unexpected fp extload");
7183     TruncVT = MemVT.changeTypeToInteger();
7184   }
7185 
7186   SDValue Cvt = NewLoad;
7187   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7188     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7189                       DAG.getValueType(TruncVT));
7190   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7191              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7192     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7193   } else {
7194     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7195   }
7196 
7197   EVT VT = Ld->getValueType(0);
7198   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7199 
7200   DCI.AddToWorklist(Cvt.getNode());
7201 
7202   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7203   // the appropriate extension from the 32-bit load.
7204   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7205   DCI.AddToWorklist(Cvt.getNode());
7206 
7207   // Handle conversion back to floating point if necessary.
7208   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7209 
7210   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7211 }
7212 
7213 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7214   SDLoc DL(Op);
7215   LoadSDNode *Load = cast<LoadSDNode>(Op);
7216   ISD::LoadExtType ExtType = Load->getExtensionType();
7217   EVT MemVT = Load->getMemoryVT();
7218 
7219   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7220     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7221       return SDValue();
7222 
7223     // FIXME: Copied from PPC
7224     // First, load into 32 bits, then truncate to 1 bit.
7225 
7226     SDValue Chain = Load->getChain();
7227     SDValue BasePtr = Load->getBasePtr();
7228     MachineMemOperand *MMO = Load->getMemOperand();
7229 
7230     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7231 
7232     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7233                                    BasePtr, RealMemVT, MMO);
7234 
7235     if (!MemVT.isVector()) {
7236       SDValue Ops[] = {
7237         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7238         NewLD.getValue(1)
7239       };
7240 
7241       return DAG.getMergeValues(Ops, DL);
7242     }
7243 
7244     SmallVector<SDValue, 3> Elts;
7245     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7246       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7247                                 DAG.getConstant(I, DL, MVT::i32));
7248 
7249       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7250     }
7251 
7252     SDValue Ops[] = {
7253       DAG.getBuildVector(MemVT, DL, Elts),
7254       NewLD.getValue(1)
7255     };
7256 
7257     return DAG.getMergeValues(Ops, DL);
7258   }
7259 
7260   if (!MemVT.isVector())
7261     return SDValue();
7262 
7263   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7264          "Custom lowering for non-i32 vectors hasn't been implemented.");
7265 
7266   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7267                                       MemVT, *Load->getMemOperand())) {
7268     SDValue Ops[2];
7269     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7270     return DAG.getMergeValues(Ops, DL);
7271   }
7272 
7273   unsigned Alignment = Load->getAlignment();
7274   unsigned AS = Load->getAddressSpace();
7275   if (Subtarget->hasLDSMisalignedBug() &&
7276       AS == AMDGPUAS::FLAT_ADDRESS &&
7277       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7278     return SplitVectorLoad(Op, DAG);
7279   }
7280 
7281   MachineFunction &MF = DAG.getMachineFunction();
7282   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7283   // If there is a possibilty that flat instruction access scratch memory
7284   // then we need to use the same legalization rules we use for private.
7285   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7286       !Subtarget->hasMultiDwordFlatScratchAddressing())
7287     AS = MFI->hasFlatScratchInit() ?
7288          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7289 
7290   unsigned NumElements = MemVT.getVectorNumElements();
7291 
7292   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7293       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7294     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7295       if (MemVT.isPow2VectorType())
7296         return SDValue();
7297       if (NumElements == 3)
7298         return WidenVectorLoad(Op, DAG);
7299       return SplitVectorLoad(Op, DAG);
7300     }
7301     // Non-uniform loads will be selected to MUBUF instructions, so they
7302     // have the same legalization requirements as global and private
7303     // loads.
7304     //
7305   }
7306 
7307   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7308       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7309       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7310     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7311         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
7312         Alignment >= 4 && NumElements < 32) {
7313       if (MemVT.isPow2VectorType())
7314         return SDValue();
7315       if (NumElements == 3)
7316         return WidenVectorLoad(Op, DAG);
7317       return SplitVectorLoad(Op, DAG);
7318     }
7319     // Non-uniform loads will be selected to MUBUF instructions, so they
7320     // have the same legalization requirements as global and private
7321     // loads.
7322     //
7323   }
7324   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7325       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7326       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7327       AS == AMDGPUAS::FLAT_ADDRESS) {
7328     if (NumElements > 4)
7329       return SplitVectorLoad(Op, DAG);
7330     // v3 loads not supported on SI.
7331     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7332       return WidenVectorLoad(Op, DAG);
7333     // v3 and v4 loads are supported for private and global memory.
7334     return SDValue();
7335   }
7336   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7337     // Depending on the setting of the private_element_size field in the
7338     // resource descriptor, we can only make private accesses up to a certain
7339     // size.
7340     switch (Subtarget->getMaxPrivateElementSize()) {
7341     case 4: {
7342       SDValue Ops[2];
7343       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7344       return DAG.getMergeValues(Ops, DL);
7345     }
7346     case 8:
7347       if (NumElements > 2)
7348         return SplitVectorLoad(Op, DAG);
7349       return SDValue();
7350     case 16:
7351       // Same as global/flat
7352       if (NumElements > 4)
7353         return SplitVectorLoad(Op, DAG);
7354       // v3 loads not supported on SI.
7355       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7356         return WidenVectorLoad(Op, DAG);
7357       return SDValue();
7358     default:
7359       llvm_unreachable("unsupported private_element_size");
7360     }
7361   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7362     // Use ds_read_b128 if possible.
7363     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7364         MemVT.getStoreSize() == 16)
7365       return SDValue();
7366 
7367     if (NumElements > 2)
7368       return SplitVectorLoad(Op, DAG);
7369 
7370     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7371     // address is negative, then the instruction is incorrectly treated as
7372     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7373     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7374     // load later in the SILoadStoreOptimizer.
7375     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7376         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7377         Load->getAlignment() < 8) {
7378       return SplitVectorLoad(Op, DAG);
7379     }
7380   }
7381   return SDValue();
7382 }
7383 
7384 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7385   EVT VT = Op.getValueType();
7386   assert(VT.getSizeInBits() == 64);
7387 
7388   SDLoc DL(Op);
7389   SDValue Cond = Op.getOperand(0);
7390 
7391   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7392   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7393 
7394   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7395   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7396 
7397   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7398   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7399 
7400   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7401 
7402   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7403   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7404 
7405   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7406 
7407   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7408   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7409 }
7410 
7411 // Catch division cases where we can use shortcuts with rcp and rsq
7412 // instructions.
7413 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7414                                               SelectionDAG &DAG) const {
7415   SDLoc SL(Op);
7416   SDValue LHS = Op.getOperand(0);
7417   SDValue RHS = Op.getOperand(1);
7418   EVT VT = Op.getValueType();
7419   const SDNodeFlags Flags = Op->getFlags();
7420 
7421   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7422                             Flags.hasApproximateFuncs();
7423 
7424   // Without !fpmath accuracy information, we can't do more because we don't
7425   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7426   if (!AllowInaccurateRcp)
7427     return SDValue();
7428 
7429   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7430     if (CLHS->isExactlyValue(1.0)) {
7431       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7432       // the CI documentation has a worst case error of 1 ulp.
7433       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7434       // use it as long as we aren't trying to use denormals.
7435       //
7436       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7437 
7438       // 1.0 / sqrt(x) -> rsq(x)
7439 
7440       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7441       // error seems really high at 2^29 ULP.
7442       if (RHS.getOpcode() == ISD::FSQRT)
7443         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7444 
7445       // 1.0 / x -> rcp(x)
7446       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7447     }
7448 
7449     // Same as for 1.0, but expand the sign out of the constant.
7450     if (CLHS->isExactlyValue(-1.0)) {
7451       // -1.0 / x -> rcp (fneg x)
7452       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7453       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7454     }
7455   }
7456 
7457   // Turn into multiply by the reciprocal.
7458   // x / y -> x * (1.0 / y)
7459   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7460   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7461 }
7462 
7463 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7464                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7465   if (GlueChain->getNumValues() <= 1) {
7466     return DAG.getNode(Opcode, SL, VT, A, B);
7467   }
7468 
7469   assert(GlueChain->getNumValues() == 3);
7470 
7471   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7472   switch (Opcode) {
7473   default: llvm_unreachable("no chain equivalent for opcode");
7474   case ISD::FMUL:
7475     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7476     break;
7477   }
7478 
7479   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7480                      GlueChain.getValue(2));
7481 }
7482 
7483 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7484                            EVT VT, SDValue A, SDValue B, SDValue C,
7485                            SDValue GlueChain) {
7486   if (GlueChain->getNumValues() <= 1) {
7487     return DAG.getNode(Opcode, SL, VT, A, B, C);
7488   }
7489 
7490   assert(GlueChain->getNumValues() == 3);
7491 
7492   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7493   switch (Opcode) {
7494   default: llvm_unreachable("no chain equivalent for opcode");
7495   case ISD::FMA:
7496     Opcode = AMDGPUISD::FMA_W_CHAIN;
7497     break;
7498   }
7499 
7500   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7501                      GlueChain.getValue(2));
7502 }
7503 
7504 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7505   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7506     return FastLowered;
7507 
7508   SDLoc SL(Op);
7509   SDValue Src0 = Op.getOperand(0);
7510   SDValue Src1 = Op.getOperand(1);
7511 
7512   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7513   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7514 
7515   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7516   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7517 
7518   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7519   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7520 
7521   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7522 }
7523 
7524 // Faster 2.5 ULP division that does not support denormals.
7525 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7526   SDLoc SL(Op);
7527   SDValue LHS = Op.getOperand(1);
7528   SDValue RHS = Op.getOperand(2);
7529 
7530   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7531 
7532   const APFloat K0Val(BitsToFloat(0x6f800000));
7533   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7534 
7535   const APFloat K1Val(BitsToFloat(0x2f800000));
7536   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7537 
7538   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7539 
7540   EVT SetCCVT =
7541     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7542 
7543   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7544 
7545   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7546 
7547   // TODO: Should this propagate fast-math-flags?
7548   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7549 
7550   // rcp does not support denormals.
7551   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7552 
7553   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7554 
7555   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7556 }
7557 
7558 // Returns immediate value for setting the F32 denorm mode when using the
7559 // S_DENORM_MODE instruction.
7560 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
7561                                           const SDLoc &SL, const GCNSubtarget *ST) {
7562   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
7563   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
7564                                 ? FP_DENORM_FLUSH_NONE
7565                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
7566 
7567   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
7568   return DAG.getTargetConstant(Mode, SL, MVT::i32);
7569 }
7570 
7571 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7572   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7573     return FastLowered;
7574 
7575   SDLoc SL(Op);
7576   SDValue LHS = Op.getOperand(0);
7577   SDValue RHS = Op.getOperand(1);
7578 
7579   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7580 
7581   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7582 
7583   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7584                                           RHS, RHS, LHS);
7585   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7586                                         LHS, RHS, LHS);
7587 
7588   // Denominator is scaled to not be denormal, so using rcp is ok.
7589   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7590                                   DenominatorScaled);
7591   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7592                                      DenominatorScaled);
7593 
7594   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7595                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7596                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7597   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7598 
7599   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
7600 
7601   if (!HasFP32Denormals) {
7602     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7603 
7604     SDValue EnableDenorm;
7605     if (Subtarget->hasDenormModeInst()) {
7606       const SDValue EnableDenormValue =
7607           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
7608 
7609       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
7610                                  DAG.getEntryNode(), EnableDenormValue);
7611     } else {
7612       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7613                                                         SL, MVT::i32);
7614       EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7615                                  DAG.getEntryNode(), EnableDenormValue,
7616                                  BitField);
7617     }
7618 
7619     SDValue Ops[3] = {
7620       NegDivScale0,
7621       EnableDenorm.getValue(0),
7622       EnableDenorm.getValue(1)
7623     };
7624 
7625     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7626   }
7627 
7628   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7629                              ApproxRcp, One, NegDivScale0);
7630 
7631   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7632                              ApproxRcp, Fma0);
7633 
7634   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7635                            Fma1, Fma1);
7636 
7637   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7638                              NumeratorScaled, Mul);
7639 
7640   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7641 
7642   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7643                              NumeratorScaled, Fma3);
7644 
7645   if (!HasFP32Denormals) {
7646     SDValue DisableDenorm;
7647     if (Subtarget->hasDenormModeInst()) {
7648       const SDValue DisableDenormValue =
7649           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
7650 
7651       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
7652                                   Fma4.getValue(1), DisableDenormValue,
7653                                   Fma4.getValue(2));
7654     } else {
7655       const SDValue DisableDenormValue =
7656           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7657 
7658       DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7659                                   Fma4.getValue(1), DisableDenormValue,
7660                                   BitField, Fma4.getValue(2));
7661     }
7662 
7663     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7664                                       DisableDenorm, DAG.getRoot());
7665     DAG.setRoot(OutputChain);
7666   }
7667 
7668   SDValue Scale = NumeratorScaled.getValue(1);
7669   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7670                              Fma4, Fma1, Fma3, Scale);
7671 
7672   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7673 }
7674 
7675 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7676   if (DAG.getTarget().Options.UnsafeFPMath)
7677     return lowerFastUnsafeFDIV(Op, DAG);
7678 
7679   SDLoc SL(Op);
7680   SDValue X = Op.getOperand(0);
7681   SDValue Y = Op.getOperand(1);
7682 
7683   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7684 
7685   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7686 
7687   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7688 
7689   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7690 
7691   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7692 
7693   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7694 
7695   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7696 
7697   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7698 
7699   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7700 
7701   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7702   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7703 
7704   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7705                              NegDivScale0, Mul, DivScale1);
7706 
7707   SDValue Scale;
7708 
7709   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
7710     // Workaround a hardware bug on SI where the condition output from div_scale
7711     // is not usable.
7712 
7713     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7714 
7715     // Figure out if the scale to use for div_fmas.
7716     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7717     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7718     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7719     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7720 
7721     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7722     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7723 
7724     SDValue Scale0Hi
7725       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7726     SDValue Scale1Hi
7727       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7728 
7729     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7730     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7731     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7732   } else {
7733     Scale = DivScale1.getValue(1);
7734   }
7735 
7736   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7737                              Fma4, Fma3, Mul, Scale);
7738 
7739   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7740 }
7741 
7742 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7743   EVT VT = Op.getValueType();
7744 
7745   if (VT == MVT::f32)
7746     return LowerFDIV32(Op, DAG);
7747 
7748   if (VT == MVT::f64)
7749     return LowerFDIV64(Op, DAG);
7750 
7751   if (VT == MVT::f16)
7752     return LowerFDIV16(Op, DAG);
7753 
7754   llvm_unreachable("Unexpected type for fdiv");
7755 }
7756 
7757 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7758   SDLoc DL(Op);
7759   StoreSDNode *Store = cast<StoreSDNode>(Op);
7760   EVT VT = Store->getMemoryVT();
7761 
7762   if (VT == MVT::i1) {
7763     return DAG.getTruncStore(Store->getChain(), DL,
7764        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7765        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
7766   }
7767 
7768   assert(VT.isVector() &&
7769          Store->getValue().getValueType().getScalarType() == MVT::i32);
7770 
7771   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7772                                       VT, *Store->getMemOperand())) {
7773     return expandUnalignedStore(Store, DAG);
7774   }
7775 
7776   unsigned AS = Store->getAddressSpace();
7777   if (Subtarget->hasLDSMisalignedBug() &&
7778       AS == AMDGPUAS::FLAT_ADDRESS &&
7779       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7780     return SplitVectorStore(Op, DAG);
7781   }
7782 
7783   MachineFunction &MF = DAG.getMachineFunction();
7784   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7785   // If there is a possibilty that flat instruction access scratch memory
7786   // then we need to use the same legalization rules we use for private.
7787   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7788       !Subtarget->hasMultiDwordFlatScratchAddressing())
7789     AS = MFI->hasFlatScratchInit() ?
7790          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7791 
7792   unsigned NumElements = VT.getVectorNumElements();
7793   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7794       AS == AMDGPUAS::FLAT_ADDRESS) {
7795     if (NumElements > 4)
7796       return SplitVectorStore(Op, DAG);
7797     // v3 stores not supported on SI.
7798     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7799       return SplitVectorStore(Op, DAG);
7800     return SDValue();
7801   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7802     switch (Subtarget->getMaxPrivateElementSize()) {
7803     case 4:
7804       return scalarizeVectorStore(Store, DAG);
7805     case 8:
7806       if (NumElements > 2)
7807         return SplitVectorStore(Op, DAG);
7808       return SDValue();
7809     case 16:
7810       if (NumElements > 4 || NumElements == 3)
7811         return SplitVectorStore(Op, DAG);
7812       return SDValue();
7813     default:
7814       llvm_unreachable("unsupported private_element_size");
7815     }
7816   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7817     // Use ds_write_b128 if possible.
7818     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
7819         VT.getStoreSize() == 16 && NumElements != 3)
7820       return SDValue();
7821 
7822     if (NumElements > 2)
7823       return SplitVectorStore(Op, DAG);
7824 
7825     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7826     // address is negative, then the instruction is incorrectly treated as
7827     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7828     // stores here to avoid emitting ds_write2_b32. We may re-combine the
7829     // store later in the SILoadStoreOptimizer.
7830     if (!Subtarget->hasUsableDSOffset() &&
7831         NumElements == 2 && VT.getStoreSize() == 8 &&
7832         Store->getAlignment() < 8) {
7833       return SplitVectorStore(Op, DAG);
7834     }
7835 
7836     return SDValue();
7837   } else {
7838     llvm_unreachable("unhandled address space");
7839   }
7840 }
7841 
7842 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
7843   SDLoc DL(Op);
7844   EVT VT = Op.getValueType();
7845   SDValue Arg = Op.getOperand(0);
7846   SDValue TrigVal;
7847 
7848   // TODO: Should this propagate fast-math-flags?
7849 
7850   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7851 
7852   if (Subtarget->hasTrigReducedRange()) {
7853     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7854     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7855   } else {
7856     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7857   }
7858 
7859   switch (Op.getOpcode()) {
7860   case ISD::FCOS:
7861     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7862   case ISD::FSIN:
7863     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7864   default:
7865     llvm_unreachable("Wrong trig opcode");
7866   }
7867 }
7868 
7869 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7870   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7871   assert(AtomicNode->isCompareAndSwap());
7872   unsigned AS = AtomicNode->getAddressSpace();
7873 
7874   // No custom lowering required for local address space
7875   if (!isFlatGlobalAddrSpace(AS))
7876     return Op;
7877 
7878   // Non-local address space requires custom lowering for atomic compare
7879   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
7880   SDLoc DL(Op);
7881   SDValue ChainIn = Op.getOperand(0);
7882   SDValue Addr = Op.getOperand(1);
7883   SDValue Old = Op.getOperand(2);
7884   SDValue New = Op.getOperand(3);
7885   EVT VT = Op.getValueType();
7886   MVT SimpleVT = VT.getSimpleVT();
7887   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
7888 
7889   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
7890   SDValue Ops[] = { ChainIn, Addr, NewOld };
7891 
7892   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
7893                                  Ops, VT, AtomicNode->getMemOperand());
7894 }
7895 
7896 //===----------------------------------------------------------------------===//
7897 // Custom DAG optimizations
7898 //===----------------------------------------------------------------------===//
7899 
7900 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
7901                                                      DAGCombinerInfo &DCI) const {
7902   EVT VT = N->getValueType(0);
7903   EVT ScalarVT = VT.getScalarType();
7904   if (ScalarVT != MVT::f32)
7905     return SDValue();
7906 
7907   SelectionDAG &DAG = DCI.DAG;
7908   SDLoc DL(N);
7909 
7910   SDValue Src = N->getOperand(0);
7911   EVT SrcVT = Src.getValueType();
7912 
7913   // TODO: We could try to match extracting the higher bytes, which would be
7914   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
7915   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
7916   // about in practice.
7917   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
7918     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
7919       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
7920       DCI.AddToWorklist(Cvt.getNode());
7921       return Cvt;
7922     }
7923   }
7924 
7925   return SDValue();
7926 }
7927 
7928 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
7929 
7930 // This is a variant of
7931 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
7932 //
7933 // The normal DAG combiner will do this, but only if the add has one use since
7934 // that would increase the number of instructions.
7935 //
7936 // This prevents us from seeing a constant offset that can be folded into a
7937 // memory instruction's addressing mode. If we know the resulting add offset of
7938 // a pointer can be folded into an addressing offset, we can replace the pointer
7939 // operand with the add of new constant offset. This eliminates one of the uses,
7940 // and may allow the remaining use to also be simplified.
7941 //
7942 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
7943                                                unsigned AddrSpace,
7944                                                EVT MemVT,
7945                                                DAGCombinerInfo &DCI) const {
7946   SDValue N0 = N->getOperand(0);
7947   SDValue N1 = N->getOperand(1);
7948 
7949   // We only do this to handle cases where it's profitable when there are
7950   // multiple uses of the add, so defer to the standard combine.
7951   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
7952       N0->hasOneUse())
7953     return SDValue();
7954 
7955   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
7956   if (!CN1)
7957     return SDValue();
7958 
7959   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7960   if (!CAdd)
7961     return SDValue();
7962 
7963   // If the resulting offset is too large, we can't fold it into the addressing
7964   // mode offset.
7965   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
7966   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
7967 
7968   AddrMode AM;
7969   AM.HasBaseReg = true;
7970   AM.BaseOffs = Offset.getSExtValue();
7971   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
7972     return SDValue();
7973 
7974   SelectionDAG &DAG = DCI.DAG;
7975   SDLoc SL(N);
7976   EVT VT = N->getValueType(0);
7977 
7978   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
7979   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
7980 
7981   SDNodeFlags Flags;
7982   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
7983                           (N0.getOpcode() == ISD::OR ||
7984                            N0->getFlags().hasNoUnsignedWrap()));
7985 
7986   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
7987 }
7988 
7989 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
7990                                                   DAGCombinerInfo &DCI) const {
7991   SDValue Ptr = N->getBasePtr();
7992   SelectionDAG &DAG = DCI.DAG;
7993   SDLoc SL(N);
7994 
7995   // TODO: We could also do this for multiplies.
7996   if (Ptr.getOpcode() == ISD::SHL) {
7997     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
7998                                           N->getMemoryVT(), DCI);
7999     if (NewPtr) {
8000       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8001 
8002       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8003       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8004     }
8005   }
8006 
8007   return SDValue();
8008 }
8009 
8010 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8011   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8012          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8013          (Opc == ISD::XOR && Val == 0);
8014 }
8015 
8016 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8017 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8018 // integer combine opportunities since most 64-bit operations are decomposed
8019 // this way.  TODO: We won't want this for SALU especially if it is an inline
8020 // immediate.
8021 SDValue SITargetLowering::splitBinaryBitConstantOp(
8022   DAGCombinerInfo &DCI,
8023   const SDLoc &SL,
8024   unsigned Opc, SDValue LHS,
8025   const ConstantSDNode *CRHS) const {
8026   uint64_t Val = CRHS->getZExtValue();
8027   uint32_t ValLo = Lo_32(Val);
8028   uint32_t ValHi = Hi_32(Val);
8029   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8030 
8031     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8032          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8033         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8034     // If we need to materialize a 64-bit immediate, it will be split up later
8035     // anyway. Avoid creating the harder to understand 64-bit immediate
8036     // materialization.
8037     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8038   }
8039 
8040   return SDValue();
8041 }
8042 
8043 // Returns true if argument is a boolean value which is not serialized into
8044 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8045 static bool isBoolSGPR(SDValue V) {
8046   if (V.getValueType() != MVT::i1)
8047     return false;
8048   switch (V.getOpcode()) {
8049   default: break;
8050   case ISD::SETCC:
8051   case ISD::AND:
8052   case ISD::OR:
8053   case ISD::XOR:
8054   case AMDGPUISD::FP_CLASS:
8055     return true;
8056   }
8057   return false;
8058 }
8059 
8060 // If a constant has all zeroes or all ones within each byte return it.
8061 // Otherwise return 0.
8062 static uint32_t getConstantPermuteMask(uint32_t C) {
8063   // 0xff for any zero byte in the mask
8064   uint32_t ZeroByteMask = 0;
8065   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8066   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8067   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8068   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8069   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8070   if ((NonZeroByteMask & C) != NonZeroByteMask)
8071     return 0; // Partial bytes selected.
8072   return C;
8073 }
8074 
8075 // Check if a node selects whole bytes from its operand 0 starting at a byte
8076 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8077 // or -1 if not succeeded.
8078 // Note byte select encoding:
8079 // value 0-3 selects corresponding source byte;
8080 // value 0xc selects zero;
8081 // value 0xff selects 0xff.
8082 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8083   assert(V.getValueSizeInBits() == 32);
8084 
8085   if (V.getNumOperands() != 2)
8086     return ~0;
8087 
8088   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8089   if (!N1)
8090     return ~0;
8091 
8092   uint32_t C = N1->getZExtValue();
8093 
8094   switch (V.getOpcode()) {
8095   default:
8096     break;
8097   case ISD::AND:
8098     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8099       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8100     }
8101     break;
8102 
8103   case ISD::OR:
8104     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8105       return (0x03020100 & ~ConstMask) | ConstMask;
8106     }
8107     break;
8108 
8109   case ISD::SHL:
8110     if (C % 8)
8111       return ~0;
8112 
8113     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8114 
8115   case ISD::SRL:
8116     if (C % 8)
8117       return ~0;
8118 
8119     return uint32_t(0x0c0c0c0c03020100ull >> C);
8120   }
8121 
8122   return ~0;
8123 }
8124 
8125 SDValue SITargetLowering::performAndCombine(SDNode *N,
8126                                             DAGCombinerInfo &DCI) const {
8127   if (DCI.isBeforeLegalize())
8128     return SDValue();
8129 
8130   SelectionDAG &DAG = DCI.DAG;
8131   EVT VT = N->getValueType(0);
8132   SDValue LHS = N->getOperand(0);
8133   SDValue RHS = N->getOperand(1);
8134 
8135 
8136   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8137   if (VT == MVT::i64 && CRHS) {
8138     if (SDValue Split
8139         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8140       return Split;
8141   }
8142 
8143   if (CRHS && VT == MVT::i32) {
8144     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8145     // nb = number of trailing zeroes in mask
8146     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8147     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8148     uint64_t Mask = CRHS->getZExtValue();
8149     unsigned Bits = countPopulation(Mask);
8150     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8151         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8152       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8153         unsigned Shift = CShift->getZExtValue();
8154         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8155         unsigned Offset = NB + Shift;
8156         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8157           SDLoc SL(N);
8158           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8159                                     LHS->getOperand(0),
8160                                     DAG.getConstant(Offset, SL, MVT::i32),
8161                                     DAG.getConstant(Bits, SL, MVT::i32));
8162           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8163           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8164                                     DAG.getValueType(NarrowVT));
8165           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8166                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8167           return Shl;
8168         }
8169       }
8170     }
8171 
8172     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8173     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8174         isa<ConstantSDNode>(LHS.getOperand(2))) {
8175       uint32_t Sel = getConstantPermuteMask(Mask);
8176       if (!Sel)
8177         return SDValue();
8178 
8179       // Select 0xc for all zero bytes
8180       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8181       SDLoc DL(N);
8182       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8183                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8184     }
8185   }
8186 
8187   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8188   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8189   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8190     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8191     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8192 
8193     SDValue X = LHS.getOperand(0);
8194     SDValue Y = RHS.getOperand(0);
8195     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8196       return SDValue();
8197 
8198     if (LCC == ISD::SETO) {
8199       if (X != LHS.getOperand(1))
8200         return SDValue();
8201 
8202       if (RCC == ISD::SETUNE) {
8203         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8204         if (!C1 || !C1->isInfinity() || C1->isNegative())
8205           return SDValue();
8206 
8207         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8208                               SIInstrFlags::N_SUBNORMAL |
8209                               SIInstrFlags::N_ZERO |
8210                               SIInstrFlags::P_ZERO |
8211                               SIInstrFlags::P_SUBNORMAL |
8212                               SIInstrFlags::P_NORMAL;
8213 
8214         static_assert(((~(SIInstrFlags::S_NAN |
8215                           SIInstrFlags::Q_NAN |
8216                           SIInstrFlags::N_INFINITY |
8217                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8218                       "mask not equal");
8219 
8220         SDLoc DL(N);
8221         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8222                            X, DAG.getConstant(Mask, DL, MVT::i32));
8223       }
8224     }
8225   }
8226 
8227   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8228     std::swap(LHS, RHS);
8229 
8230   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8231       RHS.hasOneUse()) {
8232     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8233     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8234     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8235     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8236     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8237         (RHS.getOperand(0) == LHS.getOperand(0) &&
8238          LHS.getOperand(0) == LHS.getOperand(1))) {
8239       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8240       unsigned NewMask = LCC == ISD::SETO ?
8241         Mask->getZExtValue() & ~OrdMask :
8242         Mask->getZExtValue() & OrdMask;
8243 
8244       SDLoc DL(N);
8245       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8246                          DAG.getConstant(NewMask, DL, MVT::i32));
8247     }
8248   }
8249 
8250   if (VT == MVT::i32 &&
8251       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8252     // and x, (sext cc from i1) => select cc, x, 0
8253     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8254       std::swap(LHS, RHS);
8255     if (isBoolSGPR(RHS.getOperand(0)))
8256       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8257                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8258   }
8259 
8260   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8261   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8262   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8263       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8264     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8265     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8266     if (LHSMask != ~0u && RHSMask != ~0u) {
8267       // Canonicalize the expression in an attempt to have fewer unique masks
8268       // and therefore fewer registers used to hold the masks.
8269       if (LHSMask > RHSMask) {
8270         std::swap(LHSMask, RHSMask);
8271         std::swap(LHS, RHS);
8272       }
8273 
8274       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8275       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8276       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8277       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8278 
8279       // Check of we need to combine values from two sources within a byte.
8280       if (!(LHSUsedLanes & RHSUsedLanes) &&
8281           // If we select high and lower word keep it for SDWA.
8282           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8283           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8284         // Each byte in each mask is either selector mask 0-3, or has higher
8285         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8286         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8287         // mask which is not 0xff wins. By anding both masks we have a correct
8288         // result except that 0x0c shall be corrected to give 0x0c only.
8289         uint32_t Mask = LHSMask & RHSMask;
8290         for (unsigned I = 0; I < 32; I += 8) {
8291           uint32_t ByteSel = 0xff << I;
8292           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8293             Mask &= (0x0c << I) & 0xffffffff;
8294         }
8295 
8296         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8297         // or 0x0c.
8298         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8299         SDLoc DL(N);
8300 
8301         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8302                            LHS.getOperand(0), RHS.getOperand(0),
8303                            DAG.getConstant(Sel, DL, MVT::i32));
8304       }
8305     }
8306   }
8307 
8308   return SDValue();
8309 }
8310 
8311 SDValue SITargetLowering::performOrCombine(SDNode *N,
8312                                            DAGCombinerInfo &DCI) const {
8313   SelectionDAG &DAG = DCI.DAG;
8314   SDValue LHS = N->getOperand(0);
8315   SDValue RHS = N->getOperand(1);
8316 
8317   EVT VT = N->getValueType(0);
8318   if (VT == MVT::i1) {
8319     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8320     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8321         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8322       SDValue Src = LHS.getOperand(0);
8323       if (Src != RHS.getOperand(0))
8324         return SDValue();
8325 
8326       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8327       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8328       if (!CLHS || !CRHS)
8329         return SDValue();
8330 
8331       // Only 10 bits are used.
8332       static const uint32_t MaxMask = 0x3ff;
8333 
8334       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8335       SDLoc DL(N);
8336       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8337                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8338     }
8339 
8340     return SDValue();
8341   }
8342 
8343   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8344   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8345       LHS.getOpcode() == AMDGPUISD::PERM &&
8346       isa<ConstantSDNode>(LHS.getOperand(2))) {
8347     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8348     if (!Sel)
8349       return SDValue();
8350 
8351     Sel |= LHS.getConstantOperandVal(2);
8352     SDLoc DL(N);
8353     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8354                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8355   }
8356 
8357   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8358   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8359   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8360       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8361     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8362     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8363     if (LHSMask != ~0u && RHSMask != ~0u) {
8364       // Canonicalize the expression in an attempt to have fewer unique masks
8365       // and therefore fewer registers used to hold the masks.
8366       if (LHSMask > RHSMask) {
8367         std::swap(LHSMask, RHSMask);
8368         std::swap(LHS, RHS);
8369       }
8370 
8371       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8372       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8373       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8374       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8375 
8376       // Check of we need to combine values from two sources within a byte.
8377       if (!(LHSUsedLanes & RHSUsedLanes) &&
8378           // If we select high and lower word keep it for SDWA.
8379           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8380           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8381         // Kill zero bytes selected by other mask. Zero value is 0xc.
8382         LHSMask &= ~RHSUsedLanes;
8383         RHSMask &= ~LHSUsedLanes;
8384         // Add 4 to each active LHS lane
8385         LHSMask |= LHSUsedLanes & 0x04040404;
8386         // Combine masks
8387         uint32_t Sel = LHSMask | RHSMask;
8388         SDLoc DL(N);
8389 
8390         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8391                            LHS.getOperand(0), RHS.getOperand(0),
8392                            DAG.getConstant(Sel, DL, MVT::i32));
8393       }
8394     }
8395   }
8396 
8397   if (VT != MVT::i64)
8398     return SDValue();
8399 
8400   // TODO: This could be a generic combine with a predicate for extracting the
8401   // high half of an integer being free.
8402 
8403   // (or i64:x, (zero_extend i32:y)) ->
8404   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8405   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8406       RHS.getOpcode() != ISD::ZERO_EXTEND)
8407     std::swap(LHS, RHS);
8408 
8409   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8410     SDValue ExtSrc = RHS.getOperand(0);
8411     EVT SrcVT = ExtSrc.getValueType();
8412     if (SrcVT == MVT::i32) {
8413       SDLoc SL(N);
8414       SDValue LowLHS, HiBits;
8415       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8416       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8417 
8418       DCI.AddToWorklist(LowOr.getNode());
8419       DCI.AddToWorklist(HiBits.getNode());
8420 
8421       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8422                                 LowOr, HiBits);
8423       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8424     }
8425   }
8426 
8427   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8428   if (CRHS) {
8429     if (SDValue Split
8430           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8431       return Split;
8432   }
8433 
8434   return SDValue();
8435 }
8436 
8437 SDValue SITargetLowering::performXorCombine(SDNode *N,
8438                                             DAGCombinerInfo &DCI) const {
8439   EVT VT = N->getValueType(0);
8440   if (VT != MVT::i64)
8441     return SDValue();
8442 
8443   SDValue LHS = N->getOperand(0);
8444   SDValue RHS = N->getOperand(1);
8445 
8446   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8447   if (CRHS) {
8448     if (SDValue Split
8449           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8450       return Split;
8451   }
8452 
8453   return SDValue();
8454 }
8455 
8456 // Instructions that will be lowered with a final instruction that zeros the
8457 // high result bits.
8458 // XXX - probably only need to list legal operations.
8459 static bool fp16SrcZerosHighBits(unsigned Opc) {
8460   switch (Opc) {
8461   case ISD::FADD:
8462   case ISD::FSUB:
8463   case ISD::FMUL:
8464   case ISD::FDIV:
8465   case ISD::FREM:
8466   case ISD::FMA:
8467   case ISD::FMAD:
8468   case ISD::FCANONICALIZE:
8469   case ISD::FP_ROUND:
8470   case ISD::UINT_TO_FP:
8471   case ISD::SINT_TO_FP:
8472   case ISD::FABS:
8473     // Fabs is lowered to a bit operation, but it's an and which will clear the
8474     // high bits anyway.
8475   case ISD::FSQRT:
8476   case ISD::FSIN:
8477   case ISD::FCOS:
8478   case ISD::FPOWI:
8479   case ISD::FPOW:
8480   case ISD::FLOG:
8481   case ISD::FLOG2:
8482   case ISD::FLOG10:
8483   case ISD::FEXP:
8484   case ISD::FEXP2:
8485   case ISD::FCEIL:
8486   case ISD::FTRUNC:
8487   case ISD::FRINT:
8488   case ISD::FNEARBYINT:
8489   case ISD::FROUND:
8490   case ISD::FFLOOR:
8491   case ISD::FMINNUM:
8492   case ISD::FMAXNUM:
8493   case AMDGPUISD::FRACT:
8494   case AMDGPUISD::CLAMP:
8495   case AMDGPUISD::COS_HW:
8496   case AMDGPUISD::SIN_HW:
8497   case AMDGPUISD::FMIN3:
8498   case AMDGPUISD::FMAX3:
8499   case AMDGPUISD::FMED3:
8500   case AMDGPUISD::FMAD_FTZ:
8501   case AMDGPUISD::RCP:
8502   case AMDGPUISD::RSQ:
8503   case AMDGPUISD::RCP_IFLAG:
8504   case AMDGPUISD::LDEXP:
8505     return true;
8506   default:
8507     // fcopysign, select and others may be lowered to 32-bit bit operations
8508     // which don't zero the high bits.
8509     return false;
8510   }
8511 }
8512 
8513 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8514                                                    DAGCombinerInfo &DCI) const {
8515   if (!Subtarget->has16BitInsts() ||
8516       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8517     return SDValue();
8518 
8519   EVT VT = N->getValueType(0);
8520   if (VT != MVT::i32)
8521     return SDValue();
8522 
8523   SDValue Src = N->getOperand(0);
8524   if (Src.getValueType() != MVT::i16)
8525     return SDValue();
8526 
8527   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8528   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8529   if (Src.getOpcode() == ISD::BITCAST) {
8530     SDValue BCSrc = Src.getOperand(0);
8531     if (BCSrc.getValueType() == MVT::f16 &&
8532         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8533       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8534   }
8535 
8536   return SDValue();
8537 }
8538 
8539 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8540                                                         DAGCombinerInfo &DCI)
8541                                                         const {
8542   SDValue Src = N->getOperand(0);
8543   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8544 
8545   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8546       VTSign->getVT() == MVT::i8) ||
8547       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8548       VTSign->getVT() == MVT::i16)) &&
8549       Src.hasOneUse()) {
8550     auto *M = cast<MemSDNode>(Src);
8551     SDValue Ops[] = {
8552       Src.getOperand(0), // Chain
8553       Src.getOperand(1), // rsrc
8554       Src.getOperand(2), // vindex
8555       Src.getOperand(3), // voffset
8556       Src.getOperand(4), // soffset
8557       Src.getOperand(5), // offset
8558       Src.getOperand(6),
8559       Src.getOperand(7)
8560     };
8561     // replace with BUFFER_LOAD_BYTE/SHORT
8562     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8563                                          Src.getOperand(0).getValueType());
8564     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8565                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8566     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8567                                                           ResList,
8568                                                           Ops, M->getMemoryVT(),
8569                                                           M->getMemOperand());
8570     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8571                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8572   }
8573   return SDValue();
8574 }
8575 
8576 SDValue SITargetLowering::performClassCombine(SDNode *N,
8577                                               DAGCombinerInfo &DCI) const {
8578   SelectionDAG &DAG = DCI.DAG;
8579   SDValue Mask = N->getOperand(1);
8580 
8581   // fp_class x, 0 -> false
8582   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8583     if (CMask->isNullValue())
8584       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8585   }
8586 
8587   if (N->getOperand(0).isUndef())
8588     return DAG.getUNDEF(MVT::i1);
8589 
8590   return SDValue();
8591 }
8592 
8593 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8594                                             DAGCombinerInfo &DCI) const {
8595   EVT VT = N->getValueType(0);
8596   SDValue N0 = N->getOperand(0);
8597 
8598   if (N0.isUndef())
8599     return N0;
8600 
8601   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8602                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8603     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8604                            N->getFlags());
8605   }
8606 
8607   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
8608     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
8609                            N0.getOperand(0), N->getFlags());
8610   }
8611 
8612   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8613 }
8614 
8615 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8616                                        unsigned MaxDepth) const {
8617   unsigned Opcode = Op.getOpcode();
8618   if (Opcode == ISD::FCANONICALIZE)
8619     return true;
8620 
8621   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8622     auto F = CFP->getValueAPF();
8623     if (F.isNaN() && F.isSignaling())
8624       return false;
8625     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
8626   }
8627 
8628   // If source is a result of another standard FP operation it is already in
8629   // canonical form.
8630   if (MaxDepth == 0)
8631     return false;
8632 
8633   switch (Opcode) {
8634   // These will flush denorms if required.
8635   case ISD::FADD:
8636   case ISD::FSUB:
8637   case ISD::FMUL:
8638   case ISD::FCEIL:
8639   case ISD::FFLOOR:
8640   case ISD::FMA:
8641   case ISD::FMAD:
8642   case ISD::FSQRT:
8643   case ISD::FDIV:
8644   case ISD::FREM:
8645   case ISD::FP_ROUND:
8646   case ISD::FP_EXTEND:
8647   case AMDGPUISD::FMUL_LEGACY:
8648   case AMDGPUISD::FMAD_FTZ:
8649   case AMDGPUISD::RCP:
8650   case AMDGPUISD::RSQ:
8651   case AMDGPUISD::RSQ_CLAMP:
8652   case AMDGPUISD::RCP_LEGACY:
8653   case AMDGPUISD::RSQ_LEGACY:
8654   case AMDGPUISD::RCP_IFLAG:
8655   case AMDGPUISD::TRIG_PREOP:
8656   case AMDGPUISD::DIV_SCALE:
8657   case AMDGPUISD::DIV_FMAS:
8658   case AMDGPUISD::DIV_FIXUP:
8659   case AMDGPUISD::FRACT:
8660   case AMDGPUISD::LDEXP:
8661   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8662   case AMDGPUISD::CVT_F32_UBYTE0:
8663   case AMDGPUISD::CVT_F32_UBYTE1:
8664   case AMDGPUISD::CVT_F32_UBYTE2:
8665   case AMDGPUISD::CVT_F32_UBYTE3:
8666     return true;
8667 
8668   // It can/will be lowered or combined as a bit operation.
8669   // Need to check their input recursively to handle.
8670   case ISD::FNEG:
8671   case ISD::FABS:
8672   case ISD::FCOPYSIGN:
8673     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8674 
8675   case ISD::FSIN:
8676   case ISD::FCOS:
8677   case ISD::FSINCOS:
8678     return Op.getValueType().getScalarType() != MVT::f16;
8679 
8680   case ISD::FMINNUM:
8681   case ISD::FMAXNUM:
8682   case ISD::FMINNUM_IEEE:
8683   case ISD::FMAXNUM_IEEE:
8684   case AMDGPUISD::CLAMP:
8685   case AMDGPUISD::FMED3:
8686   case AMDGPUISD::FMAX3:
8687   case AMDGPUISD::FMIN3: {
8688     // FIXME: Shouldn't treat the generic operations different based these.
8689     // However, we aren't really required to flush the result from
8690     // minnum/maxnum..
8691 
8692     // snans will be quieted, so we only need to worry about denormals.
8693     if (Subtarget->supportsMinMaxDenormModes() ||
8694         denormalsEnabledForType(DAG, Op.getValueType()))
8695       return true;
8696 
8697     // Flushing may be required.
8698     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8699     // targets need to check their input recursively.
8700 
8701     // FIXME: Does this apply with clamp? It's implemented with max.
8702     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8703       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8704         return false;
8705     }
8706 
8707     return true;
8708   }
8709   case ISD::SELECT: {
8710     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8711            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8712   }
8713   case ISD::BUILD_VECTOR: {
8714     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8715       SDValue SrcOp = Op.getOperand(i);
8716       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8717         return false;
8718     }
8719 
8720     return true;
8721   }
8722   case ISD::EXTRACT_VECTOR_ELT:
8723   case ISD::EXTRACT_SUBVECTOR: {
8724     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8725   }
8726   case ISD::INSERT_VECTOR_ELT: {
8727     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8728            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8729   }
8730   case ISD::UNDEF:
8731     // Could be anything.
8732     return false;
8733 
8734   case ISD::BITCAST: {
8735     // Hack round the mess we make when legalizing extract_vector_elt
8736     SDValue Src = Op.getOperand(0);
8737     if (Src.getValueType() == MVT::i16 &&
8738         Src.getOpcode() == ISD::TRUNCATE) {
8739       SDValue TruncSrc = Src.getOperand(0);
8740       if (TruncSrc.getValueType() == MVT::i32 &&
8741           TruncSrc.getOpcode() == ISD::BITCAST &&
8742           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8743         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8744       }
8745     }
8746 
8747     return false;
8748   }
8749   case ISD::INTRINSIC_WO_CHAIN: {
8750     unsigned IntrinsicID
8751       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8752     // TODO: Handle more intrinsics
8753     switch (IntrinsicID) {
8754     case Intrinsic::amdgcn_cvt_pkrtz:
8755     case Intrinsic::amdgcn_cubeid:
8756     case Intrinsic::amdgcn_frexp_mant:
8757     case Intrinsic::amdgcn_fdot2:
8758       return true;
8759     default:
8760       break;
8761     }
8762 
8763     LLVM_FALLTHROUGH;
8764   }
8765   default:
8766     return denormalsEnabledForType(DAG, Op.getValueType()) &&
8767            DAG.isKnownNeverSNaN(Op);
8768   }
8769 
8770   llvm_unreachable("invalid operation");
8771 }
8772 
8773 // Constant fold canonicalize.
8774 SDValue SITargetLowering::getCanonicalConstantFP(
8775   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8776   // Flush denormals to 0 if not enabled.
8777   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
8778     return DAG.getConstantFP(0.0, SL, VT);
8779 
8780   if (C.isNaN()) {
8781     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8782     if (C.isSignaling()) {
8783       // Quiet a signaling NaN.
8784       // FIXME: Is this supposed to preserve payload bits?
8785       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8786     }
8787 
8788     // Make sure it is the canonical NaN bitpattern.
8789     //
8790     // TODO: Can we use -1 as the canonical NaN value since it's an inline
8791     // immediate?
8792     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8793       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8794   }
8795 
8796   // Already canonical.
8797   return DAG.getConstantFP(C, SL, VT);
8798 }
8799 
8800 static bool vectorEltWillFoldAway(SDValue Op) {
8801   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8802 }
8803 
8804 SDValue SITargetLowering::performFCanonicalizeCombine(
8805   SDNode *N,
8806   DAGCombinerInfo &DCI) const {
8807   SelectionDAG &DAG = DCI.DAG;
8808   SDValue N0 = N->getOperand(0);
8809   EVT VT = N->getValueType(0);
8810 
8811   // fcanonicalize undef -> qnan
8812   if (N0.isUndef()) {
8813     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
8814     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8815   }
8816 
8817   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
8818     EVT VT = N->getValueType(0);
8819     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
8820   }
8821 
8822   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8823   //                                                   (fcanonicalize k)
8824   //
8825   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8826 
8827   // TODO: This could be better with wider vectors that will be split to v2f16,
8828   // and to consider uses since there aren't that many packed operations.
8829   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8830       isTypeLegal(MVT::v2f16)) {
8831     SDLoc SL(N);
8832     SDValue NewElts[2];
8833     SDValue Lo = N0.getOperand(0);
8834     SDValue Hi = N0.getOperand(1);
8835     EVT EltVT = Lo.getValueType();
8836 
8837     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
8838       for (unsigned I = 0; I != 2; ++I) {
8839         SDValue Op = N0.getOperand(I);
8840         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8841           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8842                                               CFP->getValueAPF());
8843         } else if (Op.isUndef()) {
8844           // Handled below based on what the other operand is.
8845           NewElts[I] = Op;
8846         } else {
8847           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8848         }
8849       }
8850 
8851       // If one half is undef, and one is constant, perfer a splat vector rather
8852       // than the normal qNaN. If it's a register, prefer 0.0 since that's
8853       // cheaper to use and may be free with a packed operation.
8854       if (NewElts[0].isUndef()) {
8855         if (isa<ConstantFPSDNode>(NewElts[1]))
8856           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8857             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8858       }
8859 
8860       if (NewElts[1].isUndef()) {
8861         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8862           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8863       }
8864 
8865       return DAG.getBuildVector(VT, SL, NewElts);
8866     }
8867   }
8868 
8869   unsigned SrcOpc = N0.getOpcode();
8870 
8871   // If it's free to do so, push canonicalizes further up the source, which may
8872   // find a canonical source.
8873   //
8874   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
8875   // sNaNs.
8876   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
8877     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8878     if (CRHS && N0.hasOneUse()) {
8879       SDLoc SL(N);
8880       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
8881                                    N0.getOperand(0));
8882       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
8883       DCI.AddToWorklist(Canon0.getNode());
8884 
8885       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
8886     }
8887   }
8888 
8889   return isCanonicalized(DAG, N0) ? N0 : SDValue();
8890 }
8891 
8892 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
8893   switch (Opc) {
8894   case ISD::FMAXNUM:
8895   case ISD::FMAXNUM_IEEE:
8896     return AMDGPUISD::FMAX3;
8897   case ISD::SMAX:
8898     return AMDGPUISD::SMAX3;
8899   case ISD::UMAX:
8900     return AMDGPUISD::UMAX3;
8901   case ISD::FMINNUM:
8902   case ISD::FMINNUM_IEEE:
8903     return AMDGPUISD::FMIN3;
8904   case ISD::SMIN:
8905     return AMDGPUISD::SMIN3;
8906   case ISD::UMIN:
8907     return AMDGPUISD::UMIN3;
8908   default:
8909     llvm_unreachable("Not a min/max opcode");
8910   }
8911 }
8912 
8913 SDValue SITargetLowering::performIntMed3ImmCombine(
8914   SelectionDAG &DAG, const SDLoc &SL,
8915   SDValue Op0, SDValue Op1, bool Signed) const {
8916   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
8917   if (!K1)
8918     return SDValue();
8919 
8920   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
8921   if (!K0)
8922     return SDValue();
8923 
8924   if (Signed) {
8925     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
8926       return SDValue();
8927   } else {
8928     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
8929       return SDValue();
8930   }
8931 
8932   EVT VT = K0->getValueType(0);
8933   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
8934   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
8935     return DAG.getNode(Med3Opc, SL, VT,
8936                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
8937   }
8938 
8939   // If there isn't a 16-bit med3 operation, convert to 32-bit.
8940   MVT NVT = MVT::i32;
8941   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8942 
8943   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
8944   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
8945   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
8946 
8947   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
8948   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
8949 }
8950 
8951 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
8952   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
8953     return C;
8954 
8955   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
8956     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
8957       return C;
8958   }
8959 
8960   return nullptr;
8961 }
8962 
8963 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
8964                                                   const SDLoc &SL,
8965                                                   SDValue Op0,
8966                                                   SDValue Op1) const {
8967   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
8968   if (!K1)
8969     return SDValue();
8970 
8971   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
8972   if (!K0)
8973     return SDValue();
8974 
8975   // Ordered >= (although NaN inputs should have folded away by now).
8976   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
8977   if (Cmp == APFloat::cmpGreaterThan)
8978     return SDValue();
8979 
8980   const MachineFunction &MF = DAG.getMachineFunction();
8981   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8982 
8983   // TODO: Check IEEE bit enabled?
8984   EVT VT = Op0.getValueType();
8985   if (Info->getMode().DX10Clamp) {
8986     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
8987     // hardware fmed3 behavior converting to a min.
8988     // FIXME: Should this be allowing -0.0?
8989     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
8990       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
8991   }
8992 
8993   // med3 for f16 is only available on gfx9+, and not available for v2f16.
8994   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
8995     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
8996     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
8997     // then give the other result, which is different from med3 with a NaN
8998     // input.
8999     SDValue Var = Op0.getOperand(0);
9000     if (!DAG.isKnownNeverSNaN(Var))
9001       return SDValue();
9002 
9003     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9004 
9005     if ((!K0->hasOneUse() ||
9006          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9007         (!K1->hasOneUse() ||
9008          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9009       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9010                          Var, SDValue(K0, 0), SDValue(K1, 0));
9011     }
9012   }
9013 
9014   return SDValue();
9015 }
9016 
9017 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9018                                                DAGCombinerInfo &DCI) const {
9019   SelectionDAG &DAG = DCI.DAG;
9020 
9021   EVT VT = N->getValueType(0);
9022   unsigned Opc = N->getOpcode();
9023   SDValue Op0 = N->getOperand(0);
9024   SDValue Op1 = N->getOperand(1);
9025 
9026   // Only do this if the inner op has one use since this will just increases
9027   // register pressure for no benefit.
9028 
9029   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9030       !VT.isVector() &&
9031       (VT == MVT::i32 || VT == MVT::f32 ||
9032        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9033     // max(max(a, b), c) -> max3(a, b, c)
9034     // min(min(a, b), c) -> min3(a, b, c)
9035     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9036       SDLoc DL(N);
9037       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9038                          DL,
9039                          N->getValueType(0),
9040                          Op0.getOperand(0),
9041                          Op0.getOperand(1),
9042                          Op1);
9043     }
9044 
9045     // Try commuted.
9046     // max(a, max(b, c)) -> max3(a, b, c)
9047     // min(a, min(b, c)) -> min3(a, b, c)
9048     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9049       SDLoc DL(N);
9050       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9051                          DL,
9052                          N->getValueType(0),
9053                          Op0,
9054                          Op1.getOperand(0),
9055                          Op1.getOperand(1));
9056     }
9057   }
9058 
9059   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9060   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9061     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9062       return Med3;
9063   }
9064 
9065   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9066     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9067       return Med3;
9068   }
9069 
9070   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9071   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9072        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9073        (Opc == AMDGPUISD::FMIN_LEGACY &&
9074         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9075       (VT == MVT::f32 || VT == MVT::f64 ||
9076        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9077        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9078       Op0.hasOneUse()) {
9079     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9080       return Res;
9081   }
9082 
9083   return SDValue();
9084 }
9085 
9086 static bool isClampZeroToOne(SDValue A, SDValue B) {
9087   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9088     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9089       // FIXME: Should this be allowing -0.0?
9090       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9091              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9092     }
9093   }
9094 
9095   return false;
9096 }
9097 
9098 // FIXME: Should only worry about snans for version with chain.
9099 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9100                                               DAGCombinerInfo &DCI) const {
9101   EVT VT = N->getValueType(0);
9102   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9103   // NaNs. With a NaN input, the order of the operands may change the result.
9104 
9105   SelectionDAG &DAG = DCI.DAG;
9106   SDLoc SL(N);
9107 
9108   SDValue Src0 = N->getOperand(0);
9109   SDValue Src1 = N->getOperand(1);
9110   SDValue Src2 = N->getOperand(2);
9111 
9112   if (isClampZeroToOne(Src0, Src1)) {
9113     // const_a, const_b, x -> clamp is safe in all cases including signaling
9114     // nans.
9115     // FIXME: Should this be allowing -0.0?
9116     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9117   }
9118 
9119   const MachineFunction &MF = DAG.getMachineFunction();
9120   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9121 
9122   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9123   // handling no dx10-clamp?
9124   if (Info->getMode().DX10Clamp) {
9125     // If NaNs is clamped to 0, we are free to reorder the inputs.
9126 
9127     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9128       std::swap(Src0, Src1);
9129 
9130     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9131       std::swap(Src1, Src2);
9132 
9133     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9134       std::swap(Src0, Src1);
9135 
9136     if (isClampZeroToOne(Src1, Src2))
9137       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9138   }
9139 
9140   return SDValue();
9141 }
9142 
9143 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9144                                                  DAGCombinerInfo &DCI) const {
9145   SDValue Src0 = N->getOperand(0);
9146   SDValue Src1 = N->getOperand(1);
9147   if (Src0.isUndef() && Src1.isUndef())
9148     return DCI.DAG.getUNDEF(N->getValueType(0));
9149   return SDValue();
9150 }
9151 
9152 SDValue SITargetLowering::performExtractVectorEltCombine(
9153   SDNode *N, DAGCombinerInfo &DCI) const {
9154   SDValue Vec = N->getOperand(0);
9155   SelectionDAG &DAG = DCI.DAG;
9156 
9157   EVT VecVT = Vec.getValueType();
9158   EVT EltVT = VecVT.getVectorElementType();
9159 
9160   if ((Vec.getOpcode() == ISD::FNEG ||
9161        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9162     SDLoc SL(N);
9163     EVT EltVT = N->getValueType(0);
9164     SDValue Idx = N->getOperand(1);
9165     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9166                               Vec.getOperand(0), Idx);
9167     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9168   }
9169 
9170   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9171   //    =>
9172   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9173   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9174   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9175   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9176     SDLoc SL(N);
9177     EVT EltVT = N->getValueType(0);
9178     SDValue Idx = N->getOperand(1);
9179     unsigned Opc = Vec.getOpcode();
9180 
9181     switch(Opc) {
9182     default:
9183       break;
9184       // TODO: Support other binary operations.
9185     case ISD::FADD:
9186     case ISD::FSUB:
9187     case ISD::FMUL:
9188     case ISD::ADD:
9189     case ISD::UMIN:
9190     case ISD::UMAX:
9191     case ISD::SMIN:
9192     case ISD::SMAX:
9193     case ISD::FMAXNUM:
9194     case ISD::FMINNUM:
9195     case ISD::FMAXNUM_IEEE:
9196     case ISD::FMINNUM_IEEE: {
9197       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9198                                  Vec.getOperand(0), Idx);
9199       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9200                                  Vec.getOperand(1), Idx);
9201 
9202       DCI.AddToWorklist(Elt0.getNode());
9203       DCI.AddToWorklist(Elt1.getNode());
9204       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9205     }
9206     }
9207   }
9208 
9209   unsigned VecSize = VecVT.getSizeInBits();
9210   unsigned EltSize = EltVT.getSizeInBits();
9211 
9212   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9213   // This elminates non-constant index and subsequent movrel or scratch access.
9214   // Sub-dword vectors of size 2 dword or less have better implementation.
9215   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9216   // instructions.
9217   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
9218       !isa<ConstantSDNode>(N->getOperand(1))) {
9219     SDLoc SL(N);
9220     SDValue Idx = N->getOperand(1);
9221     SDValue V;
9222     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9223       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9224       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9225       if (I == 0)
9226         V = Elt;
9227       else
9228         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9229     }
9230     return V;
9231   }
9232 
9233   if (!DCI.isBeforeLegalize())
9234     return SDValue();
9235 
9236   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9237   // elements. This exposes more load reduction opportunities by replacing
9238   // multiple small extract_vector_elements with a single 32-bit extract.
9239   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9240   if (isa<MemSDNode>(Vec) &&
9241       EltSize <= 16 &&
9242       EltVT.isByteSized() &&
9243       VecSize > 32 &&
9244       VecSize % 32 == 0 &&
9245       Idx) {
9246     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9247 
9248     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9249     unsigned EltIdx = BitIndex / 32;
9250     unsigned LeftoverBitIdx = BitIndex % 32;
9251     SDLoc SL(N);
9252 
9253     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9254     DCI.AddToWorklist(Cast.getNode());
9255 
9256     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9257                               DAG.getConstant(EltIdx, SL, MVT::i32));
9258     DCI.AddToWorklist(Elt.getNode());
9259     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9260                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9261     DCI.AddToWorklist(Srl.getNode());
9262 
9263     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9264     DCI.AddToWorklist(Trunc.getNode());
9265     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9266   }
9267 
9268   return SDValue();
9269 }
9270 
9271 SDValue
9272 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9273                                                 DAGCombinerInfo &DCI) const {
9274   SDValue Vec = N->getOperand(0);
9275   SDValue Idx = N->getOperand(2);
9276   EVT VecVT = Vec.getValueType();
9277   EVT EltVT = VecVT.getVectorElementType();
9278   unsigned VecSize = VecVT.getSizeInBits();
9279   unsigned EltSize = EltVT.getSizeInBits();
9280 
9281   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9282   // => BUILD_VECTOR n x select (e, const-idx)
9283   // This elminates non-constant index and subsequent movrel or scratch access.
9284   // Sub-dword vectors of size 2 dword or less have better implementation.
9285   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
9286   // instructions.
9287   if (isa<ConstantSDNode>(Idx) ||
9288       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
9289     return SDValue();
9290 
9291   SelectionDAG &DAG = DCI.DAG;
9292   SDLoc SL(N);
9293   SDValue Ins = N->getOperand(1);
9294   EVT IdxVT = Idx.getValueType();
9295 
9296   SmallVector<SDValue, 16> Ops;
9297   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9298     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9299     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9300     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9301     Ops.push_back(V);
9302   }
9303 
9304   return DAG.getBuildVector(VecVT, SL, Ops);
9305 }
9306 
9307 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9308                                           const SDNode *N0,
9309                                           const SDNode *N1) const {
9310   EVT VT = N0->getValueType(0);
9311 
9312   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9313   // support denormals ever.
9314   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9315        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9316         getSubtarget()->hasMadF16())) &&
9317        isOperationLegal(ISD::FMAD, VT))
9318     return ISD::FMAD;
9319 
9320   const TargetOptions &Options = DAG.getTarget().Options;
9321   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9322        (N0->getFlags().hasAllowContract() &&
9323         N1->getFlags().hasAllowContract())) &&
9324       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9325     return ISD::FMA;
9326   }
9327 
9328   return 0;
9329 }
9330 
9331 // For a reassociatable opcode perform:
9332 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9333 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9334                                                SelectionDAG &DAG) const {
9335   EVT VT = N->getValueType(0);
9336   if (VT != MVT::i32 && VT != MVT::i64)
9337     return SDValue();
9338 
9339   unsigned Opc = N->getOpcode();
9340   SDValue Op0 = N->getOperand(0);
9341   SDValue Op1 = N->getOperand(1);
9342 
9343   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9344     return SDValue();
9345 
9346   if (Op0->isDivergent())
9347     std::swap(Op0, Op1);
9348 
9349   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9350     return SDValue();
9351 
9352   SDValue Op2 = Op1.getOperand(1);
9353   Op1 = Op1.getOperand(0);
9354   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9355     return SDValue();
9356 
9357   if (Op1->isDivergent())
9358     std::swap(Op1, Op2);
9359 
9360   // If either operand is constant this will conflict with
9361   // DAGCombiner::ReassociateOps().
9362   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9363       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9364     return SDValue();
9365 
9366   SDLoc SL(N);
9367   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9368   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9369 }
9370 
9371 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9372                            EVT VT,
9373                            SDValue N0, SDValue N1, SDValue N2,
9374                            bool Signed) {
9375   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9376   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9377   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9378   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9379 }
9380 
9381 SDValue SITargetLowering::performAddCombine(SDNode *N,
9382                                             DAGCombinerInfo &DCI) const {
9383   SelectionDAG &DAG = DCI.DAG;
9384   EVT VT = N->getValueType(0);
9385   SDLoc SL(N);
9386   SDValue LHS = N->getOperand(0);
9387   SDValue RHS = N->getOperand(1);
9388 
9389   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9390       && Subtarget->hasMad64_32() &&
9391       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9392       VT.getScalarSizeInBits() <= 64) {
9393     if (LHS.getOpcode() != ISD::MUL)
9394       std::swap(LHS, RHS);
9395 
9396     SDValue MulLHS = LHS.getOperand(0);
9397     SDValue MulRHS = LHS.getOperand(1);
9398     SDValue AddRHS = RHS;
9399 
9400     // TODO: Maybe restrict if SGPR inputs.
9401     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9402         numBitsUnsigned(MulRHS, DAG) <= 32) {
9403       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9404       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9405       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9406       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9407     }
9408 
9409     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9410       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9411       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9412       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9413       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9414     }
9415 
9416     return SDValue();
9417   }
9418 
9419   if (SDValue V = reassociateScalarOps(N, DAG)) {
9420     return V;
9421   }
9422 
9423   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9424     return SDValue();
9425 
9426   // add x, zext (setcc) => addcarry x, 0, setcc
9427   // add x, sext (setcc) => subcarry x, 0, setcc
9428   unsigned Opc = LHS.getOpcode();
9429   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9430       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9431     std::swap(RHS, LHS);
9432 
9433   Opc = RHS.getOpcode();
9434   switch (Opc) {
9435   default: break;
9436   case ISD::ZERO_EXTEND:
9437   case ISD::SIGN_EXTEND:
9438   case ISD::ANY_EXTEND: {
9439     auto Cond = RHS.getOperand(0);
9440     // If this won't be a real VOPC output, we would still need to insert an
9441     // extra instruction anyway.
9442     if (!isBoolSGPR(Cond))
9443       break;
9444     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9445     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9446     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9447     return DAG.getNode(Opc, SL, VTList, Args);
9448   }
9449   case ISD::ADDCARRY: {
9450     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9451     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9452     if (!C || C->getZExtValue() != 0) break;
9453     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9454     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9455   }
9456   }
9457   return SDValue();
9458 }
9459 
9460 SDValue SITargetLowering::performSubCombine(SDNode *N,
9461                                             DAGCombinerInfo &DCI) const {
9462   SelectionDAG &DAG = DCI.DAG;
9463   EVT VT = N->getValueType(0);
9464 
9465   if (VT != MVT::i32)
9466     return SDValue();
9467 
9468   SDLoc SL(N);
9469   SDValue LHS = N->getOperand(0);
9470   SDValue RHS = N->getOperand(1);
9471 
9472   // sub x, zext (setcc) => subcarry x, 0, setcc
9473   // sub x, sext (setcc) => addcarry x, 0, setcc
9474   unsigned Opc = RHS.getOpcode();
9475   switch (Opc) {
9476   default: break;
9477   case ISD::ZERO_EXTEND:
9478   case ISD::SIGN_EXTEND:
9479   case ISD::ANY_EXTEND: {
9480     auto Cond = RHS.getOperand(0);
9481     // If this won't be a real VOPC output, we would still need to insert an
9482     // extra instruction anyway.
9483     if (!isBoolSGPR(Cond))
9484       break;
9485     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9486     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9487     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
9488     return DAG.getNode(Opc, SL, VTList, Args);
9489   }
9490   }
9491 
9492   if (LHS.getOpcode() == ISD::SUBCARRY) {
9493     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9494     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9495     if (!C || !C->isNullValue())
9496       return SDValue();
9497     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9498     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9499   }
9500   return SDValue();
9501 }
9502 
9503 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9504   DAGCombinerInfo &DCI) const {
9505 
9506   if (N->getValueType(0) != MVT::i32)
9507     return SDValue();
9508 
9509   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9510   if (!C || C->getZExtValue() != 0)
9511     return SDValue();
9512 
9513   SelectionDAG &DAG = DCI.DAG;
9514   SDValue LHS = N->getOperand(0);
9515 
9516   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9517   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9518   unsigned LHSOpc = LHS.getOpcode();
9519   unsigned Opc = N->getOpcode();
9520   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9521       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9522     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9523     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9524   }
9525   return SDValue();
9526 }
9527 
9528 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9529                                              DAGCombinerInfo &DCI) const {
9530   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9531     return SDValue();
9532 
9533   SelectionDAG &DAG = DCI.DAG;
9534   EVT VT = N->getValueType(0);
9535 
9536   SDLoc SL(N);
9537   SDValue LHS = N->getOperand(0);
9538   SDValue RHS = N->getOperand(1);
9539 
9540   // These should really be instruction patterns, but writing patterns with
9541   // source modiifiers is a pain.
9542 
9543   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9544   if (LHS.getOpcode() == ISD::FADD) {
9545     SDValue A = LHS.getOperand(0);
9546     if (A == LHS.getOperand(1)) {
9547       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9548       if (FusedOp != 0) {
9549         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9550         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9551       }
9552     }
9553   }
9554 
9555   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9556   if (RHS.getOpcode() == ISD::FADD) {
9557     SDValue A = RHS.getOperand(0);
9558     if (A == RHS.getOperand(1)) {
9559       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9560       if (FusedOp != 0) {
9561         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9562         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9563       }
9564     }
9565   }
9566 
9567   return SDValue();
9568 }
9569 
9570 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9571                                              DAGCombinerInfo &DCI) const {
9572   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9573     return SDValue();
9574 
9575   SelectionDAG &DAG = DCI.DAG;
9576   SDLoc SL(N);
9577   EVT VT = N->getValueType(0);
9578   assert(!VT.isVector());
9579 
9580   // Try to get the fneg to fold into the source modifier. This undoes generic
9581   // DAG combines and folds them into the mad.
9582   //
9583   // Only do this if we are not trying to support denormals. v_mad_f32 does
9584   // not support denormals ever.
9585   SDValue LHS = N->getOperand(0);
9586   SDValue RHS = N->getOperand(1);
9587   if (LHS.getOpcode() == ISD::FADD) {
9588     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9589     SDValue A = LHS.getOperand(0);
9590     if (A == LHS.getOperand(1)) {
9591       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9592       if (FusedOp != 0){
9593         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9594         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9595 
9596         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9597       }
9598     }
9599   }
9600 
9601   if (RHS.getOpcode() == ISD::FADD) {
9602     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9603 
9604     SDValue A = RHS.getOperand(0);
9605     if (A == RHS.getOperand(1)) {
9606       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9607       if (FusedOp != 0){
9608         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9609         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9610       }
9611     }
9612   }
9613 
9614   return SDValue();
9615 }
9616 
9617 SDValue SITargetLowering::performFMACombine(SDNode *N,
9618                                             DAGCombinerInfo &DCI) const {
9619   SelectionDAG &DAG = DCI.DAG;
9620   EVT VT = N->getValueType(0);
9621   SDLoc SL(N);
9622 
9623   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9624     return SDValue();
9625 
9626   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9627   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9628   SDValue Op1 = N->getOperand(0);
9629   SDValue Op2 = N->getOperand(1);
9630   SDValue FMA = N->getOperand(2);
9631 
9632   if (FMA.getOpcode() != ISD::FMA ||
9633       Op1.getOpcode() != ISD::FP_EXTEND ||
9634       Op2.getOpcode() != ISD::FP_EXTEND)
9635     return SDValue();
9636 
9637   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9638   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9639   // is sufficient to allow generaing fdot2.
9640   const TargetOptions &Options = DAG.getTarget().Options;
9641   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9642       (N->getFlags().hasAllowContract() &&
9643        FMA->getFlags().hasAllowContract())) {
9644     Op1 = Op1.getOperand(0);
9645     Op2 = Op2.getOperand(0);
9646     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9647         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9648       return SDValue();
9649 
9650     SDValue Vec1 = Op1.getOperand(0);
9651     SDValue Idx1 = Op1.getOperand(1);
9652     SDValue Vec2 = Op2.getOperand(0);
9653 
9654     SDValue FMAOp1 = FMA.getOperand(0);
9655     SDValue FMAOp2 = FMA.getOperand(1);
9656     SDValue FMAAcc = FMA.getOperand(2);
9657 
9658     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9659         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9660       return SDValue();
9661 
9662     FMAOp1 = FMAOp1.getOperand(0);
9663     FMAOp2 = FMAOp2.getOperand(0);
9664     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9665         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9666       return SDValue();
9667 
9668     SDValue Vec3 = FMAOp1.getOperand(0);
9669     SDValue Vec4 = FMAOp2.getOperand(0);
9670     SDValue Idx2 = FMAOp1.getOperand(1);
9671 
9672     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9673         // Idx1 and Idx2 cannot be the same.
9674         Idx1 == Idx2)
9675       return SDValue();
9676 
9677     if (Vec1 == Vec2 || Vec3 == Vec4)
9678       return SDValue();
9679 
9680     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9681       return SDValue();
9682 
9683     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9684         (Vec1 == Vec4 && Vec2 == Vec3)) {
9685       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9686                          DAG.getTargetConstant(0, SL, MVT::i1));
9687     }
9688   }
9689   return SDValue();
9690 }
9691 
9692 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9693                                               DAGCombinerInfo &DCI) const {
9694   SelectionDAG &DAG = DCI.DAG;
9695   SDLoc SL(N);
9696 
9697   SDValue LHS = N->getOperand(0);
9698   SDValue RHS = N->getOperand(1);
9699   EVT VT = LHS.getValueType();
9700   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9701 
9702   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9703   if (!CRHS) {
9704     CRHS = dyn_cast<ConstantSDNode>(LHS);
9705     if (CRHS) {
9706       std::swap(LHS, RHS);
9707       CC = getSetCCSwappedOperands(CC);
9708     }
9709   }
9710 
9711   if (CRHS) {
9712     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9713         isBoolSGPR(LHS.getOperand(0))) {
9714       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9715       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9716       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9717       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9718       if ((CRHS->isAllOnesValue() &&
9719            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9720           (CRHS->isNullValue() &&
9721            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9722         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9723                            DAG.getConstant(-1, SL, MVT::i1));
9724       if ((CRHS->isAllOnesValue() &&
9725            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9726           (CRHS->isNullValue() &&
9727            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9728         return LHS.getOperand(0);
9729     }
9730 
9731     uint64_t CRHSVal = CRHS->getZExtValue();
9732     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9733         LHS.getOpcode() == ISD::SELECT &&
9734         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9735         isa<ConstantSDNode>(LHS.getOperand(2)) &&
9736         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9737         isBoolSGPR(LHS.getOperand(0))) {
9738       // Given CT != FT:
9739       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9740       // setcc (select cc, CT, CF), CF, ne => cc
9741       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9742       // setcc (select cc, CT, CF), CT, eq => cc
9743       uint64_t CT = LHS.getConstantOperandVal(1);
9744       uint64_t CF = LHS.getConstantOperandVal(2);
9745 
9746       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9747           (CT == CRHSVal && CC == ISD::SETNE))
9748         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9749                            DAG.getConstant(-1, SL, MVT::i1));
9750       if ((CF == CRHSVal && CC == ISD::SETNE) ||
9751           (CT == CRHSVal && CC == ISD::SETEQ))
9752         return LHS.getOperand(0);
9753     }
9754   }
9755 
9756   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9757                                            VT != MVT::f16))
9758     return SDValue();
9759 
9760   // Match isinf/isfinite pattern
9761   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
9762   // (fcmp one (fabs x), inf) -> (fp_class x,
9763   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9764   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
9765     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9766     if (!CRHS)
9767       return SDValue();
9768 
9769     const APFloat &APF = CRHS->getValueAPF();
9770     if (APF.isInfinity() && !APF.isNegative()) {
9771       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9772                                  SIInstrFlags::N_INFINITY;
9773       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9774                                     SIInstrFlags::P_ZERO |
9775                                     SIInstrFlags::N_NORMAL |
9776                                     SIInstrFlags::P_NORMAL |
9777                                     SIInstrFlags::N_SUBNORMAL |
9778                                     SIInstrFlags::P_SUBNORMAL;
9779       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
9780       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9781                          DAG.getConstant(Mask, SL, MVT::i32));
9782     }
9783   }
9784 
9785   return SDValue();
9786 }
9787 
9788 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9789                                                      DAGCombinerInfo &DCI) const {
9790   SelectionDAG &DAG = DCI.DAG;
9791   SDLoc SL(N);
9792   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9793 
9794   SDValue Src = N->getOperand(0);
9795   SDValue Srl = N->getOperand(0);
9796   if (Srl.getOpcode() == ISD::ZERO_EXTEND)
9797     Srl = Srl.getOperand(0);
9798 
9799   // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
9800   if (Srl.getOpcode() == ISD::SRL) {
9801     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9802     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9803     // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
9804 
9805     if (const ConstantSDNode *C =
9806         dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
9807       Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
9808                                EVT(MVT::i32));
9809 
9810       unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
9811       if (SrcOffset < 32 && SrcOffset % 8 == 0) {
9812         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
9813                            MVT::f32, Srl);
9814       }
9815     }
9816   }
9817 
9818   APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9819 
9820   KnownBits Known;
9821   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9822                                         !DCI.isBeforeLegalizeOps());
9823   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9824   if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
9825     DCI.CommitTargetLoweringOpt(TLO);
9826   }
9827 
9828   return SDValue();
9829 }
9830 
9831 SDValue SITargetLowering::performClampCombine(SDNode *N,
9832                                               DAGCombinerInfo &DCI) const {
9833   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
9834   if (!CSrc)
9835     return SDValue();
9836 
9837   const MachineFunction &MF = DCI.DAG.getMachineFunction();
9838   const APFloat &F = CSrc->getValueAPF();
9839   APFloat Zero = APFloat::getZero(F.getSemantics());
9840   APFloat::cmpResult Cmp0 = F.compare(Zero);
9841   if (Cmp0 == APFloat::cmpLessThan ||
9842       (Cmp0 == APFloat::cmpUnordered &&
9843        MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
9844     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9845   }
9846 
9847   APFloat One(F.getSemantics(), "1.0");
9848   APFloat::cmpResult Cmp1 = F.compare(One);
9849   if (Cmp1 == APFloat::cmpGreaterThan)
9850     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9851 
9852   return SDValue(CSrc, 0);
9853 }
9854 
9855 
9856 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
9857                                             DAGCombinerInfo &DCI) const {
9858   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9859     return SDValue();
9860   switch (N->getOpcode()) {
9861   default:
9862     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9863   case ISD::ADD:
9864     return performAddCombine(N, DCI);
9865   case ISD::SUB:
9866     return performSubCombine(N, DCI);
9867   case ISD::ADDCARRY:
9868   case ISD::SUBCARRY:
9869     return performAddCarrySubCarryCombine(N, DCI);
9870   case ISD::FADD:
9871     return performFAddCombine(N, DCI);
9872   case ISD::FSUB:
9873     return performFSubCombine(N, DCI);
9874   case ISD::SETCC:
9875     return performSetCCCombine(N, DCI);
9876   case ISD::FMAXNUM:
9877   case ISD::FMINNUM:
9878   case ISD::FMAXNUM_IEEE:
9879   case ISD::FMINNUM_IEEE:
9880   case ISD::SMAX:
9881   case ISD::SMIN:
9882   case ISD::UMAX:
9883   case ISD::UMIN:
9884   case AMDGPUISD::FMIN_LEGACY:
9885   case AMDGPUISD::FMAX_LEGACY:
9886     return performMinMaxCombine(N, DCI);
9887   case ISD::FMA:
9888     return performFMACombine(N, DCI);
9889   case ISD::LOAD: {
9890     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
9891       return Widended;
9892     LLVM_FALLTHROUGH;
9893   }
9894   case ISD::STORE:
9895   case ISD::ATOMIC_LOAD:
9896   case ISD::ATOMIC_STORE:
9897   case ISD::ATOMIC_CMP_SWAP:
9898   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
9899   case ISD::ATOMIC_SWAP:
9900   case ISD::ATOMIC_LOAD_ADD:
9901   case ISD::ATOMIC_LOAD_SUB:
9902   case ISD::ATOMIC_LOAD_AND:
9903   case ISD::ATOMIC_LOAD_OR:
9904   case ISD::ATOMIC_LOAD_XOR:
9905   case ISD::ATOMIC_LOAD_NAND:
9906   case ISD::ATOMIC_LOAD_MIN:
9907   case ISD::ATOMIC_LOAD_MAX:
9908   case ISD::ATOMIC_LOAD_UMIN:
9909   case ISD::ATOMIC_LOAD_UMAX:
9910   case ISD::ATOMIC_LOAD_FADD:
9911   case AMDGPUISD::ATOMIC_INC:
9912   case AMDGPUISD::ATOMIC_DEC:
9913   case AMDGPUISD::ATOMIC_LOAD_FMIN:
9914   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
9915     if (DCI.isBeforeLegalize())
9916       break;
9917     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
9918   case ISD::AND:
9919     return performAndCombine(N, DCI);
9920   case ISD::OR:
9921     return performOrCombine(N, DCI);
9922   case ISD::XOR:
9923     return performXorCombine(N, DCI);
9924   case ISD::ZERO_EXTEND:
9925     return performZeroExtendCombine(N, DCI);
9926   case ISD::SIGN_EXTEND_INREG:
9927     return performSignExtendInRegCombine(N , DCI);
9928   case AMDGPUISD::FP_CLASS:
9929     return performClassCombine(N, DCI);
9930   case ISD::FCANONICALIZE:
9931     return performFCanonicalizeCombine(N, DCI);
9932   case AMDGPUISD::RCP:
9933     return performRcpCombine(N, DCI);
9934   case AMDGPUISD::FRACT:
9935   case AMDGPUISD::RSQ:
9936   case AMDGPUISD::RCP_LEGACY:
9937   case AMDGPUISD::RSQ_LEGACY:
9938   case AMDGPUISD::RCP_IFLAG:
9939   case AMDGPUISD::RSQ_CLAMP:
9940   case AMDGPUISD::LDEXP: {
9941     SDValue Src = N->getOperand(0);
9942     if (Src.isUndef())
9943       return Src;
9944     break;
9945   }
9946   case ISD::SINT_TO_FP:
9947   case ISD::UINT_TO_FP:
9948     return performUCharToFloatCombine(N, DCI);
9949   case AMDGPUISD::CVT_F32_UBYTE0:
9950   case AMDGPUISD::CVT_F32_UBYTE1:
9951   case AMDGPUISD::CVT_F32_UBYTE2:
9952   case AMDGPUISD::CVT_F32_UBYTE3:
9953     return performCvtF32UByteNCombine(N, DCI);
9954   case AMDGPUISD::FMED3:
9955     return performFMed3Combine(N, DCI);
9956   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9957     return performCvtPkRTZCombine(N, DCI);
9958   case AMDGPUISD::CLAMP:
9959     return performClampCombine(N, DCI);
9960   case ISD::SCALAR_TO_VECTOR: {
9961     SelectionDAG &DAG = DCI.DAG;
9962     EVT VT = N->getValueType(0);
9963 
9964     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
9965     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
9966       SDLoc SL(N);
9967       SDValue Src = N->getOperand(0);
9968       EVT EltVT = Src.getValueType();
9969       if (EltVT == MVT::f16)
9970         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
9971 
9972       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
9973       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
9974     }
9975 
9976     break;
9977   }
9978   case ISD::EXTRACT_VECTOR_ELT:
9979     return performExtractVectorEltCombine(N, DCI);
9980   case ISD::INSERT_VECTOR_ELT:
9981     return performInsertVectorEltCombine(N, DCI);
9982   }
9983   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9984 }
9985 
9986 /// Helper function for adjustWritemask
9987 static unsigned SubIdx2Lane(unsigned Idx) {
9988   switch (Idx) {
9989   default: return 0;
9990   case AMDGPU::sub0: return 0;
9991   case AMDGPU::sub1: return 1;
9992   case AMDGPU::sub2: return 2;
9993   case AMDGPU::sub3: return 3;
9994   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
9995   }
9996 }
9997 
9998 /// Adjust the writemask of MIMG instructions
9999 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10000                                           SelectionDAG &DAG) const {
10001   unsigned Opcode = Node->getMachineOpcode();
10002 
10003   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10004   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10005   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10006     return Node; // not implemented for D16
10007 
10008   SDNode *Users[5] = { nullptr };
10009   unsigned Lane = 0;
10010   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10011   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10012   unsigned NewDmask = 0;
10013   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10014   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10015   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10016                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10017   unsigned TFCLane = 0;
10018   bool HasChain = Node->getNumValues() > 1;
10019 
10020   if (OldDmask == 0) {
10021     // These are folded out, but on the chance it happens don't assert.
10022     return Node;
10023   }
10024 
10025   unsigned OldBitsSet = countPopulation(OldDmask);
10026   // Work out which is the TFE/LWE lane if that is enabled.
10027   if (UsesTFC) {
10028     TFCLane = OldBitsSet;
10029   }
10030 
10031   // Try to figure out the used register components
10032   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10033        I != E; ++I) {
10034 
10035     // Don't look at users of the chain.
10036     if (I.getUse().getResNo() != 0)
10037       continue;
10038 
10039     // Abort if we can't understand the usage
10040     if (!I->isMachineOpcode() ||
10041         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10042       return Node;
10043 
10044     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10045     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10046     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10047     // set, etc.
10048     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10049 
10050     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10051     if (UsesTFC && Lane == TFCLane) {
10052       Users[Lane] = *I;
10053     } else {
10054       // Set which texture component corresponds to the lane.
10055       unsigned Comp;
10056       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10057         Comp = countTrailingZeros(Dmask);
10058         Dmask &= ~(1 << Comp);
10059       }
10060 
10061       // Abort if we have more than one user per component.
10062       if (Users[Lane])
10063         return Node;
10064 
10065       Users[Lane] = *I;
10066       NewDmask |= 1 << Comp;
10067     }
10068   }
10069 
10070   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10071   bool NoChannels = !NewDmask;
10072   if (NoChannels) {
10073     if (!UsesTFC) {
10074       // No uses of the result and not using TFC. Then do nothing.
10075       return Node;
10076     }
10077     // If the original dmask has one channel - then nothing to do
10078     if (OldBitsSet == 1)
10079       return Node;
10080     // Use an arbitrary dmask - required for the instruction to work
10081     NewDmask = 1;
10082   }
10083   // Abort if there's no change
10084   if (NewDmask == OldDmask)
10085     return Node;
10086 
10087   unsigned BitsSet = countPopulation(NewDmask);
10088 
10089   // Check for TFE or LWE - increase the number of channels by one to account
10090   // for the extra return value
10091   // This will need adjustment for D16 if this is also included in
10092   // adjustWriteMask (this function) but at present D16 are excluded.
10093   unsigned NewChannels = BitsSet + UsesTFC;
10094 
10095   int NewOpcode =
10096       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10097   assert(NewOpcode != -1 &&
10098          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10099          "failed to find equivalent MIMG op");
10100 
10101   // Adjust the writemask in the node
10102   SmallVector<SDValue, 12> Ops;
10103   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10104   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10105   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10106 
10107   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10108 
10109   MVT ResultVT = NewChannels == 1 ?
10110     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10111                            NewChannels == 5 ? 8 : NewChannels);
10112   SDVTList NewVTList = HasChain ?
10113     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10114 
10115 
10116   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10117                                               NewVTList, Ops);
10118 
10119   if (HasChain) {
10120     // Update chain.
10121     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10122     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10123   }
10124 
10125   if (NewChannels == 1) {
10126     assert(Node->hasNUsesOfValue(1, 0));
10127     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10128                                       SDLoc(Node), Users[Lane]->getValueType(0),
10129                                       SDValue(NewNode, 0));
10130     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10131     return nullptr;
10132   }
10133 
10134   // Update the users of the node with the new indices
10135   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10136     SDNode *User = Users[i];
10137     if (!User) {
10138       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10139       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10140       if (i || !NoChannels)
10141         continue;
10142     } else {
10143       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10144       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10145     }
10146 
10147     switch (Idx) {
10148     default: break;
10149     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10150     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10151     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10152     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10153     }
10154   }
10155 
10156   DAG.RemoveDeadNode(Node);
10157   return nullptr;
10158 }
10159 
10160 static bool isFrameIndexOp(SDValue Op) {
10161   if (Op.getOpcode() == ISD::AssertZext)
10162     Op = Op.getOperand(0);
10163 
10164   return isa<FrameIndexSDNode>(Op);
10165 }
10166 
10167 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10168 /// with frame index operands.
10169 /// LLVM assumes that inputs are to these instructions are registers.
10170 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10171                                                         SelectionDAG &DAG) const {
10172   if (Node->getOpcode() == ISD::CopyToReg) {
10173     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10174     SDValue SrcVal = Node->getOperand(2);
10175 
10176     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10177     // to try understanding copies to physical registers.
10178     if (SrcVal.getValueType() == MVT::i1 &&
10179         Register::isPhysicalRegister(DestReg->getReg())) {
10180       SDLoc SL(Node);
10181       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10182       SDValue VReg = DAG.getRegister(
10183         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10184 
10185       SDNode *Glued = Node->getGluedNode();
10186       SDValue ToVReg
10187         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10188                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10189       SDValue ToResultReg
10190         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10191                            VReg, ToVReg.getValue(1));
10192       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10193       DAG.RemoveDeadNode(Node);
10194       return ToResultReg.getNode();
10195     }
10196   }
10197 
10198   SmallVector<SDValue, 8> Ops;
10199   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10200     if (!isFrameIndexOp(Node->getOperand(i))) {
10201       Ops.push_back(Node->getOperand(i));
10202       continue;
10203     }
10204 
10205     SDLoc DL(Node);
10206     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10207                                      Node->getOperand(i).getValueType(),
10208                                      Node->getOperand(i)), 0));
10209   }
10210 
10211   return DAG.UpdateNodeOperands(Node, Ops);
10212 }
10213 
10214 /// Fold the instructions after selecting them.
10215 /// Returns null if users were already updated.
10216 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10217                                           SelectionDAG &DAG) const {
10218   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10219   unsigned Opcode = Node->getMachineOpcode();
10220 
10221   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10222       !TII->isGather4(Opcode)) {
10223     return adjustWritemask(Node, DAG);
10224   }
10225 
10226   if (Opcode == AMDGPU::INSERT_SUBREG ||
10227       Opcode == AMDGPU::REG_SEQUENCE) {
10228     legalizeTargetIndependentNode(Node, DAG);
10229     return Node;
10230   }
10231 
10232   switch (Opcode) {
10233   case AMDGPU::V_DIV_SCALE_F32:
10234   case AMDGPU::V_DIV_SCALE_F64: {
10235     // Satisfy the operand register constraint when one of the inputs is
10236     // undefined. Ordinarily each undef value will have its own implicit_def of
10237     // a vreg, so force these to use a single register.
10238     SDValue Src0 = Node->getOperand(0);
10239     SDValue Src1 = Node->getOperand(1);
10240     SDValue Src2 = Node->getOperand(2);
10241 
10242     if ((Src0.isMachineOpcode() &&
10243          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10244         (Src0 == Src1 || Src0 == Src2))
10245       break;
10246 
10247     MVT VT = Src0.getValueType().getSimpleVT();
10248     const TargetRegisterClass *RC =
10249         getRegClassFor(VT, Src0.getNode()->isDivergent());
10250 
10251     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10252     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10253 
10254     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10255                                       UndefReg, Src0, SDValue());
10256 
10257     // src0 must be the same register as src1 or src2, even if the value is
10258     // undefined, so make sure we don't violate this constraint.
10259     if (Src0.isMachineOpcode() &&
10260         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10261       if (Src1.isMachineOpcode() &&
10262           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10263         Src0 = Src1;
10264       else if (Src2.isMachineOpcode() &&
10265                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10266         Src0 = Src2;
10267       else {
10268         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10269         Src0 = UndefReg;
10270         Src1 = UndefReg;
10271       }
10272     } else
10273       break;
10274 
10275     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10276     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10277       Ops.push_back(Node->getOperand(I));
10278 
10279     Ops.push_back(ImpDef.getValue(1));
10280     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10281   }
10282   default:
10283     break;
10284   }
10285 
10286   return Node;
10287 }
10288 
10289 /// Assign the register class depending on the number of
10290 /// bits set in the writemask
10291 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10292                                                      SDNode *Node) const {
10293   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10294 
10295   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10296 
10297   if (TII->isVOP3(MI.getOpcode())) {
10298     // Make sure constant bus requirements are respected.
10299     TII->legalizeOperandsVOP3(MRI, MI);
10300 
10301     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10302     // This saves a chain-copy of registers and better ballance register
10303     // use between vgpr and agpr as agpr tuples tend to be big.
10304     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10305       unsigned Opc = MI.getOpcode();
10306       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10307       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10308                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10309         if (I == -1)
10310           break;
10311         MachineOperand &Op = MI.getOperand(I);
10312         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10313              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10314             !Register::isVirtualRegister(Op.getReg()) ||
10315             !TRI->isAGPR(MRI, Op.getReg()))
10316           continue;
10317         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10318         if (!Src || !Src->isCopy() ||
10319             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10320           continue;
10321         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10322         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10323         // All uses of agpr64 and agpr32 can also accept vgpr except for
10324         // v_accvgpr_read, but we do not produce agpr reads during selection,
10325         // so no use checks are needed.
10326         MRI.setRegClass(Op.getReg(), NewRC);
10327       }
10328     }
10329 
10330     return;
10331   }
10332 
10333   // Replace unused atomics with the no return version.
10334   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10335   if (NoRetAtomicOp != -1) {
10336     if (!Node->hasAnyUseOfValue(0)) {
10337       MI.setDesc(TII->get(NoRetAtomicOp));
10338       MI.RemoveOperand(0);
10339       return;
10340     }
10341 
10342     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10343     // instruction, because the return type of these instructions is a vec2 of
10344     // the memory type, so it can be tied to the input operand.
10345     // This means these instructions always have a use, so we need to add a
10346     // special case to check if the atomic has only one extract_subreg use,
10347     // which itself has no uses.
10348     if ((Node->hasNUsesOfValue(1, 0) &&
10349          Node->use_begin()->isMachineOpcode() &&
10350          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10351          !Node->use_begin()->hasAnyUseOfValue(0))) {
10352       Register Def = MI.getOperand(0).getReg();
10353 
10354       // Change this into a noret atomic.
10355       MI.setDesc(TII->get(NoRetAtomicOp));
10356       MI.RemoveOperand(0);
10357 
10358       // If we only remove the def operand from the atomic instruction, the
10359       // extract_subreg will be left with a use of a vreg without a def.
10360       // So we need to insert an implicit_def to avoid machine verifier
10361       // errors.
10362       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10363               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10364     }
10365     return;
10366   }
10367 }
10368 
10369 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10370                               uint64_t Val) {
10371   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10372   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10373 }
10374 
10375 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10376                                                 const SDLoc &DL,
10377                                                 SDValue Ptr) const {
10378   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10379 
10380   // Build the half of the subregister with the constants before building the
10381   // full 128-bit register. If we are building multiple resource descriptors,
10382   // this will allow CSEing of the 2-component register.
10383   const SDValue Ops0[] = {
10384     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10385     buildSMovImm32(DAG, DL, 0),
10386     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10387     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10388     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10389   };
10390 
10391   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10392                                                 MVT::v2i32, Ops0), 0);
10393 
10394   // Combine the constants and the pointer.
10395   const SDValue Ops1[] = {
10396     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10397     Ptr,
10398     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10399     SubRegHi,
10400     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10401   };
10402 
10403   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10404 }
10405 
10406 /// Return a resource descriptor with the 'Add TID' bit enabled
10407 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10408 ///        of the resource descriptor) to create an offset, which is added to
10409 ///        the resource pointer.
10410 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10411                                            SDValue Ptr, uint32_t RsrcDword1,
10412                                            uint64_t RsrcDword2And3) const {
10413   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10414   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10415   if (RsrcDword1) {
10416     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10417                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10418                     0);
10419   }
10420 
10421   SDValue DataLo = buildSMovImm32(DAG, DL,
10422                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10423   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10424 
10425   const SDValue Ops[] = {
10426     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10427     PtrLo,
10428     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10429     PtrHi,
10430     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10431     DataLo,
10432     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10433     DataHi,
10434     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10435   };
10436 
10437   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10438 }
10439 
10440 //===----------------------------------------------------------------------===//
10441 //                         SI Inline Assembly Support
10442 //===----------------------------------------------------------------------===//
10443 
10444 std::pair<unsigned, const TargetRegisterClass *>
10445 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
10446                                                StringRef Constraint,
10447                                                MVT VT) const {
10448   const TargetRegisterClass *RC = nullptr;
10449   if (Constraint.size() == 1) {
10450     switch (Constraint[0]) {
10451     default:
10452       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10453     case 's':
10454     case 'r':
10455       switch (VT.getSizeInBits()) {
10456       default:
10457         return std::make_pair(0U, nullptr);
10458       case 32:
10459       case 16:
10460         RC = &AMDGPU::SReg_32RegClass;
10461         break;
10462       case 64:
10463         RC = &AMDGPU::SGPR_64RegClass;
10464         break;
10465       case 96:
10466         RC = &AMDGPU::SReg_96RegClass;
10467         break;
10468       case 128:
10469         RC = &AMDGPU::SGPR_128RegClass;
10470         break;
10471       case 160:
10472         RC = &AMDGPU::SReg_160RegClass;
10473         break;
10474       case 256:
10475         RC = &AMDGPU::SReg_256RegClass;
10476         break;
10477       case 512:
10478         RC = &AMDGPU::SReg_512RegClass;
10479         break;
10480       }
10481       break;
10482     case 'v':
10483       switch (VT.getSizeInBits()) {
10484       default:
10485         return std::make_pair(0U, nullptr);
10486       case 32:
10487       case 16:
10488         RC = &AMDGPU::VGPR_32RegClass;
10489         break;
10490       case 64:
10491         RC = &AMDGPU::VReg_64RegClass;
10492         break;
10493       case 96:
10494         RC = &AMDGPU::VReg_96RegClass;
10495         break;
10496       case 128:
10497         RC = &AMDGPU::VReg_128RegClass;
10498         break;
10499       case 160:
10500         RC = &AMDGPU::VReg_160RegClass;
10501         break;
10502       case 256:
10503         RC = &AMDGPU::VReg_256RegClass;
10504         break;
10505       case 512:
10506         RC = &AMDGPU::VReg_512RegClass;
10507         break;
10508       }
10509       break;
10510     case 'a':
10511       if (!Subtarget->hasMAIInsts())
10512         break;
10513       switch (VT.getSizeInBits()) {
10514       default:
10515         return std::make_pair(0U, nullptr);
10516       case 32:
10517       case 16:
10518         RC = &AMDGPU::AGPR_32RegClass;
10519         break;
10520       case 64:
10521         RC = &AMDGPU::AReg_64RegClass;
10522         break;
10523       case 128:
10524         RC = &AMDGPU::AReg_128RegClass;
10525         break;
10526       case 512:
10527         RC = &AMDGPU::AReg_512RegClass;
10528         break;
10529       case 1024:
10530         RC = &AMDGPU::AReg_1024RegClass;
10531         // v32 types are not legal but we support them here.
10532         return std::make_pair(0U, RC);
10533       }
10534       break;
10535     }
10536     // We actually support i128, i16 and f16 as inline parameters
10537     // even if they are not reported as legal
10538     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10539                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10540       return std::make_pair(0U, RC);
10541   }
10542 
10543   if (Constraint.size() > 1) {
10544     if (Constraint[1] == 'v') {
10545       RC = &AMDGPU::VGPR_32RegClass;
10546     } else if (Constraint[1] == 's') {
10547       RC = &AMDGPU::SGPR_32RegClass;
10548     } else if (Constraint[1] == 'a') {
10549       RC = &AMDGPU::AGPR_32RegClass;
10550     }
10551 
10552     if (RC) {
10553       uint32_t Idx;
10554       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10555       if (!Failed && Idx < RC->getNumRegs())
10556         return std::make_pair(RC->getRegister(Idx), RC);
10557     }
10558   }
10559 
10560   // FIXME: Returns VS_32 for physical SGPR constraints
10561   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10562 }
10563 
10564 SITargetLowering::ConstraintType
10565 SITargetLowering::getConstraintType(StringRef Constraint) const {
10566   if (Constraint.size() == 1) {
10567     switch (Constraint[0]) {
10568     default: break;
10569     case 's':
10570     case 'v':
10571     case 'a':
10572       return C_RegisterClass;
10573     }
10574   }
10575   return TargetLowering::getConstraintType(Constraint);
10576 }
10577 
10578 // Figure out which registers should be reserved for stack access. Only after
10579 // the function is legalized do we know all of the non-spill stack objects or if
10580 // calls are present.
10581 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10582   MachineRegisterInfo &MRI = MF.getRegInfo();
10583   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10584   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10585   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10586 
10587   if (Info->isEntryFunction()) {
10588     // Callable functions have fixed registers used for stack access.
10589     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10590   }
10591 
10592   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10593                              Info->getStackPtrOffsetReg()));
10594   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10595     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10596 
10597   // We need to worry about replacing the default register with itself in case
10598   // of MIR testcases missing the MFI.
10599   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10600     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10601 
10602   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10603     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10604 
10605   if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) {
10606     MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
10607                        Info->getScratchWaveOffsetReg());
10608   }
10609 
10610   Info->limitOccupancy(MF);
10611 
10612   if (ST.isWave32() && !MF.empty()) {
10613     // Add VCC_HI def because many instructions marked as imp-use VCC where
10614     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10615     // having a use of undef.
10616 
10617     const SIInstrInfo *TII = ST.getInstrInfo();
10618     DebugLoc DL;
10619 
10620     MachineBasicBlock &MBB = MF.front();
10621     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10622     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10623 
10624     for (auto &MBB : MF) {
10625       for (auto &MI : MBB) {
10626         TII->fixImplicitOperands(MI);
10627       }
10628     }
10629   }
10630 
10631   TargetLoweringBase::finalizeLowering(MF);
10632 }
10633 
10634 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10635                                                      KnownBits &Known,
10636                                                      const APInt &DemandedElts,
10637                                                      const SelectionDAG &DAG,
10638                                                      unsigned Depth) const {
10639   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10640                                                 DAG, Depth);
10641 
10642   // Set the high bits to zero based on the maximum allowed scratch size per
10643   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10644   // calculation won't overflow, so assume the sign bit is never set.
10645   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10646 }
10647 
10648 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10649   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10650   const Align CacheLineAlign = Align(64);
10651 
10652   // Pre-GFX10 target did not benefit from loop alignment
10653   if (!ML || DisableLoopAlignment ||
10654       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10655       getSubtarget()->hasInstFwdPrefetchBug())
10656     return PrefAlign;
10657 
10658   // On GFX10 I$ is 4 x 64 bytes cache lines.
10659   // By default prefetcher keeps one cache line behind and reads two ahead.
10660   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10661   // behind and one ahead.
10662   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10663   // If loop fits 64 bytes it always spans no more than two cache lines and
10664   // does not need an alignment.
10665   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10666   // Else if loop is less or equal 192 bytes we need two lines behind.
10667 
10668   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10669   const MachineBasicBlock *Header = ML->getHeader();
10670   if (Header->getAlignment() != PrefAlign)
10671     return Header->getAlignment(); // Already processed.
10672 
10673   unsigned LoopSize = 0;
10674   for (const MachineBasicBlock *MBB : ML->blocks()) {
10675     // If inner loop block is aligned assume in average half of the alignment
10676     // size to be added as nops.
10677     if (MBB != Header)
10678       LoopSize += MBB->getAlignment().value() / 2;
10679 
10680     for (const MachineInstr &MI : *MBB) {
10681       LoopSize += TII->getInstSizeInBytes(MI);
10682       if (LoopSize > 192)
10683         return PrefAlign;
10684     }
10685   }
10686 
10687   if (LoopSize <= 64)
10688     return PrefAlign;
10689 
10690   if (LoopSize <= 128)
10691     return CacheLineAlign;
10692 
10693   // If any of parent loops is surrounded by prefetch instructions do not
10694   // insert new for inner loop, which would reset parent's settings.
10695   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10696     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10697       auto I = Exit->getFirstNonDebugInstr();
10698       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10699         return CacheLineAlign;
10700     }
10701   }
10702 
10703   MachineBasicBlock *Pre = ML->getLoopPreheader();
10704   MachineBasicBlock *Exit = ML->getExitBlock();
10705 
10706   if (Pre && Exit) {
10707     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10708             TII->get(AMDGPU::S_INST_PREFETCH))
10709       .addImm(1); // prefetch 2 lines behind PC
10710 
10711     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10712             TII->get(AMDGPU::S_INST_PREFETCH))
10713       .addImm(2); // prefetch 1 line behind PC
10714   }
10715 
10716   return CacheLineAlign;
10717 }
10718 
10719 LLVM_ATTRIBUTE_UNUSED
10720 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10721   assert(N->getOpcode() == ISD::CopyFromReg);
10722   do {
10723     // Follow the chain until we find an INLINEASM node.
10724     N = N->getOperand(0).getNode();
10725     if (N->getOpcode() == ISD::INLINEASM ||
10726         N->getOpcode() == ISD::INLINEASM_BR)
10727       return true;
10728   } while (N->getOpcode() == ISD::CopyFromReg);
10729   return false;
10730 }
10731 
10732 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10733   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10734 {
10735   switch (N->getOpcode()) {
10736     case ISD::CopyFromReg:
10737     {
10738       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10739       const MachineFunction * MF = FLI->MF;
10740       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10741       const MachineRegisterInfo &MRI = MF->getRegInfo();
10742       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10743       unsigned Reg = R->getReg();
10744       if (Register::isPhysicalRegister(Reg))
10745         return !TRI.isSGPRReg(MRI, Reg);
10746 
10747       if (MRI.isLiveIn(Reg)) {
10748         // workitem.id.x workitem.id.y workitem.id.z
10749         // Any VGPR formal argument is also considered divergent
10750         if (!TRI.isSGPRReg(MRI, Reg))
10751           return true;
10752         // Formal arguments of non-entry functions
10753         // are conservatively considered divergent
10754         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10755           return true;
10756         return false;
10757       }
10758       const Value *V = FLI->getValueFromVirtualReg(Reg);
10759       if (V)
10760         return KDA->isDivergent(V);
10761       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10762       return !TRI.isSGPRReg(MRI, Reg);
10763     }
10764     break;
10765     case ISD::LOAD: {
10766       const LoadSDNode *L = cast<LoadSDNode>(N);
10767       unsigned AS = L->getAddressSpace();
10768       // A flat load may access private memory.
10769       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10770     } break;
10771     case ISD::CALLSEQ_END:
10772     return true;
10773     break;
10774     case ISD::INTRINSIC_WO_CHAIN:
10775     {
10776 
10777     }
10778       return AMDGPU::isIntrinsicSourceOfDivergence(
10779       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10780     case ISD::INTRINSIC_W_CHAIN:
10781       return AMDGPU::isIntrinsicSourceOfDivergence(
10782       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10783   }
10784   return false;
10785 }
10786 
10787 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
10788                                                EVT VT) const {
10789   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10790   case MVT::f32:
10791     return hasFP32Denormals(DAG.getMachineFunction());
10792   case MVT::f64:
10793   case MVT::f16:
10794     return hasFP64FP16Denormals(DAG.getMachineFunction());
10795   default:
10796     return false;
10797   }
10798 }
10799 
10800 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
10801                                                     const SelectionDAG &DAG,
10802                                                     bool SNaN,
10803                                                     unsigned Depth) const {
10804   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
10805     const MachineFunction &MF = DAG.getMachineFunction();
10806     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10807 
10808     if (Info->getMode().DX10Clamp)
10809       return true; // Clamped to 0.
10810     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10811   }
10812 
10813   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
10814                                                             SNaN, Depth);
10815 }
10816 
10817 TargetLowering::AtomicExpansionKind
10818 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
10819   switch (RMW->getOperation()) {
10820   case AtomicRMWInst::FAdd: {
10821     Type *Ty = RMW->getType();
10822 
10823     // We don't have a way to support 16-bit atomics now, so just leave them
10824     // as-is.
10825     if (Ty->isHalfTy())
10826       return AtomicExpansionKind::None;
10827 
10828     if (!Ty->isFloatTy())
10829       return AtomicExpansionKind::CmpXChg;
10830 
10831     // TODO: Do have these for flat. Older targets also had them for buffers.
10832     unsigned AS = RMW->getPointerAddressSpace();
10833 
10834     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
10835       return RMW->use_empty() ? AtomicExpansionKind::None :
10836                                 AtomicExpansionKind::CmpXChg;
10837     }
10838 
10839     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10840       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
10841   }
10842   default:
10843     break;
10844   }
10845 
10846   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
10847 }
10848 
10849 const TargetRegisterClass *
10850 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
10851   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
10852   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10853   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
10854     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
10855                                                : &AMDGPU::SReg_32RegClass;
10856   if (!TRI->isSGPRClass(RC) && !isDivergent)
10857     return TRI->getEquivalentSGPRClass(RC);
10858   else if (TRI->isSGPRClass(RC) && isDivergent)
10859     return TRI->getEquivalentVGPRClass(RC);
10860 
10861   return RC;
10862 }
10863 
10864 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
10865                       unsigned WaveSize) {
10866   // FIXME: We asssume we never cast the mask results of a control flow
10867   // intrinsic.
10868   // Early exit if the type won't be consistent as a compile time hack.
10869   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
10870   if (!IT || IT->getBitWidth() != WaveSize)
10871     return false;
10872 
10873   if (!isa<Instruction>(V))
10874     return false;
10875   if (!Visited.insert(V).second)
10876     return false;
10877   bool Result = false;
10878   for (auto U : V->users()) {
10879     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
10880       if (V == U->getOperand(1)) {
10881         switch (Intrinsic->getIntrinsicID()) {
10882         default:
10883           Result = false;
10884           break;
10885         case Intrinsic::amdgcn_if_break:
10886         case Intrinsic::amdgcn_if:
10887         case Intrinsic::amdgcn_else:
10888           Result = true;
10889           break;
10890         }
10891       }
10892       if (V == U->getOperand(0)) {
10893         switch (Intrinsic->getIntrinsicID()) {
10894         default:
10895           Result = false;
10896           break;
10897         case Intrinsic::amdgcn_end_cf:
10898         case Intrinsic::amdgcn_loop:
10899           Result = true;
10900           break;
10901         }
10902       }
10903     } else {
10904       Result = hasCFUser(U, Visited, WaveSize);
10905     }
10906     if (Result)
10907       break;
10908   }
10909   return Result;
10910 }
10911 
10912 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
10913                                                const Value *V) const {
10914   if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(V)) {
10915     switch (Intrinsic->getIntrinsicID()) {
10916     default:
10917       return false;
10918     case Intrinsic::amdgcn_if_break:
10919       return true;
10920     }
10921   }
10922   if (const ExtractValueInst *ExtValue = dyn_cast<ExtractValueInst>(V)) {
10923     if (const IntrinsicInst *Intrinsic =
10924             dyn_cast<IntrinsicInst>(ExtValue->getOperand(0))) {
10925       switch (Intrinsic->getIntrinsicID()) {
10926       default:
10927         return false;
10928       case Intrinsic::amdgcn_if:
10929       case Intrinsic::amdgcn_else: {
10930         ArrayRef<unsigned> Indices = ExtValue->getIndices();
10931         if (Indices.size() == 1 && Indices[0] == 1) {
10932           return true;
10933         }
10934       }
10935       }
10936     }
10937   }
10938   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
10939     if (isa<InlineAsm>(CI->getCalledValue())) {
10940       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
10941       ImmutableCallSite CS(CI);
10942       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
10943           MF.getDataLayout(), Subtarget->getRegisterInfo(), CS);
10944       for (auto &TC : TargetConstraints) {
10945         if (TC.Type == InlineAsm::isOutput) {
10946           ComputeConstraintToUse(TC, SDValue());
10947           unsigned AssignedReg;
10948           const TargetRegisterClass *RC;
10949           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
10950               SIRI, TC.ConstraintCode, TC.ConstraintVT);
10951           if (RC) {
10952             MachineRegisterInfo &MRI = MF.getRegInfo();
10953             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
10954               return true;
10955             else if (SIRI->isSGPRClass(RC))
10956               return true;
10957           }
10958         }
10959       }
10960     }
10961   }
10962   SmallPtrSet<const Value *, 16> Visited;
10963   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
10964 }
10965