1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #if defined(_MSC_VER) || defined(__MINGW32__)
15 // Provide M_PI.
16 #define _USE_MATH_DEFINES
17 #endif
18 
19 #include "SIISelLowering.h"
20 #include "AMDGPU.h"
21 #include "AMDGPUSubtarget.h"
22 #include "AMDGPUTargetMachine.h"
23 #include "SIDefines.h"
24 #include "SIInstrInfo.h"
25 #include "SIMachineFunctionInfo.h"
26 #include "SIRegisterInfo.h"
27 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
28 #include "Utils/AMDGPUBaseInfo.h"
29 #include "llvm/ADT/APFloat.h"
30 #include "llvm/ADT/APInt.h"
31 #include "llvm/ADT/ArrayRef.h"
32 #include "llvm/ADT/BitVector.h"
33 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/StringSwitch.h"
37 #include "llvm/ADT/Twine.h"
38 #include "llvm/CodeGen/Analysis.h"
39 #include "llvm/CodeGen/CallingConvLower.h"
40 #include "llvm/CodeGen/DAGCombine.h"
41 #include "llvm/CodeGen/ISDOpcodes.h"
42 #include "llvm/CodeGen/MachineBasicBlock.h"
43 #include "llvm/CodeGen/MachineFrameInfo.h"
44 #include "llvm/CodeGen/MachineFunction.h"
45 #include "llvm/CodeGen/MachineInstr.h"
46 #include "llvm/CodeGen/MachineInstrBuilder.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/MachineModuleInfo.h"
49 #include "llvm/CodeGen/MachineOperand.h"
50 #include "llvm/CodeGen/MachineRegisterInfo.h"
51 #include "llvm/CodeGen/SelectionDAG.h"
52 #include "llvm/CodeGen/SelectionDAGNodes.h"
53 #include "llvm/CodeGen/TargetCallingConv.h"
54 #include "llvm/CodeGen/TargetRegisterInfo.h"
55 #include "llvm/CodeGen/ValueTypes.h"
56 #include "llvm/IR/Constants.h"
57 #include "llvm/IR/DataLayout.h"
58 #include "llvm/IR/DebugLoc.h"
59 #include "llvm/IR/DerivedTypes.h"
60 #include "llvm/IR/DiagnosticInfo.h"
61 #include "llvm/IR/Function.h"
62 #include "llvm/IR/GlobalValue.h"
63 #include "llvm/IR/InstrTypes.h"
64 #include "llvm/IR/Instruction.h"
65 #include "llvm/IR/Instructions.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/Type.h"
68 #include "llvm/Support/Casting.h"
69 #include "llvm/Support/CodeGen.h"
70 #include "llvm/Support/CommandLine.h"
71 #include "llvm/Support/Compiler.h"
72 #include "llvm/Support/ErrorHandling.h"
73 #include "llvm/Support/KnownBits.h"
74 #include "llvm/Support/MachineValueType.h"
75 #include "llvm/Support/MathExtras.h"
76 #include "llvm/Target/TargetOptions.h"
77 #include <cassert>
78 #include <cmath>
79 #include <cstdint>
80 #include <iterator>
81 #include <tuple>
82 #include <utility>
83 #include <vector>
84 
85 using namespace llvm;
86 
87 #define DEBUG_TYPE "si-lower"
88 
89 STATISTIC(NumTailCalls, "Number of tail calls");
90 
91 static cl::opt<bool> EnableVGPRIndexMode(
92   "amdgpu-vgpr-index-mode",
93   cl::desc("Use GPR indexing mode instead of movrel for vector indexing"),
94   cl::init(false));
95 
96 static cl::opt<bool> DisableLoopAlignment(
97   "amdgpu-disable-loop-alignment",
98   cl::desc("Do not align and prefetch loops"),
99   cl::init(false));
100 
101 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
102   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
103   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
104     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
105       return AMDGPU::SGPR0 + Reg;
106     }
107   }
108   llvm_unreachable("Cannot allocate sgpr");
109 }
110 
111 SITargetLowering::SITargetLowering(const TargetMachine &TM,
112                                    const GCNSubtarget &STI)
113     : AMDGPUTargetLowering(TM, STI),
114       Subtarget(&STI) {
115   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
116   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
117 
118   addRegisterClass(MVT::i32, &AMDGPU::SReg_32_XM0RegClass);
119   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
120 
121   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
122   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
123   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
124 
125   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
126   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
127 
128   addRegisterClass(MVT::v2i64, &AMDGPU::SReg_128RegClass);
129   addRegisterClass(MVT::v2f64, &AMDGPU::SReg_128RegClass);
130 
131   addRegisterClass(MVT::v4i32, &AMDGPU::SReg_128RegClass);
132   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
133 
134   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
135   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
136 
137   addRegisterClass(MVT::v8i32, &AMDGPU::SReg_256RegClass);
138   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
139 
140   addRegisterClass(MVT::v16i32, &AMDGPU::SReg_512RegClass);
141   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
142 
143   if (Subtarget->has16BitInsts()) {
144     addRegisterClass(MVT::i16, &AMDGPU::SReg_32_XM0RegClass);
145     addRegisterClass(MVT::f16, &AMDGPU::SReg_32_XM0RegClass);
146 
147     // Unless there are also VOP3P operations, not operations are really legal.
148     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32_XM0RegClass);
149     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32_XM0RegClass);
150     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
151     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
152   }
153 
154   computeRegisterProperties(Subtarget->getRegisterInfo());
155 
156   // We need to custom lower vector stores from local memory
157   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
158   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
159   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
160   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
161   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
162   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
163   setOperationAction(ISD::LOAD, MVT::i1, Custom);
164   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
165 
166   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
167   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
168   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
169   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
170   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
171   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
172   setOperationAction(ISD::STORE, MVT::i1, Custom);
173   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
174 
175   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
176   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
177   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
178   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
179   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
180   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
181   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
182   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
183   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
184   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
185 
186   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
187   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
188 
189   setOperationAction(ISD::SELECT, MVT::i1, Promote);
190   setOperationAction(ISD::SELECT, MVT::i64, Custom);
191   setOperationAction(ISD::SELECT, MVT::f64, Promote);
192   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
193 
194   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
195   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
196   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
197   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
198   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
199 
200   setOperationAction(ISD::SETCC, MVT::i1, Promote);
201   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
202   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
203   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
204 
205   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
206   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
207 
208   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
209   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
210   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
211   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
212   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
213   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
214   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
215 
216   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
217   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
218   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
219   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
220   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
221   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
222   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
223 
224   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
225   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
226   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
227   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
228   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
229   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
230 
231   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
232   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
233   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
234   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
235   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
236   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
237 
238   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
239   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
240   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
241   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
242   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
243   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
244 
245   setOperationAction(ISD::UADDO, MVT::i32, Legal);
246   setOperationAction(ISD::USUBO, MVT::i32, Legal);
247 
248   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
249   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
250 
251   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
252   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
253   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
254 
255 #if 0
256   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
257   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
258 #endif
259 
260   // We only support LOAD/STORE and vector manipulation ops for vectors
261   // with > 4 elements.
262   for (MVT VT : {MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
263         MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16, MVT::v32i32 }) {
264     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
265       switch (Op) {
266       case ISD::LOAD:
267       case ISD::STORE:
268       case ISD::BUILD_VECTOR:
269       case ISD::BITCAST:
270       case ISD::EXTRACT_VECTOR_ELT:
271       case ISD::INSERT_VECTOR_ELT:
272       case ISD::INSERT_SUBVECTOR:
273       case ISD::EXTRACT_SUBVECTOR:
274       case ISD::SCALAR_TO_VECTOR:
275         break;
276       case ISD::CONCAT_VECTORS:
277         setOperationAction(Op, VT, Custom);
278         break;
279       default:
280         setOperationAction(Op, VT, Expand);
281         break;
282       }
283     }
284   }
285 
286   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
287 
288   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
289   // is expanded to avoid having two separate loops in case the index is a VGPR.
290 
291   // Most operations are naturally 32-bit vector operations. We only support
292   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
293   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
294     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
295     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
296 
297     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
298     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
299 
300     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
301     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
302 
303     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
304     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
305   }
306 
307   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
308   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
309   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
310   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
311 
312   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
313   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
314 
315   // Avoid stack access for these.
316   // TODO: Generalize to more vector types.
317   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
318   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
319   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
320   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
321 
322   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
323   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
324   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
325   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
326   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
327 
328   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
329   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
330   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
331 
332   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
333   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
334   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
335   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
336 
337   // Deal with vec3 vector operations when widened to vec4.
338   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Expand);
339   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Expand);
340   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Expand);
341   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Expand);
342 
343   // Deal with vec5 vector operations when widened to vec8.
344   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Expand);
345   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Expand);
346   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Expand);
347   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Expand);
348 
349   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
350   // and output demarshalling
351   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
352   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
353 
354   // We can't return success/failure, only the old value,
355   // let LLVM add the comparison
356   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
357   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
358 
359   if (Subtarget->hasFlatAddressSpace()) {
360     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
361     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
362   }
363 
364   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
365   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
366 
367   // On SI this is s_memtime and s_memrealtime on VI.
368   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
369   setOperationAction(ISD::TRAP, MVT::Other, Custom);
370   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
371 
372   if (Subtarget->has16BitInsts()) {
373     setOperationAction(ISD::FLOG, MVT::f16, Custom);
374     setOperationAction(ISD::FEXP, MVT::f16, Custom);
375     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
376   }
377 
378   // v_mad_f32 does not support denormals according to some sources.
379   if (!Subtarget->hasFP32Denormals())
380     setOperationAction(ISD::FMAD, MVT::f32, Legal);
381 
382   if (!Subtarget->hasBFI()) {
383     // fcopysign can be done in a single instruction with BFI.
384     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
385     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
386   }
387 
388   if (!Subtarget->hasBCNT(32))
389     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
390 
391   if (!Subtarget->hasBCNT(64))
392     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
393 
394   if (Subtarget->hasFFBH())
395     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
396 
397   if (Subtarget->hasFFBL())
398     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
399 
400   // We only really have 32-bit BFE instructions (and 16-bit on VI).
401   //
402   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
403   // effort to match them now. We want this to be false for i64 cases when the
404   // extraction isn't restricted to the upper or lower half. Ideally we would
405   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
406   // span the midpoint are probably relatively rare, so don't worry about them
407   // for now.
408   if (Subtarget->hasBFE())
409     setHasExtractBitsInsn(true);
410 
411   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
412   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
413   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
414   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
415 
416 
417   // These are really only legal for ieee_mode functions. We should be avoiding
418   // them for functions that don't have ieee_mode enabled, so just say they are
419   // legal.
420   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
421   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
422   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
423   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
424 
425 
426   if (Subtarget->getGeneration() >= AMDGPUSubtarget::SEA_ISLANDS) {
427     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
428     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
429     setOperationAction(ISD::FRINT, MVT::f64, Legal);
430   } else {
431     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
432     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
433     setOperationAction(ISD::FRINT, MVT::f64, Custom);
434     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
435   }
436 
437   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
438 
439   setOperationAction(ISD::FSIN, MVT::f32, Custom);
440   setOperationAction(ISD::FCOS, MVT::f32, Custom);
441   setOperationAction(ISD::FDIV, MVT::f32, Custom);
442   setOperationAction(ISD::FDIV, MVT::f64, Custom);
443 
444   if (Subtarget->has16BitInsts()) {
445     setOperationAction(ISD::Constant, MVT::i16, Legal);
446 
447     setOperationAction(ISD::SMIN, MVT::i16, Legal);
448     setOperationAction(ISD::SMAX, MVT::i16, Legal);
449 
450     setOperationAction(ISD::UMIN, MVT::i16, Legal);
451     setOperationAction(ISD::UMAX, MVT::i16, Legal);
452 
453     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
454     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
455 
456     setOperationAction(ISD::ROTR, MVT::i16, Promote);
457     setOperationAction(ISD::ROTL, MVT::i16, Promote);
458 
459     setOperationAction(ISD::SDIV, MVT::i16, Promote);
460     setOperationAction(ISD::UDIV, MVT::i16, Promote);
461     setOperationAction(ISD::SREM, MVT::i16, Promote);
462     setOperationAction(ISD::UREM, MVT::i16, Promote);
463 
464     setOperationAction(ISD::BSWAP, MVT::i16, Promote);
465     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
466 
467     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
468     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
469     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
470     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
471     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
472 
473     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
474 
475     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
476 
477     setOperationAction(ISD::LOAD, MVT::i16, Custom);
478 
479     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
480 
481     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
482     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
483     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
484     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
485 
486     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
487     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
488     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Promote);
489     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Promote);
490 
491     // F16 - Constant Actions.
492     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
493 
494     // F16 - Load/Store Actions.
495     setOperationAction(ISD::LOAD, MVT::f16, Promote);
496     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
497     setOperationAction(ISD::STORE, MVT::f16, Promote);
498     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
499 
500     // F16 - VOP1 Actions.
501     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
502     setOperationAction(ISD::FCOS, MVT::f16, Promote);
503     setOperationAction(ISD::FSIN, MVT::f16, Promote);
504     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
505     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
506     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
507     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
508     setOperationAction(ISD::FROUND, MVT::f16, Custom);
509 
510     // F16 - VOP2 Actions.
511     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
512     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
513 
514     setOperationAction(ISD::FDIV, MVT::f16, Custom);
515 
516     // F16 - VOP3 Actions.
517     setOperationAction(ISD::FMA, MVT::f16, Legal);
518     if (!Subtarget->hasFP16Denormals() && STI.hasMadF16())
519       setOperationAction(ISD::FMAD, MVT::f16, Legal);
520 
521     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
522       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
523         switch (Op) {
524         case ISD::LOAD:
525         case ISD::STORE:
526         case ISD::BUILD_VECTOR:
527         case ISD::BITCAST:
528         case ISD::EXTRACT_VECTOR_ELT:
529         case ISD::INSERT_VECTOR_ELT:
530         case ISD::INSERT_SUBVECTOR:
531         case ISD::EXTRACT_SUBVECTOR:
532         case ISD::SCALAR_TO_VECTOR:
533           break;
534         case ISD::CONCAT_VECTORS:
535           setOperationAction(Op, VT, Custom);
536           break;
537         default:
538           setOperationAction(Op, VT, Expand);
539           break;
540         }
541       }
542     }
543 
544     // XXX - Do these do anything? Vector constants turn into build_vector.
545     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
546     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
547 
548     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
549     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
550 
551     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
552     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
553     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
554     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
555 
556     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
557     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
558     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
559     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
560 
561     setOperationAction(ISD::AND, MVT::v2i16, Promote);
562     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
563     setOperationAction(ISD::OR, MVT::v2i16, Promote);
564     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
565     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
566     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
567 
568     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
569     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
570     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
571     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
572 
573     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
574     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
575     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
576     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
577 
578     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
579     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
580     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
581     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
582 
583     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
584     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
585     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
586 
587     if (!Subtarget->hasVOP3PInsts()) {
588       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
589       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
590     }
591 
592     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
593     // This isn't really legal, but this avoids the legalizer unrolling it (and
594     // allows matching fneg (fabs x) patterns)
595     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
596 
597     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
598     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
599     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
600     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
601 
602     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
603     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
604 
605     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
606     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
607   }
608 
609   if (Subtarget->hasVOP3PInsts()) {
610     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
611     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
612     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
613     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
614     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
615     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
616     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
617     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
618     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
619     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
620 
621     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
622     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
623     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
624 
625     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
626     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
627 
628     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
629 
630     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
631     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
632 
633     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
634     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
635     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
636     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
637     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
638     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
639 
640     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
641     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
642     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
643     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
644 
645     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
646     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
647 
648     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
649     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
650 
651     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
652     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
653     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
654 
655     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
656     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
657     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
658   }
659 
660   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
661   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
662 
663   if (Subtarget->has16BitInsts()) {
664     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
665     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
666     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
667     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
668   } else {
669     // Legalization hack.
670     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
671     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
672 
673     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
674     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
675   }
676 
677   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
678     setOperationAction(ISD::SELECT, VT, Custom);
679   }
680 
681   setTargetDAGCombine(ISD::ADD);
682   setTargetDAGCombine(ISD::ADDCARRY);
683   setTargetDAGCombine(ISD::SUB);
684   setTargetDAGCombine(ISD::SUBCARRY);
685   setTargetDAGCombine(ISD::FADD);
686   setTargetDAGCombine(ISD::FSUB);
687   setTargetDAGCombine(ISD::FMINNUM);
688   setTargetDAGCombine(ISD::FMAXNUM);
689   setTargetDAGCombine(ISD::FMINNUM_IEEE);
690   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
691   setTargetDAGCombine(ISD::FMA);
692   setTargetDAGCombine(ISD::SMIN);
693   setTargetDAGCombine(ISD::SMAX);
694   setTargetDAGCombine(ISD::UMIN);
695   setTargetDAGCombine(ISD::UMAX);
696   setTargetDAGCombine(ISD::SETCC);
697   setTargetDAGCombine(ISD::AND);
698   setTargetDAGCombine(ISD::OR);
699   setTargetDAGCombine(ISD::XOR);
700   setTargetDAGCombine(ISD::SINT_TO_FP);
701   setTargetDAGCombine(ISD::UINT_TO_FP);
702   setTargetDAGCombine(ISD::FCANONICALIZE);
703   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
704   setTargetDAGCombine(ISD::ZERO_EXTEND);
705   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
706   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
707   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
708 
709   // All memory operations. Some folding on the pointer operand is done to help
710   // matching the constant offsets in the addressing modes.
711   setTargetDAGCombine(ISD::LOAD);
712   setTargetDAGCombine(ISD::STORE);
713   setTargetDAGCombine(ISD::ATOMIC_LOAD);
714   setTargetDAGCombine(ISD::ATOMIC_STORE);
715   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
716   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
717   setTargetDAGCombine(ISD::ATOMIC_SWAP);
718   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
719   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
720   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
721   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
722   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
723   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
724   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
725   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
726   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
727   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
728   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
729 
730   setSchedulingPreference(Sched::RegPressure);
731 }
732 
733 const GCNSubtarget *SITargetLowering::getSubtarget() const {
734   return Subtarget;
735 }
736 
737 //===----------------------------------------------------------------------===//
738 // TargetLowering queries
739 //===----------------------------------------------------------------------===//
740 
741 // v_mad_mix* support a conversion from f16 to f32.
742 //
743 // There is only one special case when denormals are enabled we don't currently,
744 // where this is OK to use.
745 bool SITargetLowering::isFPExtFoldable(unsigned Opcode,
746                                            EVT DestVT, EVT SrcVT) const {
747   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
748           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
749          DestVT.getScalarType() == MVT::f32 && !Subtarget->hasFP32Denormals() &&
750          SrcVT.getScalarType() == MVT::f16;
751 }
752 
753 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
754   // SI has some legal vector types, but no legal vector operations. Say no
755   // shuffles are legal in order to prefer scalarizing some vector operations.
756   return false;
757 }
758 
759 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
760                                                     CallingConv::ID CC,
761                                                     EVT VT) const {
762   // TODO: Consider splitting all arguments into 32-bit pieces.
763   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
764     EVT ScalarVT = VT.getScalarType();
765     unsigned Size = ScalarVT.getSizeInBits();
766     if (Size == 32)
767       return ScalarVT.getSimpleVT();
768 
769     if (Size == 64)
770       return MVT::i32;
771 
772     if (Size == 16 && Subtarget->has16BitInsts())
773       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
774   }
775 
776   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
777 }
778 
779 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
780                                                          CallingConv::ID CC,
781                                                          EVT VT) const {
782   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
783     unsigned NumElts = VT.getVectorNumElements();
784     EVT ScalarVT = VT.getScalarType();
785     unsigned Size = ScalarVT.getSizeInBits();
786 
787     if (Size == 32)
788       return NumElts;
789 
790     if (Size == 64)
791       return 2 * NumElts;
792 
793     if (Size == 16 && Subtarget->has16BitInsts())
794       return (VT.getVectorNumElements() + 1) / 2;
795   }
796 
797   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
798 }
799 
800 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
801   LLVMContext &Context, CallingConv::ID CC,
802   EVT VT, EVT &IntermediateVT,
803   unsigned &NumIntermediates, MVT &RegisterVT) const {
804   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
805     unsigned NumElts = VT.getVectorNumElements();
806     EVT ScalarVT = VT.getScalarType();
807     unsigned Size = ScalarVT.getSizeInBits();
808     if (Size == 32) {
809       RegisterVT = ScalarVT.getSimpleVT();
810       IntermediateVT = RegisterVT;
811       NumIntermediates = NumElts;
812       return NumIntermediates;
813     }
814 
815     if (Size == 64) {
816       RegisterVT = MVT::i32;
817       IntermediateVT = RegisterVT;
818       NumIntermediates = 2 * NumElts;
819       return NumIntermediates;
820     }
821 
822     // FIXME: We should fix the ABI to be the same on targets without 16-bit
823     // support, but unless we can properly handle 3-vectors, it will be still be
824     // inconsistent.
825     if (Size == 16 && Subtarget->has16BitInsts()) {
826       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
827       IntermediateVT = RegisterVT;
828       NumIntermediates = (NumElts + 1) / 2;
829       return NumIntermediates;
830     }
831   }
832 
833   return TargetLowering::getVectorTypeBreakdownForCallingConv(
834     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
835 }
836 
837 static MVT memVTFromAggregate(Type *Ty) {
838   // Only limited forms of aggregate type currently expected.
839   assert(Ty->isStructTy() && "Expected struct type");
840 
841 
842   Type *ElementType = nullptr;
843   unsigned NumElts;
844   if (Ty->getContainedType(0)->isVectorTy()) {
845     VectorType *VecComponent = cast<VectorType>(Ty->getContainedType(0));
846     ElementType = VecComponent->getElementType();
847     NumElts = VecComponent->getNumElements();
848   } else {
849     ElementType = Ty->getContainedType(0);
850     NumElts = 1;
851   }
852 
853   assert((Ty->getContainedType(1) && Ty->getContainedType(1)->isIntegerTy(32)) && "Expected int32 type");
854 
855   // Calculate the size of the memVT type from the aggregate
856   unsigned Pow2Elts = 0;
857   unsigned ElementSize;
858   switch (ElementType->getTypeID()) {
859     default:
860       llvm_unreachable("Unknown type!");
861     case Type::IntegerTyID:
862       ElementSize = cast<IntegerType>(ElementType)->getBitWidth();
863       break;
864     case Type::HalfTyID:
865       ElementSize = 16;
866       break;
867     case Type::FloatTyID:
868       ElementSize = 32;
869       break;
870   }
871   unsigned AdditionalElts = ElementSize == 16 ? 2 : 1;
872   Pow2Elts = 1 << Log2_32_Ceil(NumElts + AdditionalElts);
873 
874   return MVT::getVectorVT(MVT::getVT(ElementType, false),
875                           Pow2Elts);
876 }
877 
878 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
879                                           const CallInst &CI,
880                                           MachineFunction &MF,
881                                           unsigned IntrID) const {
882   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
883           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
884     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
885                                                   (Intrinsic::ID)IntrID);
886     if (Attr.hasFnAttribute(Attribute::ReadNone))
887       return false;
888 
889     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
890 
891     if (RsrcIntr->IsImage) {
892       Info.ptrVal = MFI->getImagePSV(
893         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
894         CI.getArgOperand(RsrcIntr->RsrcArg));
895       Info.align = 0;
896     } else {
897       Info.ptrVal = MFI->getBufferPSV(
898         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
899         CI.getArgOperand(RsrcIntr->RsrcArg));
900     }
901 
902     Info.flags = MachineMemOperand::MODereferenceable;
903     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
904       Info.opc = ISD::INTRINSIC_W_CHAIN;
905       Info.memVT = MVT::getVT(CI.getType(), true);
906       if (Info.memVT == MVT::Other) {
907         // Some intrinsics return an aggregate type - special case to work out
908         // the correct memVT
909         Info.memVT = memVTFromAggregate(CI.getType());
910       }
911       Info.flags |= MachineMemOperand::MOLoad;
912     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
913       Info.opc = ISD::INTRINSIC_VOID;
914       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
915       Info.flags |= MachineMemOperand::MOStore;
916     } else {
917       // Atomic
918       Info.opc = ISD::INTRINSIC_W_CHAIN;
919       Info.memVT = MVT::getVT(CI.getType());
920       Info.flags = MachineMemOperand::MOLoad |
921                    MachineMemOperand::MOStore |
922                    MachineMemOperand::MODereferenceable;
923 
924       // XXX - Should this be volatile without known ordering?
925       Info.flags |= MachineMemOperand::MOVolatile;
926     }
927     return true;
928   }
929 
930   switch (IntrID) {
931   case Intrinsic::amdgcn_atomic_inc:
932   case Intrinsic::amdgcn_atomic_dec:
933   case Intrinsic::amdgcn_ds_ordered_add:
934   case Intrinsic::amdgcn_ds_ordered_swap:
935   case Intrinsic::amdgcn_ds_fadd:
936   case Intrinsic::amdgcn_ds_fmin:
937   case Intrinsic::amdgcn_ds_fmax: {
938     Info.opc = ISD::INTRINSIC_W_CHAIN;
939     Info.memVT = MVT::getVT(CI.getType());
940     Info.ptrVal = CI.getOperand(0);
941     Info.align = 0;
942     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
943 
944     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
945     if (!Vol->isZero())
946       Info.flags |= MachineMemOperand::MOVolatile;
947 
948     return true;
949   }
950   case Intrinsic::amdgcn_ds_append:
951   case Intrinsic::amdgcn_ds_consume: {
952     Info.opc = ISD::INTRINSIC_W_CHAIN;
953     Info.memVT = MVT::getVT(CI.getType());
954     Info.ptrVal = CI.getOperand(0);
955     Info.align = 0;
956     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
957 
958     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
959     if (!Vol->isZero())
960       Info.flags |= MachineMemOperand::MOVolatile;
961 
962     return true;
963   }
964   case Intrinsic::amdgcn_ds_gws_init:
965   case Intrinsic::amdgcn_ds_gws_barrier: {
966     Info.opc = ISD::INTRINSIC_VOID;
967 
968     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
969     Info.ptrVal =
970         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
971 
972     // This is an abstract access, but we need to specify a type and size.
973     Info.memVT = MVT::i32;
974     Info.size = 4;
975     Info.align = 4;
976 
977     Info.flags = MachineMemOperand::MOStore;
978     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
979       Info.flags = MachineMemOperand::MOLoad;
980     return true;
981   }
982   default:
983     return false;
984   }
985 }
986 
987 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
988                                             SmallVectorImpl<Value*> &Ops,
989                                             Type *&AccessTy) const {
990   switch (II->getIntrinsicID()) {
991   case Intrinsic::amdgcn_atomic_inc:
992   case Intrinsic::amdgcn_atomic_dec:
993   case Intrinsic::amdgcn_ds_ordered_add:
994   case Intrinsic::amdgcn_ds_ordered_swap:
995   case Intrinsic::amdgcn_ds_fadd:
996   case Intrinsic::amdgcn_ds_fmin:
997   case Intrinsic::amdgcn_ds_fmax: {
998     Value *Ptr = II->getArgOperand(0);
999     AccessTy = II->getType();
1000     Ops.push_back(Ptr);
1001     return true;
1002   }
1003   default:
1004     return false;
1005   }
1006 }
1007 
1008 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1009   if (!Subtarget->hasFlatInstOffsets()) {
1010     // Flat instructions do not have offsets, and only have the register
1011     // address.
1012     return AM.BaseOffs == 0 && AM.Scale == 0;
1013   }
1014 
1015   // GFX9 added a 13-bit signed offset. When using regular flat instructions,
1016   // the sign bit is ignored and is treated as a 12-bit unsigned offset.
1017 
1018   // GFX10 shrinked signed offset to 12 bits. When using regular flat
1019   // instructions, the sign bit is also ignored and is treated as 11-bit
1020   // unsigned offset.
1021 
1022   if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
1023     return isUInt<11>(AM.BaseOffs) && AM.Scale == 0;
1024 
1025   // Just r + i
1026   return isUInt<12>(AM.BaseOffs) && AM.Scale == 0;
1027 }
1028 
1029 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1030   if (Subtarget->hasFlatGlobalInsts())
1031     return isInt<13>(AM.BaseOffs) && AM.Scale == 0;
1032 
1033   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1034       // Assume the we will use FLAT for all global memory accesses
1035       // on VI.
1036       // FIXME: This assumption is currently wrong.  On VI we still use
1037       // MUBUF instructions for the r + i addressing mode.  As currently
1038       // implemented, the MUBUF instructions only work on buffer < 4GB.
1039       // It may be possible to support > 4GB buffers with MUBUF instructions,
1040       // by setting the stride value in the resource descriptor which would
1041       // increase the size limit to (stride * 4GB).  However, this is risky,
1042       // because it has never been validated.
1043     return isLegalFlatAddressingMode(AM);
1044   }
1045 
1046   return isLegalMUBUFAddressingMode(AM);
1047 }
1048 
1049 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1050   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1051   // additionally can do r + r + i with addr64. 32-bit has more addressing
1052   // mode options. Depending on the resource constant, it can also do
1053   // (i64 r0) + (i32 r1) * (i14 i).
1054   //
1055   // Private arrays end up using a scratch buffer most of the time, so also
1056   // assume those use MUBUF instructions. Scratch loads / stores are currently
1057   // implemented as mubuf instructions with offen bit set, so slightly
1058   // different than the normal addr64.
1059   if (!isUInt<12>(AM.BaseOffs))
1060     return false;
1061 
1062   // FIXME: Since we can split immediate into soffset and immediate offset,
1063   // would it make sense to allow any immediate?
1064 
1065   switch (AM.Scale) {
1066   case 0: // r + i or just i, depending on HasBaseReg.
1067     return true;
1068   case 1:
1069     return true; // We have r + r or r + i.
1070   case 2:
1071     if (AM.HasBaseReg) {
1072       // Reject 2 * r + r.
1073       return false;
1074     }
1075 
1076     // Allow 2 * r as r + r
1077     // Or  2 * r + i is allowed as r + r + i.
1078     return true;
1079   default: // Don't allow n * r
1080     return false;
1081   }
1082 }
1083 
1084 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1085                                              const AddrMode &AM, Type *Ty,
1086                                              unsigned AS, Instruction *I) const {
1087   // No global is ever allowed as a base.
1088   if (AM.BaseGV)
1089     return false;
1090 
1091   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1092     return isLegalGlobalAddressingMode(AM);
1093 
1094   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1095       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1096       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1097     // If the offset isn't a multiple of 4, it probably isn't going to be
1098     // correctly aligned.
1099     // FIXME: Can we get the real alignment here?
1100     if (AM.BaseOffs % 4 != 0)
1101       return isLegalMUBUFAddressingMode(AM);
1102 
1103     // There are no SMRD extloads, so if we have to do a small type access we
1104     // will use a MUBUF load.
1105     // FIXME?: We also need to do this if unaligned, but we don't know the
1106     // alignment here.
1107     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1108       return isLegalGlobalAddressingMode(AM);
1109 
1110     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1111       // SMRD instructions have an 8-bit, dword offset on SI.
1112       if (!isUInt<8>(AM.BaseOffs / 4))
1113         return false;
1114     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1115       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1116       // in 8-bits, it can use a smaller encoding.
1117       if (!isUInt<32>(AM.BaseOffs / 4))
1118         return false;
1119     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1120       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1121       if (!isUInt<20>(AM.BaseOffs))
1122         return false;
1123     } else
1124       llvm_unreachable("unhandled generation");
1125 
1126     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1127       return true;
1128 
1129     if (AM.Scale == 1 && AM.HasBaseReg)
1130       return true;
1131 
1132     return false;
1133 
1134   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1135     return isLegalMUBUFAddressingMode(AM);
1136   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1137              AS == AMDGPUAS::REGION_ADDRESS) {
1138     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1139     // field.
1140     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1141     // an 8-bit dword offset but we don't know the alignment here.
1142     if (!isUInt<16>(AM.BaseOffs))
1143       return false;
1144 
1145     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1146       return true;
1147 
1148     if (AM.Scale == 1 && AM.HasBaseReg)
1149       return true;
1150 
1151     return false;
1152   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1153              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1154     // For an unknown address space, this usually means that this is for some
1155     // reason being used for pure arithmetic, and not based on some addressing
1156     // computation. We don't have instructions that compute pointers with any
1157     // addressing modes, so treat them as having no offset like flat
1158     // instructions.
1159     return isLegalFlatAddressingMode(AM);
1160   } else {
1161     llvm_unreachable("unhandled address space");
1162   }
1163 }
1164 
1165 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1166                                         const SelectionDAG &DAG) const {
1167   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1168     return (MemVT.getSizeInBits() <= 4 * 32);
1169   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1170     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1171     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1172   } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
1173     return (MemVT.getSizeInBits() <= 2 * 32);
1174   }
1175   return true;
1176 }
1177 
1178 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1179     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1180     bool *IsFast) const {
1181   if (IsFast)
1182     *IsFast = false;
1183 
1184   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1185   // which isn't a simple VT.
1186   // Until MVT is extended to handle this, simply check for the size and
1187   // rely on the condition below: allow accesses if the size is a multiple of 4.
1188   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1189                            VT.getStoreSize() > 16)) {
1190     return false;
1191   }
1192 
1193   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1194       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1195     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1196     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1197     // with adjacent offsets.
1198     bool AlignedBy4 = (Align % 4 == 0);
1199     if (IsFast)
1200       *IsFast = AlignedBy4;
1201 
1202     return AlignedBy4;
1203   }
1204 
1205   // FIXME: We have to be conservative here and assume that flat operations
1206   // will access scratch.  If we had access to the IR function, then we
1207   // could determine if any private memory was used in the function.
1208   if (!Subtarget->hasUnalignedScratchAccess() &&
1209       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1210        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1211     bool AlignedBy4 = Align >= 4;
1212     if (IsFast)
1213       *IsFast = AlignedBy4;
1214 
1215     return AlignedBy4;
1216   }
1217 
1218   if (Subtarget->hasUnalignedBufferAccess()) {
1219     // If we have an uniform constant load, it still requires using a slow
1220     // buffer instruction if unaligned.
1221     if (IsFast) {
1222       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1223                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1224         (Align % 4 == 0) : true;
1225     }
1226 
1227     return true;
1228   }
1229 
1230   // Smaller than dword value must be aligned.
1231   if (VT.bitsLT(MVT::i32))
1232     return false;
1233 
1234   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1235   // byte-address are ignored, thus forcing Dword alignment.
1236   // This applies to private, global, and constant memory.
1237   if (IsFast)
1238     *IsFast = true;
1239 
1240   return VT.bitsGT(MVT::i32) && Align % 4 == 0;
1241 }
1242 
1243 EVT SITargetLowering::getOptimalMemOpType(
1244     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
1245     bool ZeroMemset, bool MemcpyStrSrc,
1246     const AttributeList &FuncAttributes) const {
1247   // FIXME: Should account for address space here.
1248 
1249   // The default fallback uses the private pointer size as a guess for a type to
1250   // use. Make sure we switch these to 64-bit accesses.
1251 
1252   if (Size >= 16 && DstAlign >= 4) // XXX: Should only do for global
1253     return MVT::v4i32;
1254 
1255   if (Size >= 8 && DstAlign >= 4)
1256     return MVT::v2i32;
1257 
1258   // Use the default.
1259   return MVT::Other;
1260 }
1261 
1262 static bool isFlatGlobalAddrSpace(unsigned AS) {
1263   return AS == AMDGPUAS::GLOBAL_ADDRESS ||
1264          AS == AMDGPUAS::FLAT_ADDRESS ||
1265          AS == AMDGPUAS::CONSTANT_ADDRESS ||
1266          AS > AMDGPUAS::MAX_AMDGPU_ADDRESS;
1267 }
1268 
1269 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1270                                            unsigned DestAS) const {
1271   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1272 }
1273 
1274 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1275   const MemSDNode *MemNode = cast<MemSDNode>(N);
1276   const Value *Ptr = MemNode->getMemOperand()->getValue();
1277   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1278   return I && I->getMetadata("amdgpu.noclobber");
1279 }
1280 
1281 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1282                                            unsigned DestAS) const {
1283   // Flat -> private/local is a simple truncate.
1284   // Flat -> global is no-op
1285   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1286     return true;
1287 
1288   return isNoopAddrSpaceCast(SrcAS, DestAS);
1289 }
1290 
1291 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1292   const MemSDNode *MemNode = cast<MemSDNode>(N);
1293 
1294   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1295 }
1296 
1297 TargetLoweringBase::LegalizeTypeAction
1298 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1299   if (VT.getVectorNumElements() != 1 && VT.getScalarType().bitsLE(MVT::i16))
1300     return TypeSplitVector;
1301 
1302   return TargetLoweringBase::getPreferredVectorAction(VT);
1303 }
1304 
1305 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1306                                                          Type *Ty) const {
1307   // FIXME: Could be smarter if called for vector constants.
1308   return true;
1309 }
1310 
1311 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1312   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1313     switch (Op) {
1314     case ISD::LOAD:
1315     case ISD::STORE:
1316 
1317     // These operations are done with 32-bit instructions anyway.
1318     case ISD::AND:
1319     case ISD::OR:
1320     case ISD::XOR:
1321     case ISD::SELECT:
1322       // TODO: Extensions?
1323       return true;
1324     default:
1325       return false;
1326     }
1327   }
1328 
1329   // SimplifySetCC uses this function to determine whether or not it should
1330   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1331   if (VT == MVT::i1 && Op == ISD::SETCC)
1332     return false;
1333 
1334   return TargetLowering::isTypeDesirableForOp(Op, VT);
1335 }
1336 
1337 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1338                                                    const SDLoc &SL,
1339                                                    SDValue Chain,
1340                                                    uint64_t Offset) const {
1341   const DataLayout &DL = DAG.getDataLayout();
1342   MachineFunction &MF = DAG.getMachineFunction();
1343   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1344 
1345   const ArgDescriptor *InputPtrReg;
1346   const TargetRegisterClass *RC;
1347 
1348   std::tie(InputPtrReg, RC)
1349     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1350 
1351   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1352   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1353   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1354     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1355 
1356   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1357 }
1358 
1359 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1360                                             const SDLoc &SL) const {
1361   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1362                                                FIRST_IMPLICIT);
1363   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1364 }
1365 
1366 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1367                                          const SDLoc &SL, SDValue Val,
1368                                          bool Signed,
1369                                          const ISD::InputArg *Arg) const {
1370   // First, if it is a widened vector, narrow it.
1371   if (VT.isVector() &&
1372       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1373     EVT NarrowedVT =
1374         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1375                          VT.getVectorNumElements());
1376     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1377                       DAG.getConstant(0, SL, MVT::i32));
1378   }
1379 
1380   // Then convert the vector elements or scalar value.
1381   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1382       VT.bitsLT(MemVT)) {
1383     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1384     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1385   }
1386 
1387   if (MemVT.isFloatingPoint())
1388     Val = getFPExtOrFPTrunc(DAG, Val, SL, VT);
1389   else if (Signed)
1390     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1391   else
1392     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1393 
1394   return Val;
1395 }
1396 
1397 SDValue SITargetLowering::lowerKernargMemParameter(
1398   SelectionDAG &DAG, EVT VT, EVT MemVT,
1399   const SDLoc &SL, SDValue Chain,
1400   uint64_t Offset, unsigned Align, bool Signed,
1401   const ISD::InputArg *Arg) const {
1402   Type *Ty = MemVT.getTypeForEVT(*DAG.getContext());
1403   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
1404   MachinePointerInfo PtrInfo(UndefValue::get(PtrTy));
1405 
1406   // Try to avoid using an extload by loading earlier than the argument address,
1407   // and extracting the relevant bits. The load should hopefully be merged with
1408   // the previous argument.
1409   if (MemVT.getStoreSize() < 4 && Align < 4) {
1410     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1411     int64_t AlignDownOffset = alignDown(Offset, 4);
1412     int64_t OffsetDiff = Offset - AlignDownOffset;
1413 
1414     EVT IntVT = MemVT.changeTypeToInteger();
1415 
1416     // TODO: If we passed in the base kernel offset we could have a better
1417     // alignment than 4, but we don't really need it.
1418     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1419     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1420                                MachineMemOperand::MODereferenceable |
1421                                MachineMemOperand::MOInvariant);
1422 
1423     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1424     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1425 
1426     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1427     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1428     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1429 
1430 
1431     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1432   }
1433 
1434   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1435   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1436                              MachineMemOperand::MODereferenceable |
1437                              MachineMemOperand::MOInvariant);
1438 
1439   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1440   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1441 }
1442 
1443 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1444                                               const SDLoc &SL, SDValue Chain,
1445                                               const ISD::InputArg &Arg) const {
1446   MachineFunction &MF = DAG.getMachineFunction();
1447   MachineFrameInfo &MFI = MF.getFrameInfo();
1448 
1449   if (Arg.Flags.isByVal()) {
1450     unsigned Size = Arg.Flags.getByValSize();
1451     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1452     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1453   }
1454 
1455   unsigned ArgOffset = VA.getLocMemOffset();
1456   unsigned ArgSize = VA.getValVT().getStoreSize();
1457 
1458   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1459 
1460   // Create load nodes to retrieve arguments from the stack.
1461   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1462   SDValue ArgValue;
1463 
1464   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1465   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1466   MVT MemVT = VA.getValVT();
1467 
1468   switch (VA.getLocInfo()) {
1469   default:
1470     break;
1471   case CCValAssign::BCvt:
1472     MemVT = VA.getLocVT();
1473     break;
1474   case CCValAssign::SExt:
1475     ExtType = ISD::SEXTLOAD;
1476     break;
1477   case CCValAssign::ZExt:
1478     ExtType = ISD::ZEXTLOAD;
1479     break;
1480   case CCValAssign::AExt:
1481     ExtType = ISD::EXTLOAD;
1482     break;
1483   }
1484 
1485   ArgValue = DAG.getExtLoad(
1486     ExtType, SL, VA.getLocVT(), Chain, FIN,
1487     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1488     MemVT);
1489   return ArgValue;
1490 }
1491 
1492 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1493   const SIMachineFunctionInfo &MFI,
1494   EVT VT,
1495   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1496   const ArgDescriptor *Reg;
1497   const TargetRegisterClass *RC;
1498 
1499   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1500   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1501 }
1502 
1503 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1504                                    CallingConv::ID CallConv,
1505                                    ArrayRef<ISD::InputArg> Ins,
1506                                    BitVector &Skipped,
1507                                    FunctionType *FType,
1508                                    SIMachineFunctionInfo *Info) {
1509   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1510     const ISD::InputArg *Arg = &Ins[I];
1511 
1512     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1513            "vector type argument should have been split");
1514 
1515     // First check if it's a PS input addr.
1516     if (CallConv == CallingConv::AMDGPU_PS &&
1517         !Arg->Flags.isInReg() && !Arg->Flags.isByVal() && PSInputNum <= 15) {
1518 
1519       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1520 
1521       // Inconveniently only the first part of the split is marked as isSplit,
1522       // so skip to the end. We only want to increment PSInputNum once for the
1523       // entire split argument.
1524       if (Arg->Flags.isSplit()) {
1525         while (!Arg->Flags.isSplitEnd()) {
1526           assert(!Arg->VT.isVector() &&
1527                  "unexpected vector split in ps argument type");
1528           if (!SkipArg)
1529             Splits.push_back(*Arg);
1530           Arg = &Ins[++I];
1531         }
1532       }
1533 
1534       if (SkipArg) {
1535         // We can safely skip PS inputs.
1536         Skipped.set(Arg->getOrigArgIndex());
1537         ++PSInputNum;
1538         continue;
1539       }
1540 
1541       Info->markPSInputAllocated(PSInputNum);
1542       if (Arg->Used)
1543         Info->markPSInputEnabled(PSInputNum);
1544 
1545       ++PSInputNum;
1546     }
1547 
1548     Splits.push_back(*Arg);
1549   }
1550 }
1551 
1552 // Allocate special inputs passed in VGPRs.
1553 static void allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1554                                            MachineFunction &MF,
1555                                            const SIRegisterInfo &TRI,
1556                                            SIMachineFunctionInfo &Info) {
1557   if (Info.hasWorkItemIDX()) {
1558     unsigned Reg = AMDGPU::VGPR0;
1559     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1560 
1561     CCInfo.AllocateReg(Reg);
1562     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1563   }
1564 
1565   if (Info.hasWorkItemIDY()) {
1566     unsigned Reg = AMDGPU::VGPR1;
1567     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1568 
1569     CCInfo.AllocateReg(Reg);
1570     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1571   }
1572 
1573   if (Info.hasWorkItemIDZ()) {
1574     unsigned Reg = AMDGPU::VGPR2;
1575     MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1576 
1577     CCInfo.AllocateReg(Reg);
1578     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1579   }
1580 }
1581 
1582 // Try to allocate a VGPR at the end of the argument list, or if no argument
1583 // VGPRs are left allocating a stack slot.
1584 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo) {
1585   ArrayRef<MCPhysReg> ArgVGPRs
1586     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1587   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1588   if (RegIdx == ArgVGPRs.size()) {
1589     // Spill to stack required.
1590     int64_t Offset = CCInfo.AllocateStack(4, 4);
1591 
1592     return ArgDescriptor::createStack(Offset);
1593   }
1594 
1595   unsigned Reg = ArgVGPRs[RegIdx];
1596   Reg = CCInfo.AllocateReg(Reg);
1597   assert(Reg != AMDGPU::NoRegister);
1598 
1599   MachineFunction &MF = CCInfo.getMachineFunction();
1600   MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1601   return ArgDescriptor::createRegister(Reg);
1602 }
1603 
1604 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1605                                              const TargetRegisterClass *RC,
1606                                              unsigned NumArgRegs) {
1607   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1608   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1609   if (RegIdx == ArgSGPRs.size())
1610     report_fatal_error("ran out of SGPRs for arguments");
1611 
1612   unsigned Reg = ArgSGPRs[RegIdx];
1613   Reg = CCInfo.AllocateReg(Reg);
1614   assert(Reg != AMDGPU::NoRegister);
1615 
1616   MachineFunction &MF = CCInfo.getMachineFunction();
1617   MF.addLiveIn(Reg, RC);
1618   return ArgDescriptor::createRegister(Reg);
1619 }
1620 
1621 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1622   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1623 }
1624 
1625 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1626   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1627 }
1628 
1629 static void allocateSpecialInputVGPRs(CCState &CCInfo,
1630                                       MachineFunction &MF,
1631                                       const SIRegisterInfo &TRI,
1632                                       SIMachineFunctionInfo &Info) {
1633   if (Info.hasWorkItemIDX())
1634     Info.setWorkItemIDX(allocateVGPR32Input(CCInfo));
1635 
1636   if (Info.hasWorkItemIDY())
1637     Info.setWorkItemIDY(allocateVGPR32Input(CCInfo));
1638 
1639   if (Info.hasWorkItemIDZ())
1640     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo));
1641 }
1642 
1643 static void allocateSpecialInputSGPRs(CCState &CCInfo,
1644                                       MachineFunction &MF,
1645                                       const SIRegisterInfo &TRI,
1646                                       SIMachineFunctionInfo &Info) {
1647   auto &ArgInfo = Info.getArgInfo();
1648 
1649   // TODO: Unify handling with private memory pointers.
1650 
1651   if (Info.hasDispatchPtr())
1652     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1653 
1654   if (Info.hasQueuePtr())
1655     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1656 
1657   if (Info.hasKernargSegmentPtr())
1658     ArgInfo.KernargSegmentPtr = allocateSGPR64Input(CCInfo);
1659 
1660   if (Info.hasDispatchID())
1661     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1662 
1663   // flat_scratch_init is not applicable for non-kernel functions.
1664 
1665   if (Info.hasWorkGroupIDX())
1666     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1667 
1668   if (Info.hasWorkGroupIDY())
1669     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1670 
1671   if (Info.hasWorkGroupIDZ())
1672     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1673 
1674   if (Info.hasImplicitArgPtr())
1675     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1676 }
1677 
1678 // Allocate special inputs passed in user SGPRs.
1679 static void allocateHSAUserSGPRs(CCState &CCInfo,
1680                                  MachineFunction &MF,
1681                                  const SIRegisterInfo &TRI,
1682                                  SIMachineFunctionInfo &Info) {
1683   if (Info.hasImplicitBufferPtr()) {
1684     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1685     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1686     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1687   }
1688 
1689   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1690   if (Info.hasPrivateSegmentBuffer()) {
1691     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1692     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1693     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1694   }
1695 
1696   if (Info.hasDispatchPtr()) {
1697     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1698     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1699     CCInfo.AllocateReg(DispatchPtrReg);
1700   }
1701 
1702   if (Info.hasQueuePtr()) {
1703     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1704     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1705     CCInfo.AllocateReg(QueuePtrReg);
1706   }
1707 
1708   if (Info.hasKernargSegmentPtr()) {
1709     unsigned InputPtrReg = Info.addKernargSegmentPtr(TRI);
1710     MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1711     CCInfo.AllocateReg(InputPtrReg);
1712   }
1713 
1714   if (Info.hasDispatchID()) {
1715     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1716     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1717     CCInfo.AllocateReg(DispatchIDReg);
1718   }
1719 
1720   if (Info.hasFlatScratchInit()) {
1721     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1722     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1723     CCInfo.AllocateReg(FlatScratchInitReg);
1724   }
1725 
1726   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1727   // these from the dispatch pointer.
1728 }
1729 
1730 // Allocate special input registers that are initialized per-wave.
1731 static void allocateSystemSGPRs(CCState &CCInfo,
1732                                 MachineFunction &MF,
1733                                 SIMachineFunctionInfo &Info,
1734                                 CallingConv::ID CallConv,
1735                                 bool IsShader) {
1736   if (Info.hasWorkGroupIDX()) {
1737     unsigned Reg = Info.addWorkGroupIDX();
1738     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1739     CCInfo.AllocateReg(Reg);
1740   }
1741 
1742   if (Info.hasWorkGroupIDY()) {
1743     unsigned Reg = Info.addWorkGroupIDY();
1744     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1745     CCInfo.AllocateReg(Reg);
1746   }
1747 
1748   if (Info.hasWorkGroupIDZ()) {
1749     unsigned Reg = Info.addWorkGroupIDZ();
1750     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1751     CCInfo.AllocateReg(Reg);
1752   }
1753 
1754   if (Info.hasWorkGroupInfo()) {
1755     unsigned Reg = Info.addWorkGroupInfo();
1756     MF.addLiveIn(Reg, &AMDGPU::SReg_32_XM0RegClass);
1757     CCInfo.AllocateReg(Reg);
1758   }
1759 
1760   if (Info.hasPrivateSegmentWaveByteOffset()) {
1761     // Scratch wave offset passed in system SGPR.
1762     unsigned PrivateSegmentWaveByteOffsetReg;
1763 
1764     if (IsShader) {
1765       PrivateSegmentWaveByteOffsetReg =
1766         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1767 
1768       // This is true if the scratch wave byte offset doesn't have a fixed
1769       // location.
1770       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1771         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1772         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1773       }
1774     } else
1775       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1776 
1777     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1778     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1779   }
1780 }
1781 
1782 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1783                                      MachineFunction &MF,
1784                                      const SIRegisterInfo &TRI,
1785                                      SIMachineFunctionInfo &Info) {
1786   // Now that we've figured out where the scratch register inputs are, see if
1787   // should reserve the arguments and use them directly.
1788   MachineFrameInfo &MFI = MF.getFrameInfo();
1789   bool HasStackObjects = MFI.hasStackObjects();
1790   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1791 
1792   // Record that we know we have non-spill stack objects so we don't need to
1793   // check all stack objects later.
1794   if (HasStackObjects)
1795     Info.setHasNonSpillStackObjects(true);
1796 
1797   // Everything live out of a block is spilled with fast regalloc, so it's
1798   // almost certain that spilling will be required.
1799   if (TM.getOptLevel() == CodeGenOpt::None)
1800     HasStackObjects = true;
1801 
1802   // For now assume stack access is needed in any callee functions, so we need
1803   // the scratch registers to pass in.
1804   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
1805 
1806   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
1807     // If we have stack objects, we unquestionably need the private buffer
1808     // resource. For the Code Object V2 ABI, this will be the first 4 user
1809     // SGPR inputs. We can reserve those and use them directly.
1810 
1811     unsigned PrivateSegmentBufferReg =
1812         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
1813     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
1814   } else {
1815     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
1816     // We tentatively reserve the last registers (skipping the last registers
1817     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
1818     // we'll replace these with the ones immediately after those which were
1819     // really allocated. In the prologue copies will be inserted from the
1820     // argument to these reserved registers.
1821 
1822     // Without HSA, relocations are used for the scratch pointer and the
1823     // buffer resource setup is always inserted in the prologue. Scratch wave
1824     // offset is still in an input SGPR.
1825     Info.setScratchRSrcReg(ReservedBufferReg);
1826   }
1827 
1828   // This should be accurate for kernels even before the frame is finalized.
1829   const bool HasFP = ST.getFrameLowering()->hasFP(MF);
1830   if (HasFP) {
1831     unsigned ReservedOffsetReg =
1832         TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1833     MachineRegisterInfo &MRI = MF.getRegInfo();
1834 
1835     // Try to use s32 as the SP, but move it if it would interfere with input
1836     // arguments. This won't work with calls though.
1837     //
1838     // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
1839     // registers.
1840     if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
1841       Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
1842     } else {
1843       assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
1844 
1845       if (MFI.hasCalls())
1846         report_fatal_error("call in graphics shader with too many input SGPRs");
1847 
1848       for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
1849         if (!MRI.isLiveIn(Reg)) {
1850           Info.setStackPtrOffsetReg(Reg);
1851           break;
1852         }
1853       }
1854 
1855       if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
1856         report_fatal_error("failed to find register for SP");
1857     }
1858 
1859     Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1860     Info.setFrameOffsetReg(ReservedOffsetReg);
1861   } else if (RequiresStackAccess) {
1862     assert(!MFI.hasCalls());
1863     // We know there are accesses and they will be done relative to SP, so just
1864     // pin it to the input.
1865     //
1866     // FIXME: Should not do this if inline asm is reading/writing these
1867     // registers.
1868     unsigned PreloadedSP = Info.getPreloadedReg(
1869         AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_WAVE_BYTE_OFFSET);
1870 
1871     Info.setStackPtrOffsetReg(PreloadedSP);
1872     Info.setScratchWaveOffsetReg(PreloadedSP);
1873     Info.setFrameOffsetReg(PreloadedSP);
1874   } else {
1875     assert(!MFI.hasCalls());
1876 
1877     // There may not be stack access at all. There may still be spills, or
1878     // access of a constant pointer (in which cases an extra copy will be
1879     // emitted in the prolog).
1880     unsigned ReservedOffsetReg
1881       = TRI.reservedPrivateSegmentWaveByteOffsetReg(MF);
1882     Info.setStackPtrOffsetReg(ReservedOffsetReg);
1883     Info.setScratchWaveOffsetReg(ReservedOffsetReg);
1884     Info.setFrameOffsetReg(ReservedOffsetReg);
1885   }
1886 }
1887 
1888 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
1889   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
1890   return !Info->isEntryFunction();
1891 }
1892 
1893 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
1894 
1895 }
1896 
1897 void SITargetLowering::insertCopiesSplitCSR(
1898   MachineBasicBlock *Entry,
1899   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
1900   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1901 
1902   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
1903   if (!IStart)
1904     return;
1905 
1906   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
1907   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
1908   MachineBasicBlock::iterator MBBI = Entry->begin();
1909   for (const MCPhysReg *I = IStart; *I; ++I) {
1910     const TargetRegisterClass *RC = nullptr;
1911     if (AMDGPU::SReg_64RegClass.contains(*I))
1912       RC = &AMDGPU::SGPR_64RegClass;
1913     else if (AMDGPU::SReg_32RegClass.contains(*I))
1914       RC = &AMDGPU::SGPR_32RegClass;
1915     else
1916       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
1917 
1918     unsigned NewVR = MRI->createVirtualRegister(RC);
1919     // Create copy from CSR to a virtual register.
1920     Entry->addLiveIn(*I);
1921     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
1922       .addReg(*I);
1923 
1924     // Insert the copy-back instructions right before the terminator.
1925     for (auto *Exit : Exits)
1926       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
1927               TII->get(TargetOpcode::COPY), *I)
1928         .addReg(NewVR);
1929   }
1930 }
1931 
1932 SDValue SITargetLowering::LowerFormalArguments(
1933     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
1934     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
1935     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
1936   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
1937 
1938   MachineFunction &MF = DAG.getMachineFunction();
1939   const Function &Fn = MF.getFunction();
1940   FunctionType *FType = MF.getFunction().getFunctionType();
1941   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1942 
1943   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
1944     DiagnosticInfoUnsupported NoGraphicsHSA(
1945         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
1946     DAG.getContext()->diagnose(NoGraphicsHSA);
1947     return DAG.getEntryNode();
1948   }
1949 
1950   SmallVector<ISD::InputArg, 16> Splits;
1951   SmallVector<CCValAssign, 16> ArgLocs;
1952   BitVector Skipped(Ins.size());
1953   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
1954                  *DAG.getContext());
1955 
1956   bool IsShader = AMDGPU::isShader(CallConv);
1957   bool IsKernel = AMDGPU::isKernel(CallConv);
1958   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
1959 
1960   if (IsShader) {
1961     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
1962 
1963     // At least one interpolation mode must be enabled or else the GPU will
1964     // hang.
1965     //
1966     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
1967     // set PSInputAddr, the user wants to enable some bits after the compilation
1968     // based on run-time states. Since we can't know what the final PSInputEna
1969     // will look like, so we shouldn't do anything here and the user should take
1970     // responsibility for the correct programming.
1971     //
1972     // Otherwise, the following restrictions apply:
1973     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
1974     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
1975     //   enabled too.
1976     if (CallConv == CallingConv::AMDGPU_PS) {
1977       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
1978            ((Info->getPSInputAddr() & 0xF) == 0 &&
1979             Info->isPSInputAllocated(11))) {
1980         CCInfo.AllocateReg(AMDGPU::VGPR0);
1981         CCInfo.AllocateReg(AMDGPU::VGPR1);
1982         Info->markPSInputAllocated(0);
1983         Info->markPSInputEnabled(0);
1984       }
1985       if (Subtarget->isAmdPalOS()) {
1986         // For isAmdPalOS, the user does not enable some bits after compilation
1987         // based on run-time states; the register values being generated here are
1988         // the final ones set in hardware. Therefore we need to apply the
1989         // workaround to PSInputAddr and PSInputEnable together.  (The case where
1990         // a bit is set in PSInputAddr but not PSInputEnable is where the
1991         // frontend set up an input arg for a particular interpolation mode, but
1992         // nothing uses that input arg. Really we should have an earlier pass
1993         // that removes such an arg.)
1994         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
1995         if ((PsInputBits & 0x7F) == 0 ||
1996             ((PsInputBits & 0xF) == 0 &&
1997              (PsInputBits >> 11 & 1)))
1998           Info->markPSInputEnabled(
1999               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2000       }
2001     }
2002 
2003     assert(!Info->hasDispatchPtr() &&
2004            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2005            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2006            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2007            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2008            !Info->hasWorkItemIDZ());
2009   } else if (IsKernel) {
2010     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2011   } else {
2012     Splits.append(Ins.begin(), Ins.end());
2013   }
2014 
2015   if (IsEntryFunc) {
2016     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2017     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2018   }
2019 
2020   if (IsKernel) {
2021     analyzeFormalArgumentsCompute(CCInfo, Ins);
2022   } else {
2023     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2024     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2025   }
2026 
2027   SmallVector<SDValue, 16> Chains;
2028 
2029   // FIXME: This is the minimum kernel argument alignment. We should improve
2030   // this to the maximum alignment of the arguments.
2031   //
2032   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2033   // kern arg offset.
2034   const unsigned KernelArgBaseAlign = 16;
2035 
2036    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2037     const ISD::InputArg &Arg = Ins[i];
2038     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2039       InVals.push_back(DAG.getUNDEF(Arg.VT));
2040       continue;
2041     }
2042 
2043     CCValAssign &VA = ArgLocs[ArgIdx++];
2044     MVT VT = VA.getLocVT();
2045 
2046     if (IsEntryFunc && VA.isMemLoc()) {
2047       VT = Ins[i].VT;
2048       EVT MemVT = VA.getLocVT();
2049 
2050       const uint64_t Offset = VA.getLocMemOffset();
2051       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2052 
2053       SDValue Arg = lowerKernargMemParameter(
2054         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2055       Chains.push_back(Arg.getValue(1));
2056 
2057       auto *ParamTy =
2058         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2059       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2060           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2061                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2062         // On SI local pointers are just offsets into LDS, so they are always
2063         // less than 16-bits.  On CI and newer they could potentially be
2064         // real pointers, so we can't guarantee their size.
2065         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2066                           DAG.getValueType(MVT::i16));
2067       }
2068 
2069       InVals.push_back(Arg);
2070       continue;
2071     } else if (!IsEntryFunc && VA.isMemLoc()) {
2072       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2073       InVals.push_back(Val);
2074       if (!Arg.Flags.isByVal())
2075         Chains.push_back(Val.getValue(1));
2076       continue;
2077     }
2078 
2079     assert(VA.isRegLoc() && "Parameter must be in a register!");
2080 
2081     unsigned Reg = VA.getLocReg();
2082     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2083     EVT ValVT = VA.getValVT();
2084 
2085     Reg = MF.addLiveIn(Reg, RC);
2086     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2087 
2088     if (Arg.Flags.isSRet()) {
2089       // The return object should be reasonably addressable.
2090 
2091       // FIXME: This helps when the return is a real sret. If it is a
2092       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2093       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2094       unsigned NumBits
2095         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2096       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2097         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2098     }
2099 
2100     // If this is an 8 or 16-bit value, it is really passed promoted
2101     // to 32 bits. Insert an assert[sz]ext to capture this, then
2102     // truncate to the right size.
2103     switch (VA.getLocInfo()) {
2104     case CCValAssign::Full:
2105       break;
2106     case CCValAssign::BCvt:
2107       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2108       break;
2109     case CCValAssign::SExt:
2110       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2111                         DAG.getValueType(ValVT));
2112       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2113       break;
2114     case CCValAssign::ZExt:
2115       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2116                         DAG.getValueType(ValVT));
2117       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2118       break;
2119     case CCValAssign::AExt:
2120       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2121       break;
2122     default:
2123       llvm_unreachable("Unknown loc info!");
2124     }
2125 
2126     InVals.push_back(Val);
2127   }
2128 
2129   if (!IsEntryFunc) {
2130     // Special inputs come after user arguments.
2131     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2132   }
2133 
2134   // Start adding system SGPRs.
2135   if (IsEntryFunc) {
2136     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2137   } else {
2138     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2139     CCInfo.AllocateReg(Info->getScratchWaveOffsetReg());
2140     CCInfo.AllocateReg(Info->getFrameOffsetReg());
2141     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2142   }
2143 
2144   auto &ArgUsageInfo =
2145     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2146   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2147 
2148   unsigned StackArgSize = CCInfo.getNextStackOffset();
2149   Info->setBytesInStackArgArea(StackArgSize);
2150 
2151   return Chains.empty() ? Chain :
2152     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2153 }
2154 
2155 // TODO: If return values can't fit in registers, we should return as many as
2156 // possible in registers before passing on stack.
2157 bool SITargetLowering::CanLowerReturn(
2158   CallingConv::ID CallConv,
2159   MachineFunction &MF, bool IsVarArg,
2160   const SmallVectorImpl<ISD::OutputArg> &Outs,
2161   LLVMContext &Context) const {
2162   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2163   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2164   // for shaders. Vector types should be explicitly handled by CC.
2165   if (AMDGPU::isEntryFunctionCC(CallConv))
2166     return true;
2167 
2168   SmallVector<CCValAssign, 16> RVLocs;
2169   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2170   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2171 }
2172 
2173 SDValue
2174 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2175                               bool isVarArg,
2176                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2177                               const SmallVectorImpl<SDValue> &OutVals,
2178                               const SDLoc &DL, SelectionDAG &DAG) const {
2179   MachineFunction &MF = DAG.getMachineFunction();
2180   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2181 
2182   if (AMDGPU::isKernel(CallConv)) {
2183     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2184                                              OutVals, DL, DAG);
2185   }
2186 
2187   bool IsShader = AMDGPU::isShader(CallConv);
2188 
2189   Info->setIfReturnsVoid(Outs.empty());
2190   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2191 
2192   // CCValAssign - represent the assignment of the return value to a location.
2193   SmallVector<CCValAssign, 48> RVLocs;
2194   SmallVector<ISD::OutputArg, 48> Splits;
2195 
2196   // CCState - Info about the registers and stack slots.
2197   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2198                  *DAG.getContext());
2199 
2200   // Analyze outgoing return values.
2201   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2202 
2203   SDValue Flag;
2204   SmallVector<SDValue, 48> RetOps;
2205   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2206 
2207   // Add return address for callable functions.
2208   if (!Info->isEntryFunction()) {
2209     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2210     SDValue ReturnAddrReg = CreateLiveInRegister(
2211       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2212 
2213     // FIXME: Should be able to use a vreg here, but need a way to prevent it
2214     // from being allcoated to a CSR.
2215 
2216     SDValue PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2217                                                 MVT::i64);
2218 
2219     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, Flag);
2220     Flag = Chain.getValue(1);
2221 
2222     RetOps.push_back(PhysReturnAddrReg);
2223   }
2224 
2225   // Copy the result values into the output registers.
2226   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2227        ++I, ++RealRVLocIdx) {
2228     CCValAssign &VA = RVLocs[I];
2229     assert(VA.isRegLoc() && "Can only return in registers!");
2230     // TODO: Partially return in registers if return values don't fit.
2231     SDValue Arg = OutVals[RealRVLocIdx];
2232 
2233     // Copied from other backends.
2234     switch (VA.getLocInfo()) {
2235     case CCValAssign::Full:
2236       break;
2237     case CCValAssign::BCvt:
2238       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2239       break;
2240     case CCValAssign::SExt:
2241       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2242       break;
2243     case CCValAssign::ZExt:
2244       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2245       break;
2246     case CCValAssign::AExt:
2247       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2248       break;
2249     default:
2250       llvm_unreachable("Unknown loc info!");
2251     }
2252 
2253     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2254     Flag = Chain.getValue(1);
2255     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2256   }
2257 
2258   // FIXME: Does sret work properly?
2259   if (!Info->isEntryFunction()) {
2260     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2261     const MCPhysReg *I =
2262       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2263     if (I) {
2264       for (; *I; ++I) {
2265         if (AMDGPU::SReg_64RegClass.contains(*I))
2266           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2267         else if (AMDGPU::SReg_32RegClass.contains(*I))
2268           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2269         else
2270           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2271       }
2272     }
2273   }
2274 
2275   // Update chain and glue.
2276   RetOps[0] = Chain;
2277   if (Flag.getNode())
2278     RetOps.push_back(Flag);
2279 
2280   unsigned Opc = AMDGPUISD::ENDPGM;
2281   if (!IsWaveEnd)
2282     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2283   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2284 }
2285 
2286 SDValue SITargetLowering::LowerCallResult(
2287     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2288     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2289     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2290     SDValue ThisVal) const {
2291   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2292 
2293   // Assign locations to each value returned by this call.
2294   SmallVector<CCValAssign, 16> RVLocs;
2295   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2296                  *DAG.getContext());
2297   CCInfo.AnalyzeCallResult(Ins, RetCC);
2298 
2299   // Copy all of the result registers out of their specified physreg.
2300   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2301     CCValAssign VA = RVLocs[i];
2302     SDValue Val;
2303 
2304     if (VA.isRegLoc()) {
2305       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2306       Chain = Val.getValue(1);
2307       InFlag = Val.getValue(2);
2308     } else if (VA.isMemLoc()) {
2309       report_fatal_error("TODO: return values in memory");
2310     } else
2311       llvm_unreachable("unknown argument location type");
2312 
2313     switch (VA.getLocInfo()) {
2314     case CCValAssign::Full:
2315       break;
2316     case CCValAssign::BCvt:
2317       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2318       break;
2319     case CCValAssign::ZExt:
2320       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2321                         DAG.getValueType(VA.getValVT()));
2322       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2323       break;
2324     case CCValAssign::SExt:
2325       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2326                         DAG.getValueType(VA.getValVT()));
2327       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2328       break;
2329     case CCValAssign::AExt:
2330       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2331       break;
2332     default:
2333       llvm_unreachable("Unknown loc info!");
2334     }
2335 
2336     InVals.push_back(Val);
2337   }
2338 
2339   return Chain;
2340 }
2341 
2342 // Add code to pass special inputs required depending on used features separate
2343 // from the explicit user arguments present in the IR.
2344 void SITargetLowering::passSpecialInputs(
2345     CallLoweringInfo &CLI,
2346     CCState &CCInfo,
2347     const SIMachineFunctionInfo &Info,
2348     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2349     SmallVectorImpl<SDValue> &MemOpChains,
2350     SDValue Chain) const {
2351   // If we don't have a call site, this was a call inserted by
2352   // legalization. These can never use special inputs.
2353   if (!CLI.CS)
2354     return;
2355 
2356   const Function *CalleeFunc = CLI.CS.getCalledFunction();
2357   assert(CalleeFunc);
2358 
2359   SelectionDAG &DAG = CLI.DAG;
2360   const SDLoc &DL = CLI.DL;
2361 
2362   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2363 
2364   auto &ArgUsageInfo =
2365     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2366   const AMDGPUFunctionArgInfo &CalleeArgInfo
2367     = ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2368 
2369   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2370 
2371   // TODO: Unify with private memory register handling. This is complicated by
2372   // the fact that at least in kernels, the input argument is not necessarily
2373   // in the same location as the input.
2374   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2375     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2376     AMDGPUFunctionArgInfo::QUEUE_PTR,
2377     AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR,
2378     AMDGPUFunctionArgInfo::DISPATCH_ID,
2379     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2380     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2381     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z,
2382     AMDGPUFunctionArgInfo::WORKITEM_ID_X,
2383     AMDGPUFunctionArgInfo::WORKITEM_ID_Y,
2384     AMDGPUFunctionArgInfo::WORKITEM_ID_Z,
2385     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR
2386   };
2387 
2388   for (auto InputID : InputRegs) {
2389     const ArgDescriptor *OutgoingArg;
2390     const TargetRegisterClass *ArgRC;
2391 
2392     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo.getPreloadedValue(InputID);
2393     if (!OutgoingArg)
2394       continue;
2395 
2396     const ArgDescriptor *IncomingArg;
2397     const TargetRegisterClass *IncomingArgRC;
2398     std::tie(IncomingArg, IncomingArgRC)
2399       = CallerArgInfo.getPreloadedValue(InputID);
2400     assert(IncomingArgRC == ArgRC);
2401 
2402     // All special arguments are ints for now.
2403     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2404     SDValue InputReg;
2405 
2406     if (IncomingArg) {
2407       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2408     } else {
2409       // The implicit arg ptr is special because it doesn't have a corresponding
2410       // input for kernels, and is computed from the kernarg segment pointer.
2411       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2412       InputReg = getImplicitArgPtr(DAG, DL);
2413     }
2414 
2415     if (OutgoingArg->isRegister()) {
2416       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2417     } else {
2418       unsigned SpecialArgOffset = CCInfo.AllocateStack(ArgVT.getStoreSize(), 4);
2419       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2420                                               SpecialArgOffset);
2421       MemOpChains.push_back(ArgStore);
2422     }
2423   }
2424 }
2425 
2426 static bool canGuaranteeTCO(CallingConv::ID CC) {
2427   return CC == CallingConv::Fast;
2428 }
2429 
2430 /// Return true if we might ever do TCO for calls with this calling convention.
2431 static bool mayTailCallThisCC(CallingConv::ID CC) {
2432   switch (CC) {
2433   case CallingConv::C:
2434     return true;
2435   default:
2436     return canGuaranteeTCO(CC);
2437   }
2438 }
2439 
2440 bool SITargetLowering::isEligibleForTailCallOptimization(
2441     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2442     const SmallVectorImpl<ISD::OutputArg> &Outs,
2443     const SmallVectorImpl<SDValue> &OutVals,
2444     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2445   if (!mayTailCallThisCC(CalleeCC))
2446     return false;
2447 
2448   MachineFunction &MF = DAG.getMachineFunction();
2449   const Function &CallerF = MF.getFunction();
2450   CallingConv::ID CallerCC = CallerF.getCallingConv();
2451   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2452   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2453 
2454   // Kernels aren't callable, and don't have a live in return address so it
2455   // doesn't make sense to do a tail call with entry functions.
2456   if (!CallerPreserved)
2457     return false;
2458 
2459   bool CCMatch = CallerCC == CalleeCC;
2460 
2461   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2462     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2463       return true;
2464     return false;
2465   }
2466 
2467   // TODO: Can we handle var args?
2468   if (IsVarArg)
2469     return false;
2470 
2471   for (const Argument &Arg : CallerF.args()) {
2472     if (Arg.hasByValAttr())
2473       return false;
2474   }
2475 
2476   LLVMContext &Ctx = *DAG.getContext();
2477 
2478   // Check that the call results are passed in the same way.
2479   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2480                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2481                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2482     return false;
2483 
2484   // The callee has to preserve all registers the caller needs to preserve.
2485   if (!CCMatch) {
2486     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2487     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2488       return false;
2489   }
2490 
2491   // Nothing more to check if the callee is taking no arguments.
2492   if (Outs.empty())
2493     return true;
2494 
2495   SmallVector<CCValAssign, 16> ArgLocs;
2496   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2497 
2498   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2499 
2500   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2501   // If the stack arguments for this call do not fit into our own save area then
2502   // the call cannot be made tail.
2503   // TODO: Is this really necessary?
2504   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2505     return false;
2506 
2507   const MachineRegisterInfo &MRI = MF.getRegInfo();
2508   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2509 }
2510 
2511 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2512   if (!CI->isTailCall())
2513     return false;
2514 
2515   const Function *ParentFn = CI->getParent()->getParent();
2516   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2517     return false;
2518 
2519   auto Attr = ParentFn->getFnAttribute("disable-tail-calls");
2520   return (Attr.getValueAsString() != "true");
2521 }
2522 
2523 // The wave scratch offset register is used as the global base pointer.
2524 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2525                                     SmallVectorImpl<SDValue> &InVals) const {
2526   SelectionDAG &DAG = CLI.DAG;
2527   const SDLoc &DL = CLI.DL;
2528   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2529   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2530   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2531   SDValue Chain = CLI.Chain;
2532   SDValue Callee = CLI.Callee;
2533   bool &IsTailCall = CLI.IsTailCall;
2534   CallingConv::ID CallConv = CLI.CallConv;
2535   bool IsVarArg = CLI.IsVarArg;
2536   bool IsSibCall = false;
2537   bool IsThisReturn = false;
2538   MachineFunction &MF = DAG.getMachineFunction();
2539 
2540   if (IsVarArg) {
2541     return lowerUnhandledCall(CLI, InVals,
2542                               "unsupported call to variadic function ");
2543   }
2544 
2545   if (!CLI.CS.getInstruction())
2546     report_fatal_error("unsupported libcall legalization");
2547 
2548   if (!CLI.CS.getCalledFunction()) {
2549     return lowerUnhandledCall(CLI, InVals,
2550                               "unsupported indirect call to function ");
2551   }
2552 
2553   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2554     return lowerUnhandledCall(CLI, InVals,
2555                               "unsupported required tail call to function ");
2556   }
2557 
2558   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2559     // Note the issue is with the CC of the calling function, not of the call
2560     // itself.
2561     return lowerUnhandledCall(CLI, InVals,
2562                           "unsupported call from graphics shader of function ");
2563   }
2564 
2565   if (IsTailCall) {
2566     IsTailCall = isEligibleForTailCallOptimization(
2567       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2568     if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall()) {
2569       report_fatal_error("failed to perform tail call elimination on a call "
2570                          "site marked musttail");
2571     }
2572 
2573     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2574 
2575     // A sibling call is one where we're under the usual C ABI and not planning
2576     // to change that but can still do a tail call:
2577     if (!TailCallOpt && IsTailCall)
2578       IsSibCall = true;
2579 
2580     if (IsTailCall)
2581       ++NumTailCalls;
2582   }
2583 
2584   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2585 
2586   // Analyze operands of the call, assigning locations to each operand.
2587   SmallVector<CCValAssign, 16> ArgLocs;
2588   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2589   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2590 
2591   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2592 
2593   // Get a count of how many bytes are to be pushed on the stack.
2594   unsigned NumBytes = CCInfo.getNextStackOffset();
2595 
2596   if (IsSibCall) {
2597     // Since we're not changing the ABI to make this a tail call, the memory
2598     // operands are already available in the caller's incoming argument space.
2599     NumBytes = 0;
2600   }
2601 
2602   // FPDiff is the byte offset of the call's argument area from the callee's.
2603   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2604   // by this amount for a tail call. In a sibling call it must be 0 because the
2605   // caller will deallocate the entire stack and the callee still expects its
2606   // arguments to begin at SP+0. Completely unused for non-tail calls.
2607   int32_t FPDiff = 0;
2608   MachineFrameInfo &MFI = MF.getFrameInfo();
2609   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2610 
2611   SDValue CallerSavedFP;
2612 
2613   // Adjust the stack pointer for the new arguments...
2614   // These operations are automatically eliminated by the prolog/epilog pass
2615   if (!IsSibCall) {
2616     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2617 
2618     SmallVector<SDValue, 4> CopyFromChains;
2619 
2620     unsigned OffsetReg = Info->getScratchWaveOffsetReg();
2621 
2622     // In the HSA case, this should be an identity copy.
2623     SDValue ScratchRSrcReg
2624       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2625     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2626     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2627 
2628     // TODO: Don't hardcode these registers and get from the callee function.
2629     SDValue ScratchWaveOffsetReg
2630       = DAG.getCopyFromReg(Chain, DL, OffsetReg, MVT::i32);
2631     RegsToPass.emplace_back(AMDGPU::SGPR4, ScratchWaveOffsetReg);
2632     CopyFromChains.push_back(ScratchWaveOffsetReg.getValue(1));
2633 
2634     if (!Info->isEntryFunction()) {
2635       // Avoid clobbering this function's FP value. In the current convention
2636       // callee will overwrite this, so do save/restore around the call site.
2637       CallerSavedFP = DAG.getCopyFromReg(Chain, DL,
2638                                          Info->getFrameOffsetReg(), MVT::i32);
2639       CopyFromChains.push_back(CallerSavedFP.getValue(1));
2640     }
2641 
2642     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2643   }
2644 
2645   SmallVector<SDValue, 8> MemOpChains;
2646   MVT PtrVT = MVT::i32;
2647 
2648   // Walk the register/memloc assignments, inserting copies/loads.
2649   for (unsigned i = 0, realArgIdx = 0, e = ArgLocs.size(); i != e;
2650        ++i, ++realArgIdx) {
2651     CCValAssign &VA = ArgLocs[i];
2652     SDValue Arg = OutVals[realArgIdx];
2653 
2654     // Promote the value if needed.
2655     switch (VA.getLocInfo()) {
2656     case CCValAssign::Full:
2657       break;
2658     case CCValAssign::BCvt:
2659       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2660       break;
2661     case CCValAssign::ZExt:
2662       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2663       break;
2664     case CCValAssign::SExt:
2665       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2666       break;
2667     case CCValAssign::AExt:
2668       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2669       break;
2670     case CCValAssign::FPExt:
2671       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2672       break;
2673     default:
2674       llvm_unreachable("Unknown loc info!");
2675     }
2676 
2677     if (VA.isRegLoc()) {
2678       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2679     } else {
2680       assert(VA.isMemLoc());
2681 
2682       SDValue DstAddr;
2683       MachinePointerInfo DstInfo;
2684 
2685       unsigned LocMemOffset = VA.getLocMemOffset();
2686       int32_t Offset = LocMemOffset;
2687 
2688       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2689       unsigned Align = 0;
2690 
2691       if (IsTailCall) {
2692         ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
2693         unsigned OpSize = Flags.isByVal() ?
2694           Flags.getByValSize() : VA.getValVT().getStoreSize();
2695 
2696         // FIXME: We can have better than the minimum byval required alignment.
2697         Align = Flags.isByVal() ? Flags.getByValAlign() :
2698           MinAlign(Subtarget->getStackAlignment(), Offset);
2699 
2700         Offset = Offset + FPDiff;
2701         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2702 
2703         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2704         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2705 
2706         // Make sure any stack arguments overlapping with where we're storing
2707         // are loaded before this eventual operation. Otherwise they'll be
2708         // clobbered.
2709 
2710         // FIXME: Why is this really necessary? This seems to just result in a
2711         // lot of code to copy the stack and write them back to the same
2712         // locations, which are supposed to be immutable?
2713         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2714       } else {
2715         DstAddr = PtrOff;
2716         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2717         Align = MinAlign(Subtarget->getStackAlignment(), LocMemOffset);
2718       }
2719 
2720       if (Outs[i].Flags.isByVal()) {
2721         SDValue SizeNode =
2722             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2723         SDValue Cpy = DAG.getMemcpy(
2724             Chain, DL, DstAddr, Arg, SizeNode, Outs[i].Flags.getByValAlign(),
2725             /*isVol = */ false, /*AlwaysInline = */ true,
2726             /*isTailCall = */ false, DstInfo,
2727             MachinePointerInfo(UndefValue::get(Type::getInt8PtrTy(
2728                 *DAG.getContext(), AMDGPUAS::PRIVATE_ADDRESS))));
2729 
2730         MemOpChains.push_back(Cpy);
2731       } else {
2732         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Align);
2733         MemOpChains.push_back(Store);
2734       }
2735     }
2736   }
2737 
2738   // Copy special input registers after user input arguments.
2739   passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2740 
2741   if (!MemOpChains.empty())
2742     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2743 
2744   // Build a sequence of copy-to-reg nodes chained together with token chain
2745   // and flag operands which copy the outgoing args into the appropriate regs.
2746   SDValue InFlag;
2747   for (auto &RegToPass : RegsToPass) {
2748     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2749                              RegToPass.second, InFlag);
2750     InFlag = Chain.getValue(1);
2751   }
2752 
2753 
2754   SDValue PhysReturnAddrReg;
2755   if (IsTailCall) {
2756     // Since the return is being combined with the call, we need to pass on the
2757     // return address.
2758 
2759     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2760     SDValue ReturnAddrReg = CreateLiveInRegister(
2761       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2762 
2763     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
2764                                         MVT::i64);
2765     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
2766     InFlag = Chain.getValue(1);
2767   }
2768 
2769   // We don't usually want to end the call-sequence here because we would tidy
2770   // the frame up *after* the call, however in the ABI-changing tail-call case
2771   // we've carefully laid out the parameters so that when sp is reset they'll be
2772   // in the correct location.
2773   if (IsTailCall && !IsSibCall) {
2774     Chain = DAG.getCALLSEQ_END(Chain,
2775                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
2776                                DAG.getTargetConstant(0, DL, MVT::i32),
2777                                InFlag, DL);
2778     InFlag = Chain.getValue(1);
2779   }
2780 
2781   std::vector<SDValue> Ops;
2782   Ops.push_back(Chain);
2783   Ops.push_back(Callee);
2784   // Add a redundant copy of the callee global which will not be legalized, as
2785   // we need direct access to the callee later.
2786   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Callee);
2787   const GlobalValue *GV = GSD->getGlobal();
2788   Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
2789 
2790   if (IsTailCall) {
2791     // Each tail call may have to adjust the stack by a different amount, so
2792     // this information must travel along with the operation for eventual
2793     // consumption by emitEpilogue.
2794     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
2795 
2796     Ops.push_back(PhysReturnAddrReg);
2797   }
2798 
2799   // Add argument registers to the end of the list so that they are known live
2800   // into the call.
2801   for (auto &RegToPass : RegsToPass) {
2802     Ops.push_back(DAG.getRegister(RegToPass.first,
2803                                   RegToPass.second.getValueType()));
2804   }
2805 
2806   // Add a register mask operand representing the call-preserved registers.
2807 
2808   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
2809   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
2810   assert(Mask && "Missing call preserved mask for calling convention");
2811   Ops.push_back(DAG.getRegisterMask(Mask));
2812 
2813   if (InFlag.getNode())
2814     Ops.push_back(InFlag);
2815 
2816   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2817 
2818   // If we're doing a tall call, use a TC_RETURN here rather than an
2819   // actual call instruction.
2820   if (IsTailCall) {
2821     MFI.setHasTailCall();
2822     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
2823   }
2824 
2825   // Returns a chain and a flag for retval copy to use.
2826   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
2827   Chain = Call.getValue(0);
2828   InFlag = Call.getValue(1);
2829 
2830   if (CallerSavedFP) {
2831     SDValue FPReg = DAG.getRegister(Info->getFrameOffsetReg(), MVT::i32);
2832     Chain = DAG.getCopyToReg(Chain, DL, FPReg, CallerSavedFP, InFlag);
2833     InFlag = Chain.getValue(1);
2834   }
2835 
2836   uint64_t CalleePopBytes = NumBytes;
2837   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
2838                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
2839                              InFlag, DL);
2840   if (!Ins.empty())
2841     InFlag = Chain.getValue(1);
2842 
2843   // Handle result values, copying them out of physregs into vregs that we
2844   // return.
2845   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2846                          InVals, IsThisReturn,
2847                          IsThisReturn ? OutVals[0] : SDValue());
2848 }
2849 
2850 unsigned SITargetLowering::getRegisterByName(const char* RegName, EVT VT,
2851                                              SelectionDAG &DAG) const {
2852   unsigned Reg = StringSwitch<unsigned>(RegName)
2853     .Case("m0", AMDGPU::M0)
2854     .Case("exec", AMDGPU::EXEC)
2855     .Case("exec_lo", AMDGPU::EXEC_LO)
2856     .Case("exec_hi", AMDGPU::EXEC_HI)
2857     .Case("flat_scratch", AMDGPU::FLAT_SCR)
2858     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
2859     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
2860     .Default(AMDGPU::NoRegister);
2861 
2862   if (Reg == AMDGPU::NoRegister) {
2863     report_fatal_error(Twine("invalid register name \""
2864                              + StringRef(RegName)  + "\"."));
2865 
2866   }
2867 
2868   if ((Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS ||
2869        Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) &&
2870        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
2871     report_fatal_error(Twine("invalid register \""
2872                              + StringRef(RegName)  + "\" for subtarget."));
2873   }
2874 
2875   switch (Reg) {
2876   case AMDGPU::M0:
2877   case AMDGPU::EXEC_LO:
2878   case AMDGPU::EXEC_HI:
2879   case AMDGPU::FLAT_SCR_LO:
2880   case AMDGPU::FLAT_SCR_HI:
2881     if (VT.getSizeInBits() == 32)
2882       return Reg;
2883     break;
2884   case AMDGPU::EXEC:
2885   case AMDGPU::FLAT_SCR:
2886     if (VT.getSizeInBits() == 64)
2887       return Reg;
2888     break;
2889   default:
2890     llvm_unreachable("missing register type checking");
2891   }
2892 
2893   report_fatal_error(Twine("invalid type for register \""
2894                            + StringRef(RegName) + "\"."));
2895 }
2896 
2897 // If kill is not the last instruction, split the block so kill is always a
2898 // proper terminator.
2899 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
2900                                                     MachineBasicBlock *BB) const {
2901   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
2902 
2903   MachineBasicBlock::iterator SplitPoint(&MI);
2904   ++SplitPoint;
2905 
2906   if (SplitPoint == BB->end()) {
2907     // Don't bother with a new block.
2908     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2909     return BB;
2910   }
2911 
2912   MachineFunction *MF = BB->getParent();
2913   MachineBasicBlock *SplitBB
2914     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
2915 
2916   MF->insert(++MachineFunction::iterator(BB), SplitBB);
2917   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
2918 
2919   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
2920   BB->addSuccessor(SplitBB);
2921 
2922   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
2923   return SplitBB;
2924 }
2925 
2926 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
2927 // wavefront. If the value is uniform and just happens to be in a VGPR, this
2928 // will only do one iteration. In the worst case, this will loop 64 times.
2929 //
2930 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
2931 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
2932   const SIInstrInfo *TII,
2933   MachineRegisterInfo &MRI,
2934   MachineBasicBlock &OrigBB,
2935   MachineBasicBlock &LoopBB,
2936   const DebugLoc &DL,
2937   const MachineOperand &IdxReg,
2938   unsigned InitReg,
2939   unsigned ResultReg,
2940   unsigned PhiReg,
2941   unsigned InitSaveExecReg,
2942   int Offset,
2943   bool UseGPRIdxMode,
2944   bool IsIndirectSrc) {
2945   MachineFunction *MF = OrigBB.getParent();
2946   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
2947   const SIRegisterInfo *TRI = ST.getRegisterInfo();
2948   MachineBasicBlock::iterator I = LoopBB.begin();
2949 
2950   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
2951   unsigned PhiExec = MRI.createVirtualRegister(BoolRC);
2952   unsigned NewExec = MRI.createVirtualRegister(BoolRC);
2953   unsigned CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2954   unsigned CondReg = MRI.createVirtualRegister(BoolRC);
2955 
2956   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
2957     .addReg(InitReg)
2958     .addMBB(&OrigBB)
2959     .addReg(ResultReg)
2960     .addMBB(&LoopBB);
2961 
2962   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
2963     .addReg(InitSaveExecReg)
2964     .addMBB(&OrigBB)
2965     .addReg(NewExec)
2966     .addMBB(&LoopBB);
2967 
2968   // Read the next variant <- also loop target.
2969   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
2970     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
2971 
2972   // Compare the just read M0 value to all possible Idx values.
2973   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
2974     .addReg(CurrentIdxReg)
2975     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
2976 
2977   // Update EXEC, save the original EXEC value to VCC.
2978   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
2979                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
2980           NewExec)
2981     .addReg(CondReg, RegState::Kill);
2982 
2983   MRI.setSimpleHint(NewExec, CondReg);
2984 
2985   if (UseGPRIdxMode) {
2986     unsigned IdxReg;
2987     if (Offset == 0) {
2988       IdxReg = CurrentIdxReg;
2989     } else {
2990       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
2991       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
2992         .addReg(CurrentIdxReg, RegState::Kill)
2993         .addImm(Offset);
2994     }
2995     unsigned IdxMode = IsIndirectSrc ?
2996       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
2997     MachineInstr *SetOn =
2998       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
2999       .addReg(IdxReg, RegState::Kill)
3000       .addImm(IdxMode);
3001     SetOn->getOperand(3).setIsUndef();
3002   } else {
3003     // Move index from VCC into M0
3004     if (Offset == 0) {
3005       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3006         .addReg(CurrentIdxReg, RegState::Kill);
3007     } else {
3008       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3009         .addReg(CurrentIdxReg, RegState::Kill)
3010         .addImm(Offset);
3011     }
3012   }
3013 
3014   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3015   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3016   MachineInstr *InsertPt =
3017     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3018                                                   : AMDGPU::S_XOR_B64_term), Exec)
3019       .addReg(Exec)
3020       .addReg(NewExec);
3021 
3022   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3023   // s_cbranch_scc0?
3024 
3025   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3026   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3027     .addMBB(&LoopBB);
3028 
3029   return InsertPt->getIterator();
3030 }
3031 
3032 // This has slightly sub-optimal regalloc when the source vector is killed by
3033 // the read. The register allocator does not understand that the kill is
3034 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3035 // subregister from it, using 1 more VGPR than necessary. This was saved when
3036 // this was expanded after register allocation.
3037 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3038                                                   MachineBasicBlock &MBB,
3039                                                   MachineInstr &MI,
3040                                                   unsigned InitResultReg,
3041                                                   unsigned PhiReg,
3042                                                   int Offset,
3043                                                   bool UseGPRIdxMode,
3044                                                   bool IsIndirectSrc) {
3045   MachineFunction *MF = MBB.getParent();
3046   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3047   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3048   MachineRegisterInfo &MRI = MF->getRegInfo();
3049   const DebugLoc &DL = MI.getDebugLoc();
3050   MachineBasicBlock::iterator I(&MI);
3051 
3052   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3053   unsigned DstReg = MI.getOperand(0).getReg();
3054   unsigned SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3055   unsigned TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3056   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3057   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3058 
3059   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3060 
3061   // Save the EXEC mask
3062   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3063     .addReg(Exec);
3064 
3065   // To insert the loop we need to split the block. Move everything after this
3066   // point to a new block, and insert a new empty block between the two.
3067   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3068   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3069   MachineFunction::iterator MBBI(MBB);
3070   ++MBBI;
3071 
3072   MF->insert(MBBI, LoopBB);
3073   MF->insert(MBBI, RemainderBB);
3074 
3075   LoopBB->addSuccessor(LoopBB);
3076   LoopBB->addSuccessor(RemainderBB);
3077 
3078   // Move the rest of the block into a new block.
3079   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3080   RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3081 
3082   MBB.addSuccessor(LoopBB);
3083 
3084   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3085 
3086   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3087                                       InitResultReg, DstReg, PhiReg, TmpExec,
3088                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3089 
3090   MachineBasicBlock::iterator First = RemainderBB->begin();
3091   BuildMI(*RemainderBB, First, DL, TII->get(MovExecOpc), Exec)
3092     .addReg(SaveExec);
3093 
3094   return InsPt;
3095 }
3096 
3097 // Returns subreg index, offset
3098 static std::pair<unsigned, int>
3099 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3100                             const TargetRegisterClass *SuperRC,
3101                             unsigned VecReg,
3102                             int Offset) {
3103   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3104 
3105   // Skip out of bounds offsets, or else we would end up using an undefined
3106   // register.
3107   if (Offset >= NumElts || Offset < 0)
3108     return std::make_pair(AMDGPU::sub0, Offset);
3109 
3110   return std::make_pair(AMDGPU::sub0 + Offset, 0);
3111 }
3112 
3113 // Return true if the index is an SGPR and was set.
3114 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3115                                  MachineRegisterInfo &MRI,
3116                                  MachineInstr &MI,
3117                                  int Offset,
3118                                  bool UseGPRIdxMode,
3119                                  bool IsIndirectSrc) {
3120   MachineBasicBlock *MBB = MI.getParent();
3121   const DebugLoc &DL = MI.getDebugLoc();
3122   MachineBasicBlock::iterator I(&MI);
3123 
3124   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3125   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3126 
3127   assert(Idx->getReg() != AMDGPU::NoRegister);
3128 
3129   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3130     return false;
3131 
3132   if (UseGPRIdxMode) {
3133     unsigned IdxMode = IsIndirectSrc ?
3134       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3135     if (Offset == 0) {
3136       MachineInstr *SetOn =
3137           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3138               .add(*Idx)
3139               .addImm(IdxMode);
3140 
3141       SetOn->getOperand(3).setIsUndef();
3142     } else {
3143       unsigned Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3144       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3145           .add(*Idx)
3146           .addImm(Offset);
3147       MachineInstr *SetOn =
3148         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3149         .addReg(Tmp, RegState::Kill)
3150         .addImm(IdxMode);
3151 
3152       SetOn->getOperand(3).setIsUndef();
3153     }
3154 
3155     return true;
3156   }
3157 
3158   if (Offset == 0) {
3159     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3160       .add(*Idx);
3161   } else {
3162     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3163       .add(*Idx)
3164       .addImm(Offset);
3165   }
3166 
3167   return true;
3168 }
3169 
3170 // Control flow needs to be inserted if indexing with a VGPR.
3171 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3172                                           MachineBasicBlock &MBB,
3173                                           const GCNSubtarget &ST) {
3174   const SIInstrInfo *TII = ST.getInstrInfo();
3175   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3176   MachineFunction *MF = MBB.getParent();
3177   MachineRegisterInfo &MRI = MF->getRegInfo();
3178 
3179   unsigned Dst = MI.getOperand(0).getReg();
3180   unsigned SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3181   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3182 
3183   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3184 
3185   unsigned SubReg;
3186   std::tie(SubReg, Offset)
3187     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3188 
3189   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3190 
3191   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3192     MachineBasicBlock::iterator I(&MI);
3193     const DebugLoc &DL = MI.getDebugLoc();
3194 
3195     if (UseGPRIdxMode) {
3196       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3197       // to avoid interfering with other uses, so probably requires a new
3198       // optimization pass.
3199       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3200         .addReg(SrcReg, RegState::Undef, SubReg)
3201         .addReg(SrcReg, RegState::Implicit)
3202         .addReg(AMDGPU::M0, RegState::Implicit);
3203       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3204     } else {
3205       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3206         .addReg(SrcReg, RegState::Undef, SubReg)
3207         .addReg(SrcReg, RegState::Implicit);
3208     }
3209 
3210     MI.eraseFromParent();
3211 
3212     return &MBB;
3213   }
3214 
3215   const DebugLoc &DL = MI.getDebugLoc();
3216   MachineBasicBlock::iterator I(&MI);
3217 
3218   unsigned PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3219   unsigned InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3220 
3221   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3222 
3223   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3224                               Offset, UseGPRIdxMode, true);
3225   MachineBasicBlock *LoopBB = InsPt->getParent();
3226 
3227   if (UseGPRIdxMode) {
3228     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3229       .addReg(SrcReg, RegState::Undef, SubReg)
3230       .addReg(SrcReg, RegState::Implicit)
3231       .addReg(AMDGPU::M0, RegState::Implicit);
3232     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3233   } else {
3234     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3235       .addReg(SrcReg, RegState::Undef, SubReg)
3236       .addReg(SrcReg, RegState::Implicit);
3237   }
3238 
3239   MI.eraseFromParent();
3240 
3241   return LoopBB;
3242 }
3243 
3244 static unsigned getMOVRELDPseudo(const SIRegisterInfo &TRI,
3245                                  const TargetRegisterClass *VecRC) {
3246   switch (TRI.getRegSizeInBits(*VecRC)) {
3247   case 32: // 4 bytes
3248     return AMDGPU::V_MOVRELD_B32_V1;
3249   case 64: // 8 bytes
3250     return AMDGPU::V_MOVRELD_B32_V2;
3251   case 128: // 16 bytes
3252     return AMDGPU::V_MOVRELD_B32_V4;
3253   case 256: // 32 bytes
3254     return AMDGPU::V_MOVRELD_B32_V8;
3255   case 512: // 64 bytes
3256     return AMDGPU::V_MOVRELD_B32_V16;
3257   default:
3258     llvm_unreachable("unsupported size for MOVRELD pseudos");
3259   }
3260 }
3261 
3262 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3263                                           MachineBasicBlock &MBB,
3264                                           const GCNSubtarget &ST) {
3265   const SIInstrInfo *TII = ST.getInstrInfo();
3266   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3267   MachineFunction *MF = MBB.getParent();
3268   MachineRegisterInfo &MRI = MF->getRegInfo();
3269 
3270   unsigned Dst = MI.getOperand(0).getReg();
3271   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3272   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3273   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3274   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3275   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3276 
3277   // This can be an immediate, but will be folded later.
3278   assert(Val->getReg());
3279 
3280   unsigned SubReg;
3281   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3282                                                          SrcVec->getReg(),
3283                                                          Offset);
3284   bool UseGPRIdxMode = ST.useVGPRIndexMode(EnableVGPRIndexMode);
3285 
3286   if (Idx->getReg() == AMDGPU::NoRegister) {
3287     MachineBasicBlock::iterator I(&MI);
3288     const DebugLoc &DL = MI.getDebugLoc();
3289 
3290     assert(Offset == 0);
3291 
3292     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3293         .add(*SrcVec)
3294         .add(*Val)
3295         .addImm(SubReg);
3296 
3297     MI.eraseFromParent();
3298     return &MBB;
3299   }
3300 
3301   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3302     MachineBasicBlock::iterator I(&MI);
3303     const DebugLoc &DL = MI.getDebugLoc();
3304 
3305     if (UseGPRIdxMode) {
3306       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3307           .addReg(SrcVec->getReg(), RegState::Undef, SubReg) // vdst
3308           .add(*Val)
3309           .addReg(Dst, RegState::ImplicitDefine)
3310           .addReg(SrcVec->getReg(), RegState::Implicit)
3311           .addReg(AMDGPU::M0, RegState::Implicit);
3312 
3313       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3314     } else {
3315       const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3316 
3317       BuildMI(MBB, I, DL, MovRelDesc)
3318           .addReg(Dst, RegState::Define)
3319           .addReg(SrcVec->getReg())
3320           .add(*Val)
3321           .addImm(SubReg - AMDGPU::sub0);
3322     }
3323 
3324     MI.eraseFromParent();
3325     return &MBB;
3326   }
3327 
3328   if (Val->isReg())
3329     MRI.clearKillFlags(Val->getReg());
3330 
3331   const DebugLoc &DL = MI.getDebugLoc();
3332 
3333   unsigned PhiReg = MRI.createVirtualRegister(VecRC);
3334 
3335   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3336                               Offset, UseGPRIdxMode, false);
3337   MachineBasicBlock *LoopBB = InsPt->getParent();
3338 
3339   if (UseGPRIdxMode) {
3340     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_indirect))
3341         .addReg(PhiReg, RegState::Undef, SubReg) // vdst
3342         .add(*Val)                               // src0
3343         .addReg(Dst, RegState::ImplicitDefine)
3344         .addReg(PhiReg, RegState::Implicit)
3345         .addReg(AMDGPU::M0, RegState::Implicit);
3346     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3347   } else {
3348     const MCInstrDesc &MovRelDesc = TII->get(getMOVRELDPseudo(TRI, VecRC));
3349 
3350     BuildMI(*LoopBB, InsPt, DL, MovRelDesc)
3351         .addReg(Dst, RegState::Define)
3352         .addReg(PhiReg)
3353         .add(*Val)
3354         .addImm(SubReg - AMDGPU::sub0);
3355   }
3356 
3357   MI.eraseFromParent();
3358 
3359   return LoopBB;
3360 }
3361 
3362 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3363   MachineInstr &MI, MachineBasicBlock *BB) const {
3364 
3365   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3366   MachineFunction *MF = BB->getParent();
3367   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3368 
3369   if (TII->isMIMG(MI)) {
3370     if (MI.memoperands_empty() && MI.mayLoadOrStore()) {
3371       report_fatal_error("missing mem operand from MIMG instruction");
3372     }
3373     // Add a memoperand for mimg instructions so that they aren't assumed to
3374     // be ordered memory instuctions.
3375 
3376     return BB;
3377   }
3378 
3379   switch (MI.getOpcode()) {
3380   case AMDGPU::S_ADD_U64_PSEUDO:
3381   case AMDGPU::S_SUB_U64_PSEUDO: {
3382     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3383     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3384     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3385     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3386     const DebugLoc &DL = MI.getDebugLoc();
3387 
3388     MachineOperand &Dest = MI.getOperand(0);
3389     MachineOperand &Src0 = MI.getOperand(1);
3390     MachineOperand &Src1 = MI.getOperand(2);
3391 
3392     unsigned DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3393     unsigned DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3394 
3395     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3396      Src0, BoolRC, AMDGPU::sub0,
3397      &AMDGPU::SReg_32_XM0RegClass);
3398     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3399       Src0, BoolRC, AMDGPU::sub1,
3400       &AMDGPU::SReg_32_XM0RegClass);
3401 
3402     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(MI, MRI,
3403       Src1, BoolRC, AMDGPU::sub0,
3404       &AMDGPU::SReg_32_XM0RegClass);
3405     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(MI, MRI,
3406       Src1, BoolRC, AMDGPU::sub1,
3407       &AMDGPU::SReg_32_XM0RegClass);
3408 
3409     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3410 
3411     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3412     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3413     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3414       .add(Src0Sub0)
3415       .add(Src1Sub0);
3416     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3417       .add(Src0Sub1)
3418       .add(Src1Sub1);
3419     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3420       .addReg(DestSub0)
3421       .addImm(AMDGPU::sub0)
3422       .addReg(DestSub1)
3423       .addImm(AMDGPU::sub1);
3424     MI.eraseFromParent();
3425     return BB;
3426   }
3427   case AMDGPU::SI_INIT_M0: {
3428     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3429             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3430         .add(MI.getOperand(0));
3431     MI.eraseFromParent();
3432     return BB;
3433   }
3434   case AMDGPU::SI_INIT_EXEC:
3435     // This should be before all vector instructions.
3436     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3437             AMDGPU::EXEC)
3438         .addImm(MI.getOperand(0).getImm());
3439     MI.eraseFromParent();
3440     return BB;
3441 
3442   case AMDGPU::SI_INIT_EXEC_LO:
3443     // This should be before all vector instructions.
3444     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3445             AMDGPU::EXEC_LO)
3446         .addImm(MI.getOperand(0).getImm());
3447     MI.eraseFromParent();
3448     return BB;
3449 
3450   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3451     // Extract the thread count from an SGPR input and set EXEC accordingly.
3452     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3453     //
3454     // S_BFE_U32 count, input, {shift, 7}
3455     // S_BFM_B64 exec, count, 0
3456     // S_CMP_EQ_U32 count, 64
3457     // S_CMOV_B64 exec, -1
3458     MachineInstr *FirstMI = &*BB->begin();
3459     MachineRegisterInfo &MRI = MF->getRegInfo();
3460     unsigned InputReg = MI.getOperand(0).getReg();
3461     unsigned CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3462     bool Found = false;
3463 
3464     // Move the COPY of the input reg to the beginning, so that we can use it.
3465     for (auto I = BB->begin(); I != &MI; I++) {
3466       if (I->getOpcode() != TargetOpcode::COPY ||
3467           I->getOperand(0).getReg() != InputReg)
3468         continue;
3469 
3470       if (I == FirstMI) {
3471         FirstMI = &*++BB->begin();
3472       } else {
3473         I->removeFromParent();
3474         BB->insert(FirstMI, &*I);
3475       }
3476       Found = true;
3477       break;
3478     }
3479     assert(Found);
3480     (void)Found;
3481 
3482     // This should be before all vector instructions.
3483     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3484     bool isWave32 = getSubtarget()->isWave32();
3485     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3486     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3487         .addReg(InputReg)
3488         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3489     BuildMI(*BB, FirstMI, DebugLoc(),
3490             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3491             Exec)
3492         .addReg(CountReg)
3493         .addImm(0);
3494     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3495         .addReg(CountReg, RegState::Kill)
3496         .addImm(getSubtarget()->getWavefrontSize());
3497     BuildMI(*BB, FirstMI, DebugLoc(),
3498             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3499             Exec)
3500         .addImm(-1);
3501     MI.eraseFromParent();
3502     return BB;
3503   }
3504 
3505   case AMDGPU::GET_GROUPSTATICSIZE: {
3506     DebugLoc DL = MI.getDebugLoc();
3507     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3508         .add(MI.getOperand(0))
3509         .addImm(MFI->getLDSSize());
3510     MI.eraseFromParent();
3511     return BB;
3512   }
3513   case AMDGPU::SI_INDIRECT_SRC_V1:
3514   case AMDGPU::SI_INDIRECT_SRC_V2:
3515   case AMDGPU::SI_INDIRECT_SRC_V4:
3516   case AMDGPU::SI_INDIRECT_SRC_V8:
3517   case AMDGPU::SI_INDIRECT_SRC_V16:
3518     return emitIndirectSrc(MI, *BB, *getSubtarget());
3519   case AMDGPU::SI_INDIRECT_DST_V1:
3520   case AMDGPU::SI_INDIRECT_DST_V2:
3521   case AMDGPU::SI_INDIRECT_DST_V4:
3522   case AMDGPU::SI_INDIRECT_DST_V8:
3523   case AMDGPU::SI_INDIRECT_DST_V16:
3524     return emitIndirectDst(MI, *BB, *getSubtarget());
3525   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
3526   case AMDGPU::SI_KILL_I1_PSEUDO:
3527     return splitKillBlock(MI, BB);
3528   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
3529     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3530     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3531     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3532 
3533     unsigned Dst = MI.getOperand(0).getReg();
3534     unsigned Src0 = MI.getOperand(1).getReg();
3535     unsigned Src1 = MI.getOperand(2).getReg();
3536     const DebugLoc &DL = MI.getDebugLoc();
3537     unsigned SrcCond = MI.getOperand(3).getReg();
3538 
3539     unsigned DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3540     unsigned DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3541     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3542     unsigned SrcCondCopy = MRI.createVirtualRegister(CondRC);
3543 
3544     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
3545       .addReg(SrcCond);
3546     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
3547       .addImm(0)
3548       .addReg(Src0, 0, AMDGPU::sub0)
3549       .addImm(0)
3550       .addReg(Src1, 0, AMDGPU::sub0)
3551       .addReg(SrcCondCopy);
3552     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
3553       .addImm(0)
3554       .addReg(Src0, 0, AMDGPU::sub1)
3555       .addImm(0)
3556       .addReg(Src1, 0, AMDGPU::sub1)
3557       .addReg(SrcCondCopy);
3558 
3559     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
3560       .addReg(DstLo)
3561       .addImm(AMDGPU::sub0)
3562       .addReg(DstHi)
3563       .addImm(AMDGPU::sub1);
3564     MI.eraseFromParent();
3565     return BB;
3566   }
3567   case AMDGPU::SI_BR_UNDEF: {
3568     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3569     const DebugLoc &DL = MI.getDebugLoc();
3570     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3571                            .add(MI.getOperand(0));
3572     Br->getOperand(1).setIsUndef(true); // read undef SCC
3573     MI.eraseFromParent();
3574     return BB;
3575   }
3576   case AMDGPU::ADJCALLSTACKUP:
3577   case AMDGPU::ADJCALLSTACKDOWN: {
3578     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
3579     MachineInstrBuilder MIB(*MF, &MI);
3580 
3581     // Add an implicit use of the frame offset reg to prevent the restore copy
3582     // inserted after the call from being reorderd after stack operations in the
3583     // the caller's frame.
3584     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
3585         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
3586         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
3587     return BB;
3588   }
3589   case AMDGPU::SI_CALL_ISEL: {
3590     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3591     const DebugLoc &DL = MI.getDebugLoc();
3592 
3593     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
3594 
3595     MachineInstrBuilder MIB;
3596     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
3597 
3598     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
3599       MIB.add(MI.getOperand(I));
3600 
3601     MIB.cloneMemRefs(MI);
3602     MI.eraseFromParent();
3603     return BB;
3604   }
3605   case AMDGPU::V_ADD_I32_e32:
3606   case AMDGPU::V_SUB_I32_e32:
3607   case AMDGPU::V_SUBREV_I32_e32: {
3608     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
3609     const DebugLoc &DL = MI.getDebugLoc();
3610     unsigned Opc = MI.getOpcode();
3611 
3612     bool NeedClampOperand = false;
3613     if (TII->pseudoToMCOpcode(Opc) == -1) {
3614       Opc = AMDGPU::getVOPe64(Opc);
3615       NeedClampOperand = true;
3616     }
3617 
3618     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
3619     if (TII->isVOP3(*I)) {
3620       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3621       const SIRegisterInfo *TRI = ST.getRegisterInfo();
3622       I.addReg(TRI->getVCC(), RegState::Define);
3623     }
3624     I.add(MI.getOperand(1))
3625      .add(MI.getOperand(2));
3626     if (NeedClampOperand)
3627       I.addImm(0); // clamp bit for e64 encoding
3628 
3629     TII->legalizeOperands(*I);
3630 
3631     MI.eraseFromParent();
3632     return BB;
3633   }
3634   default:
3635     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
3636   }
3637 }
3638 
3639 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
3640   return isTypeLegal(VT.getScalarType());
3641 }
3642 
3643 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
3644   // This currently forces unfolding various combinations of fsub into fma with
3645   // free fneg'd operands. As long as we have fast FMA (controlled by
3646   // isFMAFasterThanFMulAndFAdd), we should perform these.
3647 
3648   // When fma is quarter rate, for f64 where add / sub are at best half rate,
3649   // most of these combines appear to be cycle neutral but save on instruction
3650   // count / code size.
3651   return true;
3652 }
3653 
3654 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
3655                                          EVT VT) const {
3656   if (!VT.isVector()) {
3657     return MVT::i1;
3658   }
3659   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
3660 }
3661 
3662 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
3663   // TODO: Should i16 be used always if legal? For now it would force VALU
3664   // shifts.
3665   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
3666 }
3667 
3668 // Answering this is somewhat tricky and depends on the specific device which
3669 // have different rates for fma or all f64 operations.
3670 //
3671 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
3672 // regardless of which device (although the number of cycles differs between
3673 // devices), so it is always profitable for f64.
3674 //
3675 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
3676 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
3677 // which we can always do even without fused FP ops since it returns the same
3678 // result as the separate operations and since it is always full
3679 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
3680 // however does not support denormals, so we do report fma as faster if we have
3681 // a fast fma device and require denormals.
3682 //
3683 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
3684   VT = VT.getScalarType();
3685 
3686   switch (VT.getSimpleVT().SimpleTy) {
3687   case MVT::f32: {
3688     // This is as fast on some subtargets. However, we always have full rate f32
3689     // mad available which returns the same result as the separate operations
3690     // which we should prefer over fma. We can't use this if we want to support
3691     // denormals, so only report this in these cases.
3692     if (Subtarget->hasFP32Denormals())
3693       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
3694 
3695     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
3696     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
3697   }
3698   case MVT::f64:
3699     return true;
3700   case MVT::f16:
3701     return Subtarget->has16BitInsts() && Subtarget->hasFP16Denormals();
3702   default:
3703     break;
3704   }
3705 
3706   return false;
3707 }
3708 
3709 //===----------------------------------------------------------------------===//
3710 // Custom DAG Lowering Operations
3711 //===----------------------------------------------------------------------===//
3712 
3713 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3714 // wider vector type is legal.
3715 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
3716                                              SelectionDAG &DAG) const {
3717   unsigned Opc = Op.getOpcode();
3718   EVT VT = Op.getValueType();
3719   assert(VT == MVT::v4f16);
3720 
3721   SDValue Lo, Hi;
3722   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
3723 
3724   SDLoc SL(Op);
3725   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
3726                              Op->getFlags());
3727   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
3728                              Op->getFlags());
3729 
3730   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3731 }
3732 
3733 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
3734 // wider vector type is legal.
3735 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
3736                                               SelectionDAG &DAG) const {
3737   unsigned Opc = Op.getOpcode();
3738   EVT VT = Op.getValueType();
3739   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
3740 
3741   SDValue Lo0, Hi0;
3742   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
3743   SDValue Lo1, Hi1;
3744   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
3745 
3746   SDLoc SL(Op);
3747 
3748   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
3749                              Op->getFlags());
3750   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
3751                              Op->getFlags());
3752 
3753   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
3754 }
3755 
3756 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
3757   switch (Op.getOpcode()) {
3758   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
3759   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
3760   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
3761   case ISD::LOAD: {
3762     SDValue Result = LowerLOAD(Op, DAG);
3763     assert((!Result.getNode() ||
3764             Result.getNode()->getNumValues() == 2) &&
3765            "Load should return a value and a chain");
3766     return Result;
3767   }
3768 
3769   case ISD::FSIN:
3770   case ISD::FCOS:
3771     return LowerTrig(Op, DAG);
3772   case ISD::SELECT: return LowerSELECT(Op, DAG);
3773   case ISD::FDIV: return LowerFDIV(Op, DAG);
3774   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
3775   case ISD::STORE: return LowerSTORE(Op, DAG);
3776   case ISD::GlobalAddress: {
3777     MachineFunction &MF = DAG.getMachineFunction();
3778     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
3779     return LowerGlobalAddress(MFI, Op, DAG);
3780   }
3781   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
3782   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
3783   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
3784   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
3785   case ISD::INSERT_VECTOR_ELT:
3786     return lowerINSERT_VECTOR_ELT(Op, DAG);
3787   case ISD::EXTRACT_VECTOR_ELT:
3788     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
3789   case ISD::BUILD_VECTOR:
3790     return lowerBUILD_VECTOR(Op, DAG);
3791   case ISD::FP_ROUND:
3792     return lowerFP_ROUND(Op, DAG);
3793   case ISD::TRAP:
3794     return lowerTRAP(Op, DAG);
3795   case ISD::DEBUGTRAP:
3796     return lowerDEBUGTRAP(Op, DAG);
3797   case ISD::FABS:
3798   case ISD::FNEG:
3799   case ISD::FCANONICALIZE:
3800     return splitUnaryVectorOp(Op, DAG);
3801   case ISD::FMINNUM:
3802   case ISD::FMAXNUM:
3803     return lowerFMINNUM_FMAXNUM(Op, DAG);
3804   case ISD::SHL:
3805   case ISD::SRA:
3806   case ISD::SRL:
3807   case ISD::ADD:
3808   case ISD::SUB:
3809   case ISD::MUL:
3810   case ISD::SMIN:
3811   case ISD::SMAX:
3812   case ISD::UMIN:
3813   case ISD::UMAX:
3814   case ISD::FADD:
3815   case ISD::FMUL:
3816   case ISD::FMINNUM_IEEE:
3817   case ISD::FMAXNUM_IEEE:
3818     return splitBinaryVectorOp(Op, DAG);
3819   }
3820   return SDValue();
3821 }
3822 
3823 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
3824                                        const SDLoc &DL,
3825                                        SelectionDAG &DAG, bool Unpacked) {
3826   if (!LoadVT.isVector())
3827     return Result;
3828 
3829   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
3830     // Truncate to v2i16/v4i16.
3831     EVT IntLoadVT = LoadVT.changeTypeToInteger();
3832 
3833     // Workaround legalizer not scalarizing truncate after vector op
3834     // legalization byt not creating intermediate vector trunc.
3835     SmallVector<SDValue, 4> Elts;
3836     DAG.ExtractVectorElements(Result, Elts);
3837     for (SDValue &Elt : Elts)
3838       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
3839 
3840     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
3841 
3842     // Bitcast to original type (v2f16/v4f16).
3843     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3844   }
3845 
3846   // Cast back to the original packed type.
3847   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
3848 }
3849 
3850 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
3851                                               MemSDNode *M,
3852                                               SelectionDAG &DAG,
3853                                               ArrayRef<SDValue> Ops,
3854                                               bool IsIntrinsic) const {
3855   SDLoc DL(M);
3856 
3857   bool Unpacked = Subtarget->hasUnpackedD16VMem();
3858   EVT LoadVT = M->getValueType(0);
3859 
3860   EVT EquivLoadVT = LoadVT;
3861   if (Unpacked && LoadVT.isVector()) {
3862     EquivLoadVT = LoadVT.isVector() ?
3863       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
3864                        LoadVT.getVectorNumElements()) : LoadVT;
3865   }
3866 
3867   // Change from v4f16/v2f16 to EquivLoadVT.
3868   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
3869 
3870   SDValue Load
3871     = DAG.getMemIntrinsicNode(
3872       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
3873       VTList, Ops, M->getMemoryVT(),
3874       M->getMemOperand());
3875   if (!Unpacked) // Just adjusted the opcode.
3876     return Load;
3877 
3878   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
3879 
3880   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
3881 }
3882 
3883 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
3884                                   SDNode *N, SelectionDAG &DAG) {
3885   EVT VT = N->getValueType(0);
3886   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
3887   int CondCode = CD->getSExtValue();
3888   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
3889       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
3890     return DAG.getUNDEF(VT);
3891 
3892   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
3893 
3894   SDValue LHS = N->getOperand(1);
3895   SDValue RHS = N->getOperand(2);
3896 
3897   SDLoc DL(N);
3898 
3899   EVT CmpVT = LHS.getValueType();
3900   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
3901     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
3902       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3903     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
3904     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
3905   }
3906 
3907   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
3908 
3909   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
3910   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
3911 
3912   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
3913                               DAG.getCondCode(CCOpcode));
3914   if (VT.bitsEq(CCVT))
3915     return SetCC;
3916   return DAG.getZExtOrTrunc(SetCC, DL, VT);
3917 }
3918 
3919 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
3920                                   SDNode *N, SelectionDAG &DAG) {
3921   EVT VT = N->getValueType(0);
3922   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
3923 
3924   int CondCode = CD->getSExtValue();
3925   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
3926       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
3927     return DAG.getUNDEF(VT);
3928   }
3929 
3930   SDValue Src0 = N->getOperand(1);
3931   SDValue Src1 = N->getOperand(2);
3932   EVT CmpVT = Src0.getValueType();
3933   SDLoc SL(N);
3934 
3935   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
3936     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
3937     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
3938   }
3939 
3940   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
3941   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
3942   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
3943   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
3944   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
3945                               Src1, DAG.getCondCode(CCOpcode));
3946   if (VT.bitsEq(CCVT))
3947     return SetCC;
3948   return DAG.getZExtOrTrunc(SetCC, SL, VT);
3949 }
3950 
3951 void SITargetLowering::ReplaceNodeResults(SDNode *N,
3952                                           SmallVectorImpl<SDValue> &Results,
3953                                           SelectionDAG &DAG) const {
3954   switch (N->getOpcode()) {
3955   case ISD::INSERT_VECTOR_ELT: {
3956     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
3957       Results.push_back(Res);
3958     return;
3959   }
3960   case ISD::EXTRACT_VECTOR_ELT: {
3961     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
3962       Results.push_back(Res);
3963     return;
3964   }
3965   case ISD::INTRINSIC_WO_CHAIN: {
3966     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
3967     switch (IID) {
3968     case Intrinsic::amdgcn_cvt_pkrtz: {
3969       SDValue Src0 = N->getOperand(1);
3970       SDValue Src1 = N->getOperand(2);
3971       SDLoc SL(N);
3972       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
3973                                 Src0, Src1);
3974       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
3975       return;
3976     }
3977     case Intrinsic::amdgcn_cvt_pknorm_i16:
3978     case Intrinsic::amdgcn_cvt_pknorm_u16:
3979     case Intrinsic::amdgcn_cvt_pk_i16:
3980     case Intrinsic::amdgcn_cvt_pk_u16: {
3981       SDValue Src0 = N->getOperand(1);
3982       SDValue Src1 = N->getOperand(2);
3983       SDLoc SL(N);
3984       unsigned Opcode;
3985 
3986       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
3987         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
3988       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
3989         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
3990       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
3991         Opcode = AMDGPUISD::CVT_PK_I16_I32;
3992       else
3993         Opcode = AMDGPUISD::CVT_PK_U16_U32;
3994 
3995       EVT VT = N->getValueType(0);
3996       if (isTypeLegal(VT))
3997         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
3998       else {
3999         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4000         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4001       }
4002       return;
4003     }
4004     }
4005     break;
4006   }
4007   case ISD::INTRINSIC_W_CHAIN: {
4008     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4009       Results.push_back(Res);
4010       Results.push_back(Res.getValue(1));
4011       return;
4012     }
4013 
4014     break;
4015   }
4016   case ISD::SELECT: {
4017     SDLoc SL(N);
4018     EVT VT = N->getValueType(0);
4019     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4020     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4021     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4022 
4023     EVT SelectVT = NewVT;
4024     if (NewVT.bitsLT(MVT::i32)) {
4025       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4026       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4027       SelectVT = MVT::i32;
4028     }
4029 
4030     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4031                                     N->getOperand(0), LHS, RHS);
4032 
4033     if (NewVT != SelectVT)
4034       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4035     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4036     return;
4037   }
4038   case ISD::FNEG: {
4039     if (N->getValueType(0) != MVT::v2f16)
4040       break;
4041 
4042     SDLoc SL(N);
4043     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4044 
4045     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4046                              BC,
4047                              DAG.getConstant(0x80008000, SL, MVT::i32));
4048     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4049     return;
4050   }
4051   case ISD::FABS: {
4052     if (N->getValueType(0) != MVT::v2f16)
4053       break;
4054 
4055     SDLoc SL(N);
4056     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4057 
4058     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4059                              BC,
4060                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4061     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4062     return;
4063   }
4064   default:
4065     break;
4066   }
4067 }
4068 
4069 /// Helper function for LowerBRCOND
4070 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4071 
4072   SDNode *Parent = Value.getNode();
4073   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4074        I != E; ++I) {
4075 
4076     if (I.getUse().get() != Value)
4077       continue;
4078 
4079     if (I->getOpcode() == Opcode)
4080       return *I;
4081   }
4082   return nullptr;
4083 }
4084 
4085 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4086   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4087     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4088     case Intrinsic::amdgcn_if:
4089       return AMDGPUISD::IF;
4090     case Intrinsic::amdgcn_else:
4091       return AMDGPUISD::ELSE;
4092     case Intrinsic::amdgcn_loop:
4093       return AMDGPUISD::LOOP;
4094     case Intrinsic::amdgcn_end_cf:
4095       llvm_unreachable("should not occur");
4096     default:
4097       return 0;
4098     }
4099   }
4100 
4101   // break, if_break, else_break are all only used as inputs to loop, not
4102   // directly as branch conditions.
4103   return 0;
4104 }
4105 
4106 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4107   const Triple &TT = getTargetMachine().getTargetTriple();
4108   return (GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4109           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4110          AMDGPU::shouldEmitConstantsToTextSection(TT);
4111 }
4112 
4113 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4114   // FIXME: Either avoid relying on address space here or change the default
4115   // address space for functions to avoid the explicit check.
4116   return (GV->getValueType()->isFunctionTy() ||
4117           GV->getType()->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4118           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4119           GV->getType()->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4120          !shouldEmitFixup(GV) &&
4121          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4122 }
4123 
4124 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4125   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4126 }
4127 
4128 /// This transforms the control flow intrinsics to get the branch destination as
4129 /// last parameter, also switches branch target with BR if the need arise
4130 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4131                                       SelectionDAG &DAG) const {
4132   SDLoc DL(BRCOND);
4133 
4134   SDNode *Intr = BRCOND.getOperand(1).getNode();
4135   SDValue Target = BRCOND.getOperand(2);
4136   SDNode *BR = nullptr;
4137   SDNode *SetCC = nullptr;
4138 
4139   if (Intr->getOpcode() == ISD::SETCC) {
4140     // As long as we negate the condition everything is fine
4141     SetCC = Intr;
4142     Intr = SetCC->getOperand(0).getNode();
4143 
4144   } else {
4145     // Get the target from BR if we don't negate the condition
4146     BR = findUser(BRCOND, ISD::BR);
4147     Target = BR->getOperand(1);
4148   }
4149 
4150   // FIXME: This changes the types of the intrinsics instead of introducing new
4151   // nodes with the correct types.
4152   // e.g. llvm.amdgcn.loop
4153 
4154   // eg: i1,ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3
4155   // =>     t9: ch = llvm.amdgcn.loop t0, TargetConstant:i32<6271>, t3, BasicBlock:ch<bb1 0x7fee5286d088>
4156 
4157   unsigned CFNode = isCFIntrinsic(Intr);
4158   if (CFNode == 0) {
4159     // This is a uniform branch so we don't need to legalize.
4160     return BRCOND;
4161   }
4162 
4163   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4164                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4165 
4166   assert(!SetCC ||
4167         (SetCC->getConstantOperandVal(1) == 1 &&
4168          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4169                                                              ISD::SETNE));
4170 
4171   // operands of the new intrinsic call
4172   SmallVector<SDValue, 4> Ops;
4173   if (HaveChain)
4174     Ops.push_back(BRCOND.getOperand(0));
4175 
4176   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4177   Ops.push_back(Target);
4178 
4179   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4180 
4181   // build the new intrinsic call
4182   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4183 
4184   if (!HaveChain) {
4185     SDValue Ops[] =  {
4186       SDValue(Result, 0),
4187       BRCOND.getOperand(0)
4188     };
4189 
4190     Result = DAG.getMergeValues(Ops, DL).getNode();
4191   }
4192 
4193   if (BR) {
4194     // Give the branch instruction our target
4195     SDValue Ops[] = {
4196       BR->getOperand(0),
4197       BRCOND.getOperand(2)
4198     };
4199     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4200     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4201     BR = NewBR.getNode();
4202   }
4203 
4204   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4205 
4206   // Copy the intrinsic results to registers
4207   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4208     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4209     if (!CopyToReg)
4210       continue;
4211 
4212     Chain = DAG.getCopyToReg(
4213       Chain, DL,
4214       CopyToReg->getOperand(1),
4215       SDValue(Result, i - 1),
4216       SDValue());
4217 
4218     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4219   }
4220 
4221   // Remove the old intrinsic from the chain
4222   DAG.ReplaceAllUsesOfValueWith(
4223     SDValue(Intr, Intr->getNumValues() - 1),
4224     Intr->getOperand(0));
4225 
4226   return Chain;
4227 }
4228 
4229 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4230                                           SelectionDAG &DAG) const {
4231   MVT VT = Op.getSimpleValueType();
4232   SDLoc DL(Op);
4233   // Checking the depth
4234   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4235     return DAG.getConstant(0, DL, VT);
4236 
4237   MachineFunction &MF = DAG.getMachineFunction();
4238   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4239   // Check for kernel and shader functions
4240   if (Info->isEntryFunction())
4241     return DAG.getConstant(0, DL, VT);
4242 
4243   MachineFrameInfo &MFI = MF.getFrameInfo();
4244   // There is a call to @llvm.returnaddress in this function
4245   MFI.setReturnAddressIsTaken(true);
4246 
4247   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4248   // Get the return address reg and mark it as an implicit live-in
4249   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4250 
4251   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4252 }
4253 
4254 SDValue SITargetLowering::getFPExtOrFPTrunc(SelectionDAG &DAG,
4255                                             SDValue Op,
4256                                             const SDLoc &DL,
4257                                             EVT VT) const {
4258   return Op.getValueType().bitsLE(VT) ?
4259       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4260       DAG.getNode(ISD::FTRUNC, DL, VT, Op);
4261 }
4262 
4263 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4264   assert(Op.getValueType() == MVT::f16 &&
4265          "Do not know how to custom lower FP_ROUND for non-f16 type");
4266 
4267   SDValue Src = Op.getOperand(0);
4268   EVT SrcVT = Src.getValueType();
4269   if (SrcVT != MVT::f64)
4270     return Op;
4271 
4272   SDLoc DL(Op);
4273 
4274   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4275   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4276   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4277 }
4278 
4279 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4280                                                SelectionDAG &DAG) const {
4281   EVT VT = Op.getValueType();
4282   const MachineFunction &MF = DAG.getMachineFunction();
4283   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4284   bool IsIEEEMode = Info->getMode().IEEE;
4285 
4286   // FIXME: Assert during eslection that this is only selected for
4287   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4288   // mode functions, but this happens to be OK since it's only done in cases
4289   // where there is known no sNaN.
4290   if (IsIEEEMode)
4291     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4292 
4293   if (VT == MVT::v4f16)
4294     return splitBinaryVectorOp(Op, DAG);
4295   return Op;
4296 }
4297 
4298 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
4299   SDLoc SL(Op);
4300   SDValue Chain = Op.getOperand(0);
4301 
4302   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4303       !Subtarget->isTrapHandlerEnabled())
4304     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
4305 
4306   MachineFunction &MF = DAG.getMachineFunction();
4307   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4308   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4309   assert(UserSGPR != AMDGPU::NoRegister);
4310   SDValue QueuePtr = CreateLiveInRegister(
4311     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4312   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
4313   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
4314                                    QueuePtr, SDValue());
4315   SDValue Ops[] = {
4316     ToReg,
4317     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
4318     SGPR01,
4319     ToReg.getValue(1)
4320   };
4321   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4322 }
4323 
4324 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
4325   SDLoc SL(Op);
4326   SDValue Chain = Op.getOperand(0);
4327   MachineFunction &MF = DAG.getMachineFunction();
4328 
4329   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
4330       !Subtarget->isTrapHandlerEnabled()) {
4331     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
4332                                      "debugtrap handler not supported",
4333                                      Op.getDebugLoc(),
4334                                      DS_Warning);
4335     LLVMContext &Ctx = MF.getFunction().getContext();
4336     Ctx.diagnose(NoTrap);
4337     return Chain;
4338   }
4339 
4340   SDValue Ops[] = {
4341     Chain,
4342     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
4343   };
4344   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
4345 }
4346 
4347 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
4348                                              SelectionDAG &DAG) const {
4349   // FIXME: Use inline constants (src_{shared, private}_base) instead.
4350   if (Subtarget->hasApertureRegs()) {
4351     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
4352         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
4353         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
4354     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
4355         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
4356         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
4357     unsigned Encoding =
4358         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
4359         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
4360         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
4361 
4362     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
4363     SDValue ApertureReg = SDValue(
4364         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
4365     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
4366     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
4367   }
4368 
4369   MachineFunction &MF = DAG.getMachineFunction();
4370   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4371   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
4372   assert(UserSGPR != AMDGPU::NoRegister);
4373 
4374   SDValue QueuePtr = CreateLiveInRegister(
4375     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
4376 
4377   // Offset into amd_queue_t for group_segment_aperture_base_hi /
4378   // private_segment_aperture_base_hi.
4379   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
4380 
4381   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
4382 
4383   // TODO: Use custom target PseudoSourceValue.
4384   // TODO: We should use the value from the IR intrinsic call, but it might not
4385   // be available and how do we get it?
4386   Value *V = UndefValue::get(PointerType::get(Type::getInt8Ty(*DAG.getContext()),
4387                                               AMDGPUAS::CONSTANT_ADDRESS));
4388 
4389   MachinePointerInfo PtrInfo(V, StructOffset);
4390   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
4391                      MinAlign(64, StructOffset),
4392                      MachineMemOperand::MODereferenceable |
4393                          MachineMemOperand::MOInvariant);
4394 }
4395 
4396 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
4397                                              SelectionDAG &DAG) const {
4398   SDLoc SL(Op);
4399   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
4400 
4401   SDValue Src = ASC->getOperand(0);
4402   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
4403 
4404   const AMDGPUTargetMachine &TM =
4405     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
4406 
4407   // flat -> local/private
4408   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4409     unsigned DestAS = ASC->getDestAddressSpace();
4410 
4411     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
4412         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
4413       unsigned NullVal = TM.getNullPointerValue(DestAS);
4414       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4415       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
4416       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
4417 
4418       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
4419                          NonNull, Ptr, SegmentNullPtr);
4420     }
4421   }
4422 
4423   // local/private -> flat
4424   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
4425     unsigned SrcAS = ASC->getSrcAddressSpace();
4426 
4427     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
4428         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
4429       unsigned NullVal = TM.getNullPointerValue(SrcAS);
4430       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
4431 
4432       SDValue NonNull
4433         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
4434 
4435       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
4436       SDValue CvtPtr
4437         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
4438 
4439       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
4440                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
4441                          FlatNullPtr);
4442     }
4443   }
4444 
4445   // global <-> flat are no-ops and never emitted.
4446 
4447   const MachineFunction &MF = DAG.getMachineFunction();
4448   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
4449     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
4450   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
4451 
4452   return DAG.getUNDEF(ASC->getValueType(0));
4453 }
4454 
4455 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
4456                                                  SelectionDAG &DAG) const {
4457   SDValue Vec = Op.getOperand(0);
4458   SDValue InsVal = Op.getOperand(1);
4459   SDValue Idx = Op.getOperand(2);
4460   EVT VecVT = Vec.getValueType();
4461   EVT EltVT = VecVT.getVectorElementType();
4462   unsigned VecSize = VecVT.getSizeInBits();
4463   unsigned EltSize = EltVT.getSizeInBits();
4464 
4465 
4466   assert(VecSize <= 64);
4467 
4468   unsigned NumElts = VecVT.getVectorNumElements();
4469   SDLoc SL(Op);
4470   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
4471 
4472   if (NumElts == 4 && EltSize == 16 && KIdx) {
4473     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
4474 
4475     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4476                                  DAG.getConstant(0, SL, MVT::i32));
4477     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
4478                                  DAG.getConstant(1, SL, MVT::i32));
4479 
4480     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
4481     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
4482 
4483     unsigned Idx = KIdx->getZExtValue();
4484     bool InsertLo = Idx < 2;
4485     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
4486       InsertLo ? LoVec : HiVec,
4487       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
4488       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
4489 
4490     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
4491 
4492     SDValue Concat = InsertLo ?
4493       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
4494       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
4495 
4496     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
4497   }
4498 
4499   if (isa<ConstantSDNode>(Idx))
4500     return SDValue();
4501 
4502   MVT IntVT = MVT::getIntegerVT(VecSize);
4503 
4504   // Avoid stack access for dynamic indexing.
4505   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
4506 
4507   // Create a congruent vector with the target value in each element so that
4508   // the required element can be masked and ORed into the target vector.
4509   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
4510                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
4511 
4512   assert(isPowerOf2_32(EltSize));
4513   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4514 
4515   // Convert vector index to bit-index.
4516   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4517 
4518   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4519   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
4520                             DAG.getConstant(0xffff, SL, IntVT),
4521                             ScaledIdx);
4522 
4523   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
4524   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
4525                             DAG.getNOT(SL, BFM, IntVT), BCVec);
4526 
4527   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
4528   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
4529 }
4530 
4531 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
4532                                                   SelectionDAG &DAG) const {
4533   SDLoc SL(Op);
4534 
4535   EVT ResultVT = Op.getValueType();
4536   SDValue Vec = Op.getOperand(0);
4537   SDValue Idx = Op.getOperand(1);
4538   EVT VecVT = Vec.getValueType();
4539   unsigned VecSize = VecVT.getSizeInBits();
4540   EVT EltVT = VecVT.getVectorElementType();
4541   assert(VecSize <= 64);
4542 
4543   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
4544 
4545   // Make sure we do any optimizations that will make it easier to fold
4546   // source modifiers before obscuring it with bit operations.
4547 
4548   // XXX - Why doesn't this get called when vector_shuffle is expanded?
4549   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
4550     return Combined;
4551 
4552   unsigned EltSize = EltVT.getSizeInBits();
4553   assert(isPowerOf2_32(EltSize));
4554 
4555   MVT IntVT = MVT::getIntegerVT(VecSize);
4556   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
4557 
4558   // Convert vector index to bit-index (* EltSize)
4559   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
4560 
4561   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
4562   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
4563 
4564   if (ResultVT == MVT::f16) {
4565     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
4566     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
4567   }
4568 
4569   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
4570 }
4571 
4572 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
4573                                             SelectionDAG &DAG) const {
4574   SDLoc SL(Op);
4575   EVT VT = Op.getValueType();
4576 
4577   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
4578     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
4579 
4580     // Turn into pair of packed build_vectors.
4581     // TODO: Special case for constants that can be materialized with s_mov_b64.
4582     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
4583                                     { Op.getOperand(0), Op.getOperand(1) });
4584     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
4585                                     { Op.getOperand(2), Op.getOperand(3) });
4586 
4587     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
4588     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
4589 
4590     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
4591     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
4592   }
4593 
4594   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
4595   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
4596 
4597   SDValue Lo = Op.getOperand(0);
4598   SDValue Hi = Op.getOperand(1);
4599 
4600   // Avoid adding defined bits with the zero_extend.
4601   if (Hi.isUndef()) {
4602     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4603     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
4604     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
4605   }
4606 
4607   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
4608   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
4609 
4610   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
4611                               DAG.getConstant(16, SL, MVT::i32));
4612   if (Lo.isUndef())
4613     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
4614 
4615   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
4616   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
4617 
4618   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
4619   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
4620 }
4621 
4622 bool
4623 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4624   // We can fold offsets for anything that doesn't require a GOT relocation.
4625   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
4626           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4627           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4628          !shouldEmitGOTReloc(GA->getGlobal());
4629 }
4630 
4631 static SDValue
4632 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
4633                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
4634                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
4635   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
4636   // lowered to the following code sequence:
4637   //
4638   // For constant address space:
4639   //   s_getpc_b64 s[0:1]
4640   //   s_add_u32 s0, s0, $symbol
4641   //   s_addc_u32 s1, s1, 0
4642   //
4643   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4644   //   a fixup or relocation is emitted to replace $symbol with a literal
4645   //   constant, which is a pc-relative offset from the encoding of the $symbol
4646   //   operand to the global variable.
4647   //
4648   // For global address space:
4649   //   s_getpc_b64 s[0:1]
4650   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
4651   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
4652   //
4653   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
4654   //   fixups or relocations are emitted to replace $symbol@*@lo and
4655   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
4656   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
4657   //   operand to the global variable.
4658   //
4659   // What we want here is an offset from the value returned by s_getpc
4660   // (which is the address of the s_add_u32 instruction) to the global
4661   // variable, but since the encoding of $symbol starts 4 bytes after the start
4662   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
4663   // small. This requires us to add 4 to the global variable offset in order to
4664   // compute the correct address.
4665   unsigned LoFlags = GAFlags;
4666   if (LoFlags == SIInstrInfo::MO_NONE)
4667     LoFlags = SIInstrInfo::MO_REL32;
4668   SDValue PtrLo =
4669       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, LoFlags);
4670   SDValue PtrHi;
4671   if (GAFlags == SIInstrInfo::MO_NONE) {
4672     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
4673   } else {
4674     PtrHi =
4675         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
4676   }
4677   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
4678 }
4679 
4680 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
4681                                              SDValue Op,
4682                                              SelectionDAG &DAG) const {
4683   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
4684   const GlobalValue *GV = GSD->getGlobal();
4685   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
4686       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
4687       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
4688     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
4689 
4690   SDLoc DL(GSD);
4691   EVT PtrVT = Op.getValueType();
4692 
4693   // FIXME: Should not make address space based decisions here.
4694   if (shouldEmitFixup(GV))
4695     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
4696   else if (shouldEmitPCReloc(GV))
4697     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
4698                                    SIInstrInfo::MO_REL32);
4699 
4700   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
4701                                             SIInstrInfo::MO_GOTPCREL32);
4702 
4703   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
4704   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
4705   const DataLayout &DataLayout = DAG.getDataLayout();
4706   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
4707   MachinePointerInfo PtrInfo
4708     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
4709 
4710   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
4711                      MachineMemOperand::MODereferenceable |
4712                          MachineMemOperand::MOInvariant);
4713 }
4714 
4715 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
4716                                    const SDLoc &DL, SDValue V) const {
4717   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
4718   // the destination register.
4719   //
4720   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
4721   // so we will end up with redundant moves to m0.
4722   //
4723   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
4724 
4725   // A Null SDValue creates a glue result.
4726   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
4727                                   V, Chain);
4728   return SDValue(M0, 0);
4729 }
4730 
4731 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
4732                                                  SDValue Op,
4733                                                  MVT VT,
4734                                                  unsigned Offset) const {
4735   SDLoc SL(Op);
4736   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
4737                                            DAG.getEntryNode(), Offset, 4, false);
4738   // The local size values will have the hi 16-bits as zero.
4739   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
4740                      DAG.getValueType(VT));
4741 }
4742 
4743 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4744                                         EVT VT) {
4745   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4746                                       "non-hsa intrinsic with hsa target",
4747                                       DL.getDebugLoc());
4748   DAG.getContext()->diagnose(BadIntrin);
4749   return DAG.getUNDEF(VT);
4750 }
4751 
4752 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
4753                                          EVT VT) {
4754   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
4755                                       "intrinsic not supported on subtarget",
4756                                       DL.getDebugLoc());
4757   DAG.getContext()->diagnose(BadIntrin);
4758   return DAG.getUNDEF(VT);
4759 }
4760 
4761 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
4762                                     ArrayRef<SDValue> Elts) {
4763   assert(!Elts.empty());
4764   MVT Type;
4765   unsigned NumElts;
4766 
4767   if (Elts.size() == 1) {
4768     Type = MVT::f32;
4769     NumElts = 1;
4770   } else if (Elts.size() == 2) {
4771     Type = MVT::v2f32;
4772     NumElts = 2;
4773   } else if (Elts.size() <= 4) {
4774     Type = MVT::v4f32;
4775     NumElts = 4;
4776   } else if (Elts.size() <= 8) {
4777     Type = MVT::v8f32;
4778     NumElts = 8;
4779   } else {
4780     assert(Elts.size() <= 16);
4781     Type = MVT::v16f32;
4782     NumElts = 16;
4783   }
4784 
4785   SmallVector<SDValue, 16> VecElts(NumElts);
4786   for (unsigned i = 0; i < Elts.size(); ++i) {
4787     SDValue Elt = Elts[i];
4788     if (Elt.getValueType() != MVT::f32)
4789       Elt = DAG.getBitcast(MVT::f32, Elt);
4790     VecElts[i] = Elt;
4791   }
4792   for (unsigned i = Elts.size(); i < NumElts; ++i)
4793     VecElts[i] = DAG.getUNDEF(MVT::f32);
4794 
4795   if (NumElts == 1)
4796     return VecElts[0];
4797   return DAG.getBuildVector(Type, DL, VecElts);
4798 }
4799 
4800 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
4801                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
4802   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
4803 
4804   uint64_t Value = CachePolicyConst->getZExtValue();
4805   SDLoc DL(CachePolicy);
4806   if (GLC) {
4807     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
4808     Value &= ~(uint64_t)0x1;
4809   }
4810   if (SLC) {
4811     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
4812     Value &= ~(uint64_t)0x2;
4813   }
4814   if (DLC) {
4815     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
4816     Value &= ~(uint64_t)0x4;
4817   }
4818 
4819   return Value == 0;
4820 }
4821 
4822 // Re-construct the required return value for a image load intrinsic.
4823 // This is more complicated due to the optional use TexFailCtrl which means the required
4824 // return type is an aggregate
4825 static SDValue constructRetValue(SelectionDAG &DAG,
4826                                  MachineSDNode *Result,
4827                                  ArrayRef<EVT> ResultTypes,
4828                                  bool IsTexFail, bool Unpacked, bool IsD16,
4829                                  int DMaskPop, int NumVDataDwords,
4830                                  const SDLoc &DL, LLVMContext &Context) {
4831   // Determine the required return type. This is the same regardless of IsTexFail flag
4832   EVT ReqRetVT = ResultTypes[0];
4833   EVT ReqRetEltVT = ReqRetVT.isVector() ? ReqRetVT.getVectorElementType() : ReqRetVT;
4834   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
4835   EVT AdjEltVT = Unpacked && IsD16 ? MVT::i32 : ReqRetEltVT;
4836   EVT AdjVT = Unpacked ? ReqRetNumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, ReqRetNumElts)
4837                                            : AdjEltVT
4838                        : ReqRetVT;
4839 
4840   // Extract data part of the result
4841   // Bitcast the result to the same type as the required return type
4842   int NumElts;
4843   if (IsD16 && !Unpacked)
4844     NumElts = NumVDataDwords << 1;
4845   else
4846     NumElts = NumVDataDwords;
4847 
4848   EVT CastVT = NumElts > 1 ? EVT::getVectorVT(Context, AdjEltVT, NumElts)
4849                            : AdjEltVT;
4850 
4851   // Special case for v6f16. Rather than add support for this, use v3i32 to
4852   // extract the data elements
4853   bool V6F16Special = false;
4854   if (NumElts == 6) {
4855     CastVT = EVT::getVectorVT(Context, MVT::i32, NumElts / 2);
4856     DMaskPop >>= 1;
4857     ReqRetNumElts >>= 1;
4858     V6F16Special = true;
4859     AdjVT = MVT::v2i32;
4860   }
4861 
4862   SDValue N = SDValue(Result, 0);
4863   SDValue CastRes = DAG.getNode(ISD::BITCAST, DL, CastVT, N);
4864 
4865   // Iterate over the result
4866   SmallVector<SDValue, 4> BVElts;
4867 
4868   if (CastVT.isVector()) {
4869     DAG.ExtractVectorElements(CastRes, BVElts, 0, DMaskPop);
4870   } else {
4871     BVElts.push_back(CastRes);
4872   }
4873   int ExtraElts = ReqRetNumElts - DMaskPop;
4874   while(ExtraElts--)
4875     BVElts.push_back(DAG.getUNDEF(AdjEltVT));
4876 
4877   SDValue PreTFCRes;
4878   if (ReqRetNumElts > 1) {
4879     SDValue NewVec = DAG.getBuildVector(AdjVT, DL, BVElts);
4880     if (IsD16 && Unpacked)
4881       PreTFCRes = adjustLoadValueTypeImpl(NewVec, ReqRetVT, DL, DAG, Unpacked);
4882     else
4883       PreTFCRes = NewVec;
4884   } else {
4885     PreTFCRes = BVElts[0];
4886   }
4887 
4888   if (V6F16Special)
4889     PreTFCRes = DAG.getNode(ISD::BITCAST, DL, MVT::v4f16, PreTFCRes);
4890 
4891   if (!IsTexFail) {
4892     if (Result->getNumValues() > 1)
4893       return DAG.getMergeValues({PreTFCRes, SDValue(Result, 1)}, DL);
4894     else
4895       return PreTFCRes;
4896   }
4897 
4898   // Extract the TexFail result and insert into aggregate return
4899   SmallVector<SDValue, 1> TFCElt;
4900   DAG.ExtractVectorElements(N, TFCElt, DMaskPop, 1);
4901   SDValue TFCRes = DAG.getNode(ISD::BITCAST, DL, ResultTypes[1], TFCElt[0]);
4902   return DAG.getMergeValues({PreTFCRes, TFCRes, SDValue(Result, 1)}, DL);
4903 }
4904 
4905 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
4906                          SDValue *LWE, bool &IsTexFail) {
4907   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
4908 
4909   uint64_t Value = TexFailCtrlConst->getZExtValue();
4910   if (Value) {
4911     IsTexFail = true;
4912   }
4913 
4914   SDLoc DL(TexFailCtrlConst);
4915   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
4916   Value &= ~(uint64_t)0x1;
4917   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
4918   Value &= ~(uint64_t)0x2;
4919 
4920   return Value == 0;
4921 }
4922 
4923 SDValue SITargetLowering::lowerImage(SDValue Op,
4924                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
4925                                      SelectionDAG &DAG) const {
4926   SDLoc DL(Op);
4927   MachineFunction &MF = DAG.getMachineFunction();
4928   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
4929   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
4930       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
4931   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
4932   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
4933       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
4934   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
4935       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
4936   unsigned IntrOpcode = Intr->BaseOpcode;
4937   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
4938 
4939   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
4940   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
4941   bool IsD16 = false;
4942   bool IsA16 = false;
4943   SDValue VData;
4944   int NumVDataDwords;
4945   bool AdjustRetType = false;
4946 
4947   unsigned AddrIdx; // Index of first address argument
4948   unsigned DMask;
4949   unsigned DMaskLanes = 0;
4950 
4951   if (BaseOpcode->Atomic) {
4952     VData = Op.getOperand(2);
4953 
4954     bool Is64Bit = VData.getValueType() == MVT::i64;
4955     if (BaseOpcode->AtomicX2) {
4956       SDValue VData2 = Op.getOperand(3);
4957       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
4958                                  {VData, VData2});
4959       if (Is64Bit)
4960         VData = DAG.getBitcast(MVT::v4i32, VData);
4961 
4962       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
4963       DMask = Is64Bit ? 0xf : 0x3;
4964       NumVDataDwords = Is64Bit ? 4 : 2;
4965       AddrIdx = 4;
4966     } else {
4967       DMask = Is64Bit ? 0x3 : 0x1;
4968       NumVDataDwords = Is64Bit ? 2 : 1;
4969       AddrIdx = 3;
4970     }
4971   } else {
4972     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
4973     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
4974     DMask = DMaskConst->getZExtValue();
4975     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
4976 
4977     if (BaseOpcode->Store) {
4978       VData = Op.getOperand(2);
4979 
4980       MVT StoreVT = VData.getSimpleValueType();
4981       if (StoreVT.getScalarType() == MVT::f16) {
4982         if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ||
4983             !BaseOpcode->HasD16)
4984           return Op; // D16 is unsupported for this instruction
4985 
4986         IsD16 = true;
4987         VData = handleD16VData(VData, DAG);
4988       }
4989 
4990       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
4991     } else {
4992       // Work out the num dwords based on the dmask popcount and underlying type
4993       // and whether packing is supported.
4994       MVT LoadVT = ResultTypes[0].getSimpleVT();
4995       if (LoadVT.getScalarType() == MVT::f16) {
4996         if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS ||
4997             !BaseOpcode->HasD16)
4998           return Op; // D16 is unsupported for this instruction
4999 
5000         IsD16 = true;
5001       }
5002 
5003       // Confirm that the return type is large enough for the dmask specified
5004       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5005           (!LoadVT.isVector() && DMaskLanes > 1))
5006           return Op;
5007 
5008       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5009         NumVDataDwords = (DMaskLanes + 1) / 2;
5010       else
5011         NumVDataDwords = DMaskLanes;
5012 
5013       AdjustRetType = true;
5014     }
5015 
5016     AddrIdx = DMaskIdx + 1;
5017   }
5018 
5019   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5020   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5021   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5022   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5023                        NumCoords + NumLCM;
5024   unsigned NumMIVAddrs = NumVAddrs;
5025 
5026   SmallVector<SDValue, 4> VAddrs;
5027 
5028   // Optimize _L to _LZ when _L is zero
5029   if (LZMappingInfo) {
5030     if (auto ConstantLod =
5031          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5032       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5033         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5034         NumMIVAddrs--;               // remove 'lod'
5035       }
5036     }
5037   }
5038 
5039   // Optimize _mip away, when 'lod' is zero
5040   if (MIPMappingInfo) {
5041     if (auto ConstantLod =
5042          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5043       if (ConstantLod->isNullValue()) {
5044         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5045         NumMIVAddrs--;               // remove 'lod'
5046       }
5047     }
5048   }
5049 
5050   // Check for 16 bit addresses and pack if true.
5051   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5052   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5053   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5054   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16)) &&
5055       ST->hasFeature(AMDGPU::FeatureR128A16)) {
5056     IsA16 = true;
5057     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5058     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5059       SDValue AddrLo, AddrHi;
5060       // Push back extra arguments.
5061       if (i < DimIdx) {
5062         AddrLo = Op.getOperand(i);
5063       } else {
5064         AddrLo = Op.getOperand(i);
5065         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5066         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5067         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5068             ((NumGradients / 2) % 2 == 1 &&
5069             (i == DimIdx + (NumGradients / 2) - 1 ||
5070              i == DimIdx + NumGradients - 1))) {
5071           AddrHi = DAG.getUNDEF(MVT::f16);
5072         } else {
5073           AddrHi = Op.getOperand(i + 1);
5074           i++;
5075         }
5076         AddrLo = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VectorVT,
5077                              {AddrLo, AddrHi});
5078         AddrLo = DAG.getBitcast(MVT::i32, AddrLo);
5079       }
5080       VAddrs.push_back(AddrLo);
5081     }
5082   } else {
5083     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5084       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5085   }
5086 
5087   // If the register allocator cannot place the address registers contiguously
5088   // without introducing moves, then using the non-sequential address encoding
5089   // is always preferable, since it saves VALU instructions and is usually a
5090   // wash in terms of code size or even better.
5091   //
5092   // However, we currently have no way of hinting to the register allocator that
5093   // MIMG addresses should be placed contiguously when it is possible to do so,
5094   // so force non-NSA for the common 2-address case as a heuristic.
5095   //
5096   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5097   // allocation when possible.
5098   bool UseNSA =
5099       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5100   SDValue VAddr;
5101   if (!UseNSA)
5102     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5103 
5104   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5105   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5106   unsigned CtrlIdx; // Index of texfailctrl argument
5107   SDValue Unorm;
5108   if (!BaseOpcode->Sampler) {
5109     Unorm = True;
5110     CtrlIdx = AddrIdx + NumVAddrs + 1;
5111   } else {
5112     auto UnormConst =
5113         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5114 
5115     Unorm = UnormConst->getZExtValue() ? True : False;
5116     CtrlIdx = AddrIdx + NumVAddrs + 3;
5117   }
5118 
5119   SDValue TFE;
5120   SDValue LWE;
5121   SDValue TexFail = Op.getOperand(CtrlIdx);
5122   bool IsTexFail = false;
5123   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5124     return Op;
5125 
5126   if (IsTexFail) {
5127     if (!DMaskLanes) {
5128       // Expecting to get an error flag since TFC is on - and dmask is 0
5129       // Force dmask to be at least 1 otherwise the instruction will fail
5130       DMask = 0x1;
5131       DMaskLanes = 1;
5132       NumVDataDwords = 1;
5133     }
5134     NumVDataDwords += 1;
5135     AdjustRetType = true;
5136   }
5137 
5138   // Has something earlier tagged that the return type needs adjusting
5139   // This happens if the instruction is a load or has set TexFailCtrl flags
5140   if (AdjustRetType) {
5141     // NumVDataDwords reflects the true number of dwords required in the return type
5142     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5143       // This is a no-op load. This can be eliminated
5144       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5145       if (isa<MemSDNode>(Op))
5146         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5147       return Undef;
5148     }
5149 
5150     EVT NewVT = NumVDataDwords > 1 ?
5151                   EVT::getVectorVT(*DAG.getContext(), MVT::f32, NumVDataDwords)
5152                 : MVT::f32;
5153 
5154     ResultTypes[0] = NewVT;
5155     if (ResultTypes.size() == 3) {
5156       // Original result was aggregate type used for TexFailCtrl results
5157       // The actual instruction returns as a vector type which has now been
5158       // created. Remove the aggregate result.
5159       ResultTypes.erase(&ResultTypes[1]);
5160     }
5161   }
5162 
5163   SDValue GLC;
5164   SDValue SLC;
5165   SDValue DLC;
5166   if (BaseOpcode->Atomic) {
5167     GLC = True; // TODO no-return optimization
5168     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5169                           IsGFX10 ? &DLC : nullptr))
5170       return Op;
5171   } else {
5172     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5173                           IsGFX10 ? &DLC : nullptr))
5174       return Op;
5175   }
5176 
5177   SmallVector<SDValue, 26> Ops;
5178   if (BaseOpcode->Store || BaseOpcode->Atomic)
5179     Ops.push_back(VData); // vdata
5180   if (UseNSA) {
5181     for (const SDValue &Addr : VAddrs)
5182       Ops.push_back(Addr);
5183   } else {
5184     Ops.push_back(VAddr);
5185   }
5186   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
5187   if (BaseOpcode->Sampler)
5188     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
5189   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
5190   if (IsGFX10)
5191     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
5192   Ops.push_back(Unorm);
5193   if (IsGFX10)
5194     Ops.push_back(DLC);
5195   Ops.push_back(GLC);
5196   Ops.push_back(SLC);
5197   Ops.push_back(IsA16 &&  // a16 or r128
5198                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
5199   Ops.push_back(TFE); // tfe
5200   Ops.push_back(LWE); // lwe
5201   if (!IsGFX10)
5202     Ops.push_back(DimInfo->DA ? True : False);
5203   if (BaseOpcode->HasD16)
5204     Ops.push_back(IsD16 ? True : False);
5205   if (isa<MemSDNode>(Op))
5206     Ops.push_back(Op.getOperand(0)); // chain
5207 
5208   int NumVAddrDwords =
5209       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
5210   int Opcode = -1;
5211 
5212   if (IsGFX10) {
5213     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
5214                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
5215                                           : AMDGPU::MIMGEncGfx10Default,
5216                                    NumVDataDwords, NumVAddrDwords);
5217   } else {
5218     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5219       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
5220                                      NumVDataDwords, NumVAddrDwords);
5221     if (Opcode == -1)
5222       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
5223                                      NumVDataDwords, NumVAddrDwords);
5224   }
5225   assert(Opcode != -1);
5226 
5227   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
5228   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
5229     MachineMemOperand *MemRef = MemOp->getMemOperand();
5230     DAG.setNodeMemRefs(NewNode, {MemRef});
5231   }
5232 
5233   if (BaseOpcode->AtomicX2) {
5234     SmallVector<SDValue, 1> Elt;
5235     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
5236     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
5237   } else if (!BaseOpcode->Store) {
5238     return constructRetValue(DAG, NewNode,
5239                              OrigResultTypes, IsTexFail,
5240                              Subtarget->hasUnpackedD16VMem(), IsD16,
5241                              DMaskLanes, NumVDataDwords, DL,
5242                              *DAG.getContext());
5243   }
5244 
5245   return SDValue(NewNode, 0);
5246 }
5247 
5248 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
5249                                        SDValue Offset, SDValue GLC, SDValue DLC,
5250                                        SelectionDAG &DAG) const {
5251   MachineFunction &MF = DAG.getMachineFunction();
5252   MachineMemOperand *MMO = MF.getMachineMemOperand(
5253       MachinePointerInfo(),
5254       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
5255           MachineMemOperand::MOInvariant,
5256       VT.getStoreSize(), VT.getStoreSize());
5257 
5258   if (!Offset->isDivergent()) {
5259     SDValue Ops[] = {
5260         Rsrc,
5261         Offset, // Offset
5262         GLC,
5263         DLC,
5264     };
5265     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
5266                                    DAG.getVTList(VT), Ops, VT, MMO);
5267   }
5268 
5269   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
5270   // assume that the buffer is unswizzled.
5271   SmallVector<SDValue, 4> Loads;
5272   unsigned NumLoads = 1;
5273   MVT LoadVT = VT.getSimpleVT();
5274   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
5275   assert((LoadVT.getScalarType() == MVT::i32 ||
5276           LoadVT.getScalarType() == MVT::f32) &&
5277          isPowerOf2_32(NumElts));
5278 
5279   if (NumElts == 8 || NumElts == 16) {
5280     NumLoads = NumElts == 16 ? 4 : 2;
5281     LoadVT = MVT::v4i32;
5282   }
5283 
5284   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
5285   unsigned CachePolicy = cast<ConstantSDNode>(GLC)->getZExtValue();
5286   SDValue Ops[] = {
5287       DAG.getEntryNode(),                         // Chain
5288       Rsrc,                                       // rsrc
5289       DAG.getConstant(0, DL, MVT::i32),           // vindex
5290       {},                                         // voffset
5291       {},                                         // soffset
5292       {},                                         // offset
5293       DAG.getConstant(CachePolicy, DL, MVT::i32), // cachepolicy
5294       DAG.getConstant(0, DL, MVT::i1),            // idxen
5295   };
5296 
5297   // Use the alignment to ensure that the required offsets will fit into the
5298   // immediate offsets.
5299   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
5300 
5301   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
5302   for (unsigned i = 0; i < NumLoads; ++i) {
5303     Ops[5] = DAG.getConstant(InstOffset + 16 * i, DL, MVT::i32);
5304     Loads.push_back(DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList,
5305                                             Ops, LoadVT, MMO));
5306   }
5307 
5308   if (VT == MVT::v8i32 || VT == MVT::v16i32)
5309     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
5310 
5311   return Loads[0];
5312 }
5313 
5314 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
5315                                                   SelectionDAG &DAG) const {
5316   MachineFunction &MF = DAG.getMachineFunction();
5317   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
5318 
5319   EVT VT = Op.getValueType();
5320   SDLoc DL(Op);
5321   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
5322 
5323   // TODO: Should this propagate fast-math-flags?
5324 
5325   switch (IntrinsicID) {
5326   case Intrinsic::amdgcn_implicit_buffer_ptr: {
5327     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
5328       return emitNonHSAIntrinsicError(DAG, DL, VT);
5329     return getPreloadedValue(DAG, *MFI, VT,
5330                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
5331   }
5332   case Intrinsic::amdgcn_dispatch_ptr:
5333   case Intrinsic::amdgcn_queue_ptr: {
5334     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
5335       DiagnosticInfoUnsupported BadIntrin(
5336           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
5337           DL.getDebugLoc());
5338       DAG.getContext()->diagnose(BadIntrin);
5339       return DAG.getUNDEF(VT);
5340     }
5341 
5342     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
5343       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
5344     return getPreloadedValue(DAG, *MFI, VT, RegID);
5345   }
5346   case Intrinsic::amdgcn_implicitarg_ptr: {
5347     if (MFI->isEntryFunction())
5348       return getImplicitArgPtr(DAG, DL);
5349     return getPreloadedValue(DAG, *MFI, VT,
5350                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
5351   }
5352   case Intrinsic::amdgcn_kernarg_segment_ptr: {
5353     return getPreloadedValue(DAG, *MFI, VT,
5354                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
5355   }
5356   case Intrinsic::amdgcn_dispatch_id: {
5357     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
5358   }
5359   case Intrinsic::amdgcn_rcp:
5360     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
5361   case Intrinsic::amdgcn_rsq:
5362     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5363   case Intrinsic::amdgcn_rsq_legacy:
5364     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5365       return emitRemovedIntrinsicError(DAG, DL, VT);
5366 
5367     return DAG.getNode(AMDGPUISD::RSQ_LEGACY, DL, VT, Op.getOperand(1));
5368   case Intrinsic::amdgcn_rcp_legacy:
5369     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
5370       return emitRemovedIntrinsicError(DAG, DL, VT);
5371     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
5372   case Intrinsic::amdgcn_rsq_clamp: {
5373     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5374       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
5375 
5376     Type *Type = VT.getTypeForEVT(*DAG.getContext());
5377     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
5378     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
5379 
5380     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
5381     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
5382                               DAG.getConstantFP(Max, DL, VT));
5383     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
5384                        DAG.getConstantFP(Min, DL, VT));
5385   }
5386   case Intrinsic::r600_read_ngroups_x:
5387     if (Subtarget->isAmdHsaOS())
5388       return emitNonHSAIntrinsicError(DAG, DL, VT);
5389 
5390     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5391                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
5392   case Intrinsic::r600_read_ngroups_y:
5393     if (Subtarget->isAmdHsaOS())
5394       return emitNonHSAIntrinsicError(DAG, DL, VT);
5395 
5396     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5397                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
5398   case Intrinsic::r600_read_ngroups_z:
5399     if (Subtarget->isAmdHsaOS())
5400       return emitNonHSAIntrinsicError(DAG, DL, VT);
5401 
5402     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5403                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
5404   case Intrinsic::r600_read_global_size_x:
5405     if (Subtarget->isAmdHsaOS())
5406       return emitNonHSAIntrinsicError(DAG, DL, VT);
5407 
5408     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5409                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
5410   case Intrinsic::r600_read_global_size_y:
5411     if (Subtarget->isAmdHsaOS())
5412       return emitNonHSAIntrinsicError(DAG, DL, VT);
5413 
5414     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5415                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
5416   case Intrinsic::r600_read_global_size_z:
5417     if (Subtarget->isAmdHsaOS())
5418       return emitNonHSAIntrinsicError(DAG, DL, VT);
5419 
5420     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
5421                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
5422   case Intrinsic::r600_read_local_size_x:
5423     if (Subtarget->isAmdHsaOS())
5424       return emitNonHSAIntrinsicError(DAG, DL, VT);
5425 
5426     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5427                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
5428   case Intrinsic::r600_read_local_size_y:
5429     if (Subtarget->isAmdHsaOS())
5430       return emitNonHSAIntrinsicError(DAG, DL, VT);
5431 
5432     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5433                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
5434   case Intrinsic::r600_read_local_size_z:
5435     if (Subtarget->isAmdHsaOS())
5436       return emitNonHSAIntrinsicError(DAG, DL, VT);
5437 
5438     return lowerImplicitZextParam(DAG, Op, MVT::i16,
5439                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
5440   case Intrinsic::amdgcn_workgroup_id_x:
5441   case Intrinsic::r600_read_tgid_x:
5442     return getPreloadedValue(DAG, *MFI, VT,
5443                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
5444   case Intrinsic::amdgcn_workgroup_id_y:
5445   case Intrinsic::r600_read_tgid_y:
5446     return getPreloadedValue(DAG, *MFI, VT,
5447                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
5448   case Intrinsic::amdgcn_workgroup_id_z:
5449   case Intrinsic::r600_read_tgid_z:
5450     return getPreloadedValue(DAG, *MFI, VT,
5451                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
5452   case Intrinsic::amdgcn_workitem_id_x:
5453   case Intrinsic::r600_read_tidig_x:
5454     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5455                           SDLoc(DAG.getEntryNode()),
5456                           MFI->getArgInfo().WorkItemIDX);
5457   case Intrinsic::amdgcn_workitem_id_y:
5458   case Intrinsic::r600_read_tidig_y:
5459     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5460                           SDLoc(DAG.getEntryNode()),
5461                           MFI->getArgInfo().WorkItemIDY);
5462   case Intrinsic::amdgcn_workitem_id_z:
5463   case Intrinsic::r600_read_tidig_z:
5464     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
5465                           SDLoc(DAG.getEntryNode()),
5466                           MFI->getArgInfo().WorkItemIDZ);
5467   case Intrinsic::amdgcn_wavefrontsize:
5468     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
5469                            SDLoc(Op), MVT::i32);
5470   case Intrinsic::amdgcn_s_buffer_load: {
5471     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5472     SDValue GLC;
5473     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
5474     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
5475                           IsGFX10 ? &DLC : nullptr))
5476       return Op;
5477     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), GLC, DLC,
5478                         DAG);
5479   }
5480   case Intrinsic::amdgcn_fdiv_fast:
5481     return lowerFDIV_FAST(Op, DAG);
5482   case Intrinsic::amdgcn_interp_mov: {
5483     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5484     SDValue Glue = M0.getValue(1);
5485     return DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32, Op.getOperand(1),
5486                        Op.getOperand(2), Op.getOperand(3), Glue);
5487   }
5488   case Intrinsic::amdgcn_interp_p1: {
5489     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(4));
5490     SDValue Glue = M0.getValue(1);
5491     return DAG.getNode(AMDGPUISD::INTERP_P1, DL, MVT::f32, Op.getOperand(1),
5492                        Op.getOperand(2), Op.getOperand(3), Glue);
5493   }
5494   case Intrinsic::amdgcn_interp_p2: {
5495     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5496     SDValue Glue = SDValue(M0.getNode(), 1);
5497     return DAG.getNode(AMDGPUISD::INTERP_P2, DL, MVT::f32, Op.getOperand(1),
5498                        Op.getOperand(2), Op.getOperand(3), Op.getOperand(4),
5499                        Glue);
5500   }
5501   case Intrinsic::amdgcn_interp_p1_f16: {
5502     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(5));
5503     SDValue Glue = M0.getValue(1);
5504     if (getSubtarget()->getLDSBankCount() == 16) {
5505       // 16 bank LDS
5506       SDValue S = DAG.getNode(AMDGPUISD::INTERP_MOV, DL, MVT::f32,
5507                               DAG.getConstant(2, DL, MVT::i32), // P0
5508                               Op.getOperand(2), // Attrchan
5509                               Op.getOperand(3), // Attr
5510                               Glue);
5511       SDValue Ops[] = {
5512         Op.getOperand(1), // Src0
5513         Op.getOperand(2), // Attrchan
5514         Op.getOperand(3), // Attr
5515         DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5516         S, // Src2 - holds two f16 values selected by high
5517         DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers
5518         Op.getOperand(4), // high
5519         DAG.getConstant(0, DL, MVT::i1), // $clamp
5520         DAG.getConstant(0, DL, MVT::i32) // $omod
5521       };
5522       return DAG.getNode(AMDGPUISD::INTERP_P1LV_F16, DL, MVT::f32, Ops);
5523     } else {
5524       // 32 bank LDS
5525       SDValue Ops[] = {
5526         Op.getOperand(1), // Src0
5527         Op.getOperand(2), // Attrchan
5528         Op.getOperand(3), // Attr
5529         DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5530         Op.getOperand(4), // high
5531         DAG.getConstant(0, DL, MVT::i1), // $clamp
5532         DAG.getConstant(0, DL, MVT::i32), // $omod
5533         Glue
5534       };
5535       return DAG.getNode(AMDGPUISD::INTERP_P1LL_F16, DL, MVT::f32, Ops);
5536     }
5537   }
5538   case Intrinsic::amdgcn_interp_p2_f16: {
5539     SDValue M0 = copyToM0(DAG, DAG.getEntryNode(), DL, Op.getOperand(6));
5540     SDValue Glue = SDValue(M0.getNode(), 1);
5541     SDValue Ops[] = {
5542       Op.getOperand(2), // Src0
5543       Op.getOperand(3), // Attrchan
5544       Op.getOperand(4), // Attr
5545       DAG.getConstant(0, DL, MVT::i32), // $src0_modifiers
5546       Op.getOperand(1), // Src2
5547       DAG.getConstant(0, DL, MVT::i32), // $src2_modifiers
5548       Op.getOperand(5), // high
5549       DAG.getConstant(0, DL, MVT::i1), // $clamp
5550       Glue
5551     };
5552     return DAG.getNode(AMDGPUISD::INTERP_P2_F16, DL, MVT::f16, Ops);
5553   }
5554   case Intrinsic::amdgcn_sin:
5555     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
5556 
5557   case Intrinsic::amdgcn_cos:
5558     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
5559 
5560   case Intrinsic::amdgcn_log_clamp: {
5561     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
5562       return SDValue();
5563 
5564     DiagnosticInfoUnsupported BadIntrin(
5565       MF.getFunction(), "intrinsic not supported on subtarget",
5566       DL.getDebugLoc());
5567       DAG.getContext()->diagnose(BadIntrin);
5568       return DAG.getUNDEF(VT);
5569   }
5570   case Intrinsic::amdgcn_ldexp:
5571     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
5572                        Op.getOperand(1), Op.getOperand(2));
5573 
5574   case Intrinsic::amdgcn_fract:
5575     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
5576 
5577   case Intrinsic::amdgcn_class:
5578     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
5579                        Op.getOperand(1), Op.getOperand(2));
5580   case Intrinsic::amdgcn_div_fmas:
5581     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
5582                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5583                        Op.getOperand(4));
5584 
5585   case Intrinsic::amdgcn_div_fixup:
5586     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
5587                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5588 
5589   case Intrinsic::amdgcn_trig_preop:
5590     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
5591                        Op.getOperand(1), Op.getOperand(2));
5592   case Intrinsic::amdgcn_div_scale: {
5593     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
5594 
5595     // Translate to the operands expected by the machine instruction. The
5596     // first parameter must be the same as the first instruction.
5597     SDValue Numerator = Op.getOperand(1);
5598     SDValue Denominator = Op.getOperand(2);
5599 
5600     // Note this order is opposite of the machine instruction's operations,
5601     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
5602     // intrinsic has the numerator as the first operand to match a normal
5603     // division operation.
5604 
5605     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
5606 
5607     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
5608                        Denominator, Numerator);
5609   }
5610   case Intrinsic::amdgcn_icmp: {
5611     // There is a Pat that handles this variant, so return it as-is.
5612     if (Op.getOperand(1).getValueType() == MVT::i1 &&
5613         Op.getConstantOperandVal(2) == 0 &&
5614         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
5615       return Op;
5616     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
5617   }
5618   case Intrinsic::amdgcn_fcmp: {
5619     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
5620   }
5621   case Intrinsic::amdgcn_fmed3:
5622     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
5623                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5624   case Intrinsic::amdgcn_fdot2:
5625     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
5626                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
5627                        Op.getOperand(4));
5628   case Intrinsic::amdgcn_fmul_legacy:
5629     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
5630                        Op.getOperand(1), Op.getOperand(2));
5631   case Intrinsic::amdgcn_sffbh:
5632     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
5633   case Intrinsic::amdgcn_sbfe:
5634     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
5635                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5636   case Intrinsic::amdgcn_ubfe:
5637     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
5638                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
5639   case Intrinsic::amdgcn_cvt_pkrtz:
5640   case Intrinsic::amdgcn_cvt_pknorm_i16:
5641   case Intrinsic::amdgcn_cvt_pknorm_u16:
5642   case Intrinsic::amdgcn_cvt_pk_i16:
5643   case Intrinsic::amdgcn_cvt_pk_u16: {
5644     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
5645     EVT VT = Op.getValueType();
5646     unsigned Opcode;
5647 
5648     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
5649       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
5650     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
5651       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
5652     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
5653       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
5654     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
5655       Opcode = AMDGPUISD::CVT_PK_I16_I32;
5656     else
5657       Opcode = AMDGPUISD::CVT_PK_U16_U32;
5658 
5659     if (isTypeLegal(VT))
5660       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
5661 
5662     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
5663                                Op.getOperand(1), Op.getOperand(2));
5664     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
5665   }
5666   case Intrinsic::amdgcn_wqm: {
5667     SDValue Src = Op.getOperand(1);
5668     return SDValue(DAG.getMachineNode(AMDGPU::WQM, DL, Src.getValueType(), Src),
5669                    0);
5670   }
5671   case Intrinsic::amdgcn_wwm: {
5672     SDValue Src = Op.getOperand(1);
5673     return SDValue(DAG.getMachineNode(AMDGPU::WWM, DL, Src.getValueType(), Src),
5674                    0);
5675   }
5676   case Intrinsic::amdgcn_fmad_ftz:
5677     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
5678                        Op.getOperand(2), Op.getOperand(3));
5679 
5680   case Intrinsic::amdgcn_if_break:
5681     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
5682                                       Op->getOperand(1), Op->getOperand(2)), 0);
5683 
5684   default:
5685     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
5686             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
5687       return lowerImage(Op, ImageDimIntr, DAG);
5688 
5689     return Op;
5690   }
5691 }
5692 
5693 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
5694                                                  SelectionDAG &DAG) const {
5695   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
5696   SDLoc DL(Op);
5697 
5698   switch (IntrID) {
5699   case Intrinsic::amdgcn_ds_ordered_add:
5700   case Intrinsic::amdgcn_ds_ordered_swap: {
5701     MemSDNode *M = cast<MemSDNode>(Op);
5702     SDValue Chain = M->getOperand(0);
5703     SDValue M0 = M->getOperand(2);
5704     SDValue Value = M->getOperand(3);
5705     unsigned OrderedCountIndex = M->getConstantOperandVal(7);
5706     unsigned WaveRelease = M->getConstantOperandVal(8);
5707     unsigned WaveDone = M->getConstantOperandVal(9);
5708     unsigned ShaderType;
5709     unsigned Instruction;
5710 
5711     switch (IntrID) {
5712     case Intrinsic::amdgcn_ds_ordered_add:
5713       Instruction = 0;
5714       break;
5715     case Intrinsic::amdgcn_ds_ordered_swap:
5716       Instruction = 1;
5717       break;
5718     }
5719 
5720     if (WaveDone && !WaveRelease)
5721       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
5722 
5723     switch (DAG.getMachineFunction().getFunction().getCallingConv()) {
5724     case CallingConv::AMDGPU_CS:
5725     case CallingConv::AMDGPU_KERNEL:
5726       ShaderType = 0;
5727       break;
5728     case CallingConv::AMDGPU_PS:
5729       ShaderType = 1;
5730       break;
5731     case CallingConv::AMDGPU_VS:
5732       ShaderType = 2;
5733       break;
5734     case CallingConv::AMDGPU_GS:
5735       ShaderType = 3;
5736       break;
5737     default:
5738       report_fatal_error("ds_ordered_count unsupported for this calling conv");
5739     }
5740 
5741     unsigned Offset0 = OrderedCountIndex << 2;
5742     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
5743                        (Instruction << 4);
5744     unsigned Offset = Offset0 | (Offset1 << 8);
5745 
5746     SDValue Ops[] = {
5747       Chain,
5748       Value,
5749       DAG.getTargetConstant(Offset, DL, MVT::i16),
5750       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
5751     };
5752     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
5753                                    M->getVTList(), Ops, M->getMemoryVT(),
5754                                    M->getMemOperand());
5755   }
5756   case Intrinsic::amdgcn_ds_fadd: {
5757     MemSDNode *M = cast<MemSDNode>(Op);
5758     unsigned Opc;
5759     switch (IntrID) {
5760     case Intrinsic::amdgcn_ds_fadd:
5761       Opc = ISD::ATOMIC_LOAD_FADD;
5762       break;
5763     }
5764 
5765     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
5766                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
5767                          M->getMemOperand());
5768   }
5769   case Intrinsic::amdgcn_atomic_inc:
5770   case Intrinsic::amdgcn_atomic_dec:
5771   case Intrinsic::amdgcn_ds_fmin:
5772   case Intrinsic::amdgcn_ds_fmax: {
5773     MemSDNode *M = cast<MemSDNode>(Op);
5774     unsigned Opc;
5775     switch (IntrID) {
5776     case Intrinsic::amdgcn_atomic_inc:
5777       Opc = AMDGPUISD::ATOMIC_INC;
5778       break;
5779     case Intrinsic::amdgcn_atomic_dec:
5780       Opc = AMDGPUISD::ATOMIC_DEC;
5781       break;
5782     case Intrinsic::amdgcn_ds_fmin:
5783       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
5784       break;
5785     case Intrinsic::amdgcn_ds_fmax:
5786       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
5787       break;
5788     default:
5789       llvm_unreachable("Unknown intrinsic!");
5790     }
5791     SDValue Ops[] = {
5792       M->getOperand(0), // Chain
5793       M->getOperand(2), // Ptr
5794       M->getOperand(3)  // Value
5795     };
5796 
5797     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
5798                                    M->getMemoryVT(), M->getMemOperand());
5799   }
5800   case Intrinsic::amdgcn_buffer_load:
5801   case Intrinsic::amdgcn_buffer_load_format: {
5802     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
5803     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
5804     unsigned IdxEn = 1;
5805     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
5806       IdxEn = Idx->getZExtValue() != 0;
5807     SDValue Ops[] = {
5808       Op.getOperand(0), // Chain
5809       Op.getOperand(2), // rsrc
5810       Op.getOperand(3), // vindex
5811       SDValue(),        // voffset -- will be set by setBufferOffsets
5812       SDValue(),        // soffset -- will be set by setBufferOffsets
5813       SDValue(),        // offset -- will be set by setBufferOffsets
5814       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
5815       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
5816     };
5817 
5818     setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
5819     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
5820         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5821 
5822     EVT VT = Op.getValueType();
5823     EVT IntVT = VT.changeTypeToInteger();
5824     auto *M = cast<MemSDNode>(Op);
5825     EVT LoadVT = Op.getValueType();
5826 
5827     if (LoadVT.getScalarType() == MVT::f16)
5828       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
5829                                  M, DAG, Ops);
5830 
5831     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
5832     if (LoadVT.getScalarType() == MVT::i8 ||
5833         LoadVT.getScalarType() == MVT::i16)
5834       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
5835 
5836     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5837                                M->getMemOperand(), DAG);
5838   }
5839   case Intrinsic::amdgcn_raw_buffer_load:
5840   case Intrinsic::amdgcn_raw_buffer_load_format: {
5841     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
5842     SDValue Ops[] = {
5843       Op.getOperand(0), // Chain
5844       Op.getOperand(2), // rsrc
5845       DAG.getConstant(0, DL, MVT::i32), // vindex
5846       Offsets.first,    // voffset
5847       Op.getOperand(4), // soffset
5848       Offsets.second,   // offset
5849       Op.getOperand(5), // cachepolicy
5850       DAG.getConstant(0, DL, MVT::i1), // idxen
5851     };
5852 
5853     unsigned Opc = (IntrID == Intrinsic::amdgcn_raw_buffer_load) ?
5854         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5855 
5856     EVT VT = Op.getValueType();
5857     EVT IntVT = VT.changeTypeToInteger();
5858     auto *M = cast<MemSDNode>(Op);
5859     EVT LoadVT = Op.getValueType();
5860 
5861     if (LoadVT.getScalarType() == MVT::f16)
5862       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
5863                                  M, DAG, Ops);
5864 
5865     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
5866     if (LoadVT.getScalarType() == MVT::i8 ||
5867         LoadVT.getScalarType() == MVT::i16)
5868       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
5869 
5870     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5871                                M->getMemOperand(), DAG);
5872   }
5873   case Intrinsic::amdgcn_struct_buffer_load:
5874   case Intrinsic::amdgcn_struct_buffer_load_format: {
5875     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
5876     SDValue Ops[] = {
5877       Op.getOperand(0), // Chain
5878       Op.getOperand(2), // rsrc
5879       Op.getOperand(3), // vindex
5880       Offsets.first,    // voffset
5881       Op.getOperand(5), // soffset
5882       Offsets.second,   // offset
5883       Op.getOperand(6), // cachepolicy
5884       DAG.getConstant(1, DL, MVT::i1), // idxen
5885     };
5886 
5887     unsigned Opc = (IntrID == Intrinsic::amdgcn_struct_buffer_load) ?
5888         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
5889 
5890     EVT VT = Op.getValueType();
5891     EVT IntVT = VT.changeTypeToInteger();
5892     auto *M = cast<MemSDNode>(Op);
5893     EVT LoadVT = Op.getValueType();
5894 
5895     if (LoadVT.getScalarType() == MVT::f16)
5896       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
5897                                  M, DAG, Ops);
5898 
5899     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
5900     if (LoadVT.getScalarType() == MVT::i8 ||
5901         LoadVT.getScalarType() == MVT::i16)
5902       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
5903 
5904     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
5905                                M->getMemOperand(), DAG);
5906   }
5907   case Intrinsic::amdgcn_tbuffer_load: {
5908     MemSDNode *M = cast<MemSDNode>(Op);
5909     EVT LoadVT = Op.getValueType();
5910 
5911     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
5912     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
5913     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
5914     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
5915     unsigned IdxEn = 1;
5916     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
5917       IdxEn = Idx->getZExtValue() != 0;
5918     SDValue Ops[] = {
5919       Op.getOperand(0),  // Chain
5920       Op.getOperand(2),  // rsrc
5921       Op.getOperand(3),  // vindex
5922       Op.getOperand(4),  // voffset
5923       Op.getOperand(5),  // soffset
5924       Op.getOperand(6),  // offset
5925       DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
5926       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
5927       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
5928     };
5929 
5930     if (LoadVT.getScalarType() == MVT::f16)
5931       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
5932                                  M, DAG, Ops);
5933     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5934                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
5935                                DAG);
5936   }
5937   case Intrinsic::amdgcn_raw_tbuffer_load: {
5938     MemSDNode *M = cast<MemSDNode>(Op);
5939     EVT LoadVT = Op.getValueType();
5940     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
5941 
5942     SDValue Ops[] = {
5943       Op.getOperand(0),  // Chain
5944       Op.getOperand(2),  // rsrc
5945       DAG.getConstant(0, DL, MVT::i32), // vindex
5946       Offsets.first,     // voffset
5947       Op.getOperand(4),  // soffset
5948       Offsets.second,    // offset
5949       Op.getOperand(5),  // format
5950       Op.getOperand(6),  // cachepolicy
5951       DAG.getConstant(0, DL, MVT::i1), // idxen
5952     };
5953 
5954     if (LoadVT.getScalarType() == MVT::f16)
5955       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
5956                                  M, DAG, Ops);
5957     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5958                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
5959                                DAG);
5960   }
5961   case Intrinsic::amdgcn_struct_tbuffer_load: {
5962     MemSDNode *M = cast<MemSDNode>(Op);
5963     EVT LoadVT = Op.getValueType();
5964     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
5965 
5966     SDValue Ops[] = {
5967       Op.getOperand(0),  // Chain
5968       Op.getOperand(2),  // rsrc
5969       Op.getOperand(3),  // vindex
5970       Offsets.first,     // voffset
5971       Op.getOperand(5),  // soffset
5972       Offsets.second,    // offset
5973       Op.getOperand(6),  // format
5974       Op.getOperand(7),  // cachepolicy
5975       DAG.getConstant(1, DL, MVT::i1), // idxen
5976     };
5977 
5978     if (LoadVT.getScalarType() == MVT::f16)
5979       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
5980                                  M, DAG, Ops);
5981     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
5982                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
5983                                DAG);
5984   }
5985   case Intrinsic::amdgcn_buffer_atomic_swap:
5986   case Intrinsic::amdgcn_buffer_atomic_add:
5987   case Intrinsic::amdgcn_buffer_atomic_sub:
5988   case Intrinsic::amdgcn_buffer_atomic_smin:
5989   case Intrinsic::amdgcn_buffer_atomic_umin:
5990   case Intrinsic::amdgcn_buffer_atomic_smax:
5991   case Intrinsic::amdgcn_buffer_atomic_umax:
5992   case Intrinsic::amdgcn_buffer_atomic_and:
5993   case Intrinsic::amdgcn_buffer_atomic_or:
5994   case Intrinsic::amdgcn_buffer_atomic_xor: {
5995     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
5996     unsigned IdxEn = 1;
5997     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
5998       IdxEn = Idx->getZExtValue() != 0;
5999     SDValue Ops[] = {
6000       Op.getOperand(0), // Chain
6001       Op.getOperand(2), // vdata
6002       Op.getOperand(3), // rsrc
6003       Op.getOperand(4), // vindex
6004       SDValue(),        // voffset -- will be set by setBufferOffsets
6005       SDValue(),        // soffset -- will be set by setBufferOffsets
6006       SDValue(),        // offset -- will be set by setBufferOffsets
6007       DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6008       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6009     };
6010     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6011     EVT VT = Op.getValueType();
6012 
6013     auto *M = cast<MemSDNode>(Op);
6014     unsigned Opcode = 0;
6015 
6016     switch (IntrID) {
6017     case Intrinsic::amdgcn_buffer_atomic_swap:
6018       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6019       break;
6020     case Intrinsic::amdgcn_buffer_atomic_add:
6021       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6022       break;
6023     case Intrinsic::amdgcn_buffer_atomic_sub:
6024       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6025       break;
6026     case Intrinsic::amdgcn_buffer_atomic_smin:
6027       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6028       break;
6029     case Intrinsic::amdgcn_buffer_atomic_umin:
6030       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6031       break;
6032     case Intrinsic::amdgcn_buffer_atomic_smax:
6033       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6034       break;
6035     case Intrinsic::amdgcn_buffer_atomic_umax:
6036       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6037       break;
6038     case Intrinsic::amdgcn_buffer_atomic_and:
6039       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6040       break;
6041     case Intrinsic::amdgcn_buffer_atomic_or:
6042       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6043       break;
6044     case Intrinsic::amdgcn_buffer_atomic_xor:
6045       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6046       break;
6047     default:
6048       llvm_unreachable("unhandled atomic opcode");
6049     }
6050 
6051     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6052                                    M->getMemOperand());
6053   }
6054   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6055   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6056   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6057   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6058   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6059   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6060   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6061   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6062   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6063   case Intrinsic::amdgcn_raw_buffer_atomic_xor: {
6064     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6065     SDValue Ops[] = {
6066       Op.getOperand(0), // Chain
6067       Op.getOperand(2), // vdata
6068       Op.getOperand(3), // rsrc
6069       DAG.getConstant(0, DL, MVT::i32), // vindex
6070       Offsets.first,    // voffset
6071       Op.getOperand(5), // soffset
6072       Offsets.second,   // offset
6073       Op.getOperand(6), // cachepolicy
6074       DAG.getConstant(0, DL, MVT::i1), // idxen
6075     };
6076     EVT VT = Op.getValueType();
6077 
6078     auto *M = cast<MemSDNode>(Op);
6079     unsigned Opcode = 0;
6080 
6081     switch (IntrID) {
6082     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6083       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6084       break;
6085     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6086       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6087       break;
6088     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6089       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6090       break;
6091     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6092       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6093       break;
6094     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6095       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6096       break;
6097     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6098       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6099       break;
6100     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6101       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6102       break;
6103     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6104       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6105       break;
6106     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6107       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6108       break;
6109     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6110       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6111       break;
6112     default:
6113       llvm_unreachable("unhandled atomic opcode");
6114     }
6115 
6116     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6117                                    M->getMemOperand());
6118   }
6119   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6120   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6121   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6122   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6123   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6124   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6125   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6126   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6127   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6128   case Intrinsic::amdgcn_struct_buffer_atomic_xor: {
6129     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6130     SDValue Ops[] = {
6131       Op.getOperand(0), // Chain
6132       Op.getOperand(2), // vdata
6133       Op.getOperand(3), // rsrc
6134       Op.getOperand(4), // vindex
6135       Offsets.first,    // voffset
6136       Op.getOperand(6), // soffset
6137       Offsets.second,   // offset
6138       Op.getOperand(7), // cachepolicy
6139       DAG.getConstant(1, DL, MVT::i1), // idxen
6140     };
6141     EVT VT = Op.getValueType();
6142 
6143     auto *M = cast<MemSDNode>(Op);
6144     unsigned Opcode = 0;
6145 
6146     switch (IntrID) {
6147     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6148       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6149       break;
6150     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6151       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6152       break;
6153     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6154       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6155       break;
6156     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6157       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6158       break;
6159     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6160       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6161       break;
6162     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6163       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6164       break;
6165     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6166       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6167       break;
6168     case Intrinsic::amdgcn_struct_buffer_atomic_and:
6169       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6170       break;
6171     case Intrinsic::amdgcn_struct_buffer_atomic_or:
6172       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6173       break;
6174     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6175       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6176       break;
6177     default:
6178       llvm_unreachable("unhandled atomic opcode");
6179     }
6180 
6181     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6182                                    M->getMemOperand());
6183   }
6184   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
6185     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6186     unsigned IdxEn = 1;
6187     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
6188       IdxEn = Idx->getZExtValue() != 0;
6189     SDValue Ops[] = {
6190       Op.getOperand(0), // Chain
6191       Op.getOperand(2), // src
6192       Op.getOperand(3), // cmp
6193       Op.getOperand(4), // rsrc
6194       Op.getOperand(5), // vindex
6195       SDValue(),        // voffset -- will be set by setBufferOffsets
6196       SDValue(),        // soffset -- will be set by setBufferOffsets
6197       SDValue(),        // offset -- will be set by setBufferOffsets
6198       DAG.getConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6199       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6200     };
6201     setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
6202     EVT VT = Op.getValueType();
6203     auto *M = cast<MemSDNode>(Op);
6204 
6205     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6206                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6207   }
6208   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
6209     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6210     SDValue Ops[] = {
6211       Op.getOperand(0), // Chain
6212       Op.getOperand(2), // src
6213       Op.getOperand(3), // cmp
6214       Op.getOperand(4), // rsrc
6215       DAG.getConstant(0, DL, MVT::i32), // vindex
6216       Offsets.first,    // voffset
6217       Op.getOperand(6), // soffset
6218       Offsets.second,   // offset
6219       Op.getOperand(7), // cachepolicy
6220       DAG.getConstant(0, DL, MVT::i1), // idxen
6221     };
6222     EVT VT = Op.getValueType();
6223     auto *M = cast<MemSDNode>(Op);
6224 
6225     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6226                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6227   }
6228   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
6229     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
6230     SDValue Ops[] = {
6231       Op.getOperand(0), // Chain
6232       Op.getOperand(2), // src
6233       Op.getOperand(3), // cmp
6234       Op.getOperand(4), // rsrc
6235       Op.getOperand(5), // vindex
6236       Offsets.first,    // voffset
6237       Op.getOperand(7), // soffset
6238       Offsets.second,   // offset
6239       Op.getOperand(8), // cachepolicy
6240       DAG.getConstant(1, DL, MVT::i1), // idxen
6241     };
6242     EVT VT = Op.getValueType();
6243     auto *M = cast<MemSDNode>(Op);
6244 
6245     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
6246                                    Op->getVTList(), Ops, VT, M->getMemOperand());
6247   }
6248 
6249   default:
6250     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6251             AMDGPU::getImageDimIntrinsicInfo(IntrID))
6252       return lowerImage(Op, ImageDimIntr, DAG);
6253 
6254     return SDValue();
6255   }
6256 }
6257 
6258 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
6259 // dwordx4 if on SI.
6260 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
6261                                               SDVTList VTList,
6262                                               ArrayRef<SDValue> Ops, EVT MemVT,
6263                                               MachineMemOperand *MMO,
6264                                               SelectionDAG &DAG) const {
6265   EVT VT = VTList.VTs[0];
6266   EVT WidenedVT = VT;
6267   EVT WidenedMemVT = MemVT;
6268   if (!Subtarget->hasDwordx3LoadStores() &&
6269       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
6270     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
6271                                  WidenedVT.getVectorElementType(), 4);
6272     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
6273                                     WidenedMemVT.getVectorElementType(), 4);
6274     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
6275   }
6276 
6277   assert(VTList.NumVTs == 2);
6278   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
6279 
6280   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
6281                                        WidenedMemVT, MMO);
6282   if (WidenedVT != VT) {
6283     auto Extract = DAG.getNode(
6284         ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
6285         DAG.getConstant(0, DL, getVectorIdxTy(DAG.getDataLayout())));
6286     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
6287   }
6288   return NewOp;
6289 }
6290 
6291 SDValue SITargetLowering::handleD16VData(SDValue VData,
6292                                          SelectionDAG &DAG) const {
6293   EVT StoreVT = VData.getValueType();
6294 
6295   // No change for f16 and legal vector D16 types.
6296   if (!StoreVT.isVector())
6297     return VData;
6298 
6299   SDLoc DL(VData);
6300   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
6301 
6302   if (Subtarget->hasUnpackedD16VMem()) {
6303     // We need to unpack the packed data to store.
6304     EVT IntStoreVT = StoreVT.changeTypeToInteger();
6305     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
6306 
6307     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
6308                                         StoreVT.getVectorNumElements());
6309     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
6310     return DAG.UnrollVectorOp(ZExt.getNode());
6311   }
6312 
6313   assert(isTypeLegal(StoreVT));
6314   return VData;
6315 }
6316 
6317 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
6318                                               SelectionDAG &DAG) const {
6319   SDLoc DL(Op);
6320   SDValue Chain = Op.getOperand(0);
6321   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6322   MachineFunction &MF = DAG.getMachineFunction();
6323 
6324   switch (IntrinsicID) {
6325   case Intrinsic::amdgcn_exp: {
6326     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6327     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6328     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(8));
6329     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(9));
6330 
6331     const SDValue Ops[] = {
6332       Chain,
6333       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6334       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
6335       Op.getOperand(4), // src0
6336       Op.getOperand(5), // src1
6337       Op.getOperand(6), // src2
6338       Op.getOperand(7), // src3
6339       DAG.getTargetConstant(0, DL, MVT::i1), // compr
6340       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6341     };
6342 
6343     unsigned Opc = Done->isNullValue() ?
6344       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6345     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6346   }
6347   case Intrinsic::amdgcn_exp_compr: {
6348     const ConstantSDNode *Tgt = cast<ConstantSDNode>(Op.getOperand(2));
6349     const ConstantSDNode *En = cast<ConstantSDNode>(Op.getOperand(3));
6350     SDValue Src0 = Op.getOperand(4);
6351     SDValue Src1 = Op.getOperand(5);
6352     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
6353     const ConstantSDNode *VM = cast<ConstantSDNode>(Op.getOperand(7));
6354 
6355     SDValue Undef = DAG.getUNDEF(MVT::f32);
6356     const SDValue Ops[] = {
6357       Chain,
6358       DAG.getTargetConstant(Tgt->getZExtValue(), DL, MVT::i8), // tgt
6359       DAG.getTargetConstant(En->getZExtValue(), DL, MVT::i8),  // en
6360       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0),
6361       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1),
6362       Undef, // src2
6363       Undef, // src3
6364       DAG.getTargetConstant(1, DL, MVT::i1), // compr
6365       DAG.getTargetConstant(VM->getZExtValue(), DL, MVT::i1)
6366     };
6367 
6368     unsigned Opc = Done->isNullValue() ?
6369       AMDGPUISD::EXPORT : AMDGPUISD::EXPORT_DONE;
6370     return DAG.getNode(Opc, DL, Op->getVTList(), Ops);
6371   }
6372   case Intrinsic::amdgcn_s_sendmsg:
6373   case Intrinsic::amdgcn_s_sendmsghalt: {
6374     unsigned NodeOp = (IntrinsicID == Intrinsic::amdgcn_s_sendmsg) ?
6375       AMDGPUISD::SENDMSG : AMDGPUISD::SENDMSGHALT;
6376     Chain = copyToM0(DAG, Chain, DL, Op.getOperand(3));
6377     SDValue Glue = Chain.getValue(1);
6378     return DAG.getNode(NodeOp, DL, MVT::Other, Chain,
6379                        Op.getOperand(2), Glue);
6380   }
6381   case Intrinsic::amdgcn_init_exec: {
6382     return DAG.getNode(AMDGPUISD::INIT_EXEC, DL, MVT::Other, Chain,
6383                        Op.getOperand(2));
6384   }
6385   case Intrinsic::amdgcn_init_exec_from_input: {
6386     return DAG.getNode(AMDGPUISD::INIT_EXEC_FROM_INPUT, DL, MVT::Other, Chain,
6387                        Op.getOperand(2), Op.getOperand(3));
6388   }
6389   case Intrinsic::amdgcn_s_barrier: {
6390     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
6391       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
6392       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
6393       if (WGSize <= ST.getWavefrontSize())
6394         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
6395                                           Op.getOperand(0)), 0);
6396     }
6397     return SDValue();
6398   };
6399   case Intrinsic::amdgcn_tbuffer_store: {
6400     SDValue VData = Op.getOperand(2);
6401     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6402     if (IsD16)
6403       VData = handleD16VData(VData, DAG);
6404     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6405     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6406     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6407     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
6408     unsigned IdxEn = 1;
6409     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6410       IdxEn = Idx->getZExtValue() != 0;
6411     SDValue Ops[] = {
6412       Chain,
6413       VData,             // vdata
6414       Op.getOperand(3),  // rsrc
6415       Op.getOperand(4),  // vindex
6416       Op.getOperand(5),  // voffset
6417       Op.getOperand(6),  // soffset
6418       Op.getOperand(7),  // offset
6419       DAG.getConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6420       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6421       DAG.getConstant(IdxEn, DL, MVT::i1), // idexen
6422     };
6423     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6424                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6425     MemSDNode *M = cast<MemSDNode>(Op);
6426     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6427                                    M->getMemoryVT(), M->getMemOperand());
6428   }
6429 
6430   case Intrinsic::amdgcn_struct_tbuffer_store: {
6431     SDValue VData = Op.getOperand(2);
6432     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6433     if (IsD16)
6434       VData = handleD16VData(VData, DAG);
6435     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6436     SDValue Ops[] = {
6437       Chain,
6438       VData,             // vdata
6439       Op.getOperand(3),  // rsrc
6440       Op.getOperand(4),  // vindex
6441       Offsets.first,     // voffset
6442       Op.getOperand(6),  // soffset
6443       Offsets.second,    // offset
6444       Op.getOperand(7),  // format
6445       Op.getOperand(8),  // cachepolicy
6446       DAG.getConstant(1, DL, MVT::i1), // idexen
6447     };
6448     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6449                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6450     MemSDNode *M = cast<MemSDNode>(Op);
6451     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6452                                    M->getMemoryVT(), M->getMemOperand());
6453   }
6454 
6455   case Intrinsic::amdgcn_raw_tbuffer_store: {
6456     SDValue VData = Op.getOperand(2);
6457     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6458     if (IsD16)
6459       VData = handleD16VData(VData, DAG);
6460     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6461     SDValue Ops[] = {
6462       Chain,
6463       VData,             // vdata
6464       Op.getOperand(3),  // rsrc
6465       DAG.getConstant(0, DL, MVT::i32), // vindex
6466       Offsets.first,     // voffset
6467       Op.getOperand(5),  // soffset
6468       Offsets.second,    // offset
6469       Op.getOperand(6),  // format
6470       Op.getOperand(7),  // cachepolicy
6471       DAG.getConstant(0, DL, MVT::i1), // idexen
6472     };
6473     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
6474                            AMDGPUISD::TBUFFER_STORE_FORMAT;
6475     MemSDNode *M = cast<MemSDNode>(Op);
6476     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6477                                    M->getMemoryVT(), M->getMemOperand());
6478   }
6479 
6480   case Intrinsic::amdgcn_buffer_store:
6481   case Intrinsic::amdgcn_buffer_store_format: {
6482     SDValue VData = Op.getOperand(2);
6483     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6484     if (IsD16)
6485       VData = handleD16VData(VData, DAG);
6486     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6487     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6488     unsigned IdxEn = 1;
6489     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6490       IdxEn = Idx->getZExtValue() != 0;
6491     SDValue Ops[] = {
6492       Chain,
6493       VData,
6494       Op.getOperand(3), // rsrc
6495       Op.getOperand(4), // vindex
6496       SDValue(), // voffset -- will be set by setBufferOffsets
6497       SDValue(), // soffset -- will be set by setBufferOffsets
6498       SDValue(), // offset -- will be set by setBufferOffsets
6499       DAG.getConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6500       DAG.getConstant(IdxEn, DL, MVT::i1), // idxen
6501     };
6502     setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6503     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
6504                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6505     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6506     MemSDNode *M = cast<MemSDNode>(Op);
6507 
6508     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6509     EVT VDataType = VData.getValueType().getScalarType();
6510     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6511       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6512 
6513     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6514                                    M->getMemoryVT(), M->getMemOperand());
6515   }
6516 
6517   case Intrinsic::amdgcn_raw_buffer_store:
6518   case Intrinsic::amdgcn_raw_buffer_store_format: {
6519     SDValue VData = Op.getOperand(2);
6520     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6521     if (IsD16)
6522       VData = handleD16VData(VData, DAG);
6523     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6524     SDValue Ops[] = {
6525       Chain,
6526       VData,
6527       Op.getOperand(3), // rsrc
6528       DAG.getConstant(0, DL, MVT::i32), // vindex
6529       Offsets.first,    // voffset
6530       Op.getOperand(5), // soffset
6531       Offsets.second,   // offset
6532       Op.getOperand(6), // cachepolicy
6533       DAG.getConstant(0, DL, MVT::i1), // idxen
6534     };
6535     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_raw_buffer_store ?
6536                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6537     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6538     MemSDNode *M = cast<MemSDNode>(Op);
6539 
6540     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6541     EVT VDataType = VData.getValueType().getScalarType();
6542     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6543       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6544 
6545     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6546                                    M->getMemoryVT(), M->getMemOperand());
6547   }
6548 
6549   case Intrinsic::amdgcn_struct_buffer_store:
6550   case Intrinsic::amdgcn_struct_buffer_store_format: {
6551     SDValue VData = Op.getOperand(2);
6552     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
6553     if (IsD16)
6554       VData = handleD16VData(VData, DAG);
6555     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6556     SDValue Ops[] = {
6557       Chain,
6558       VData,
6559       Op.getOperand(3), // rsrc
6560       Op.getOperand(4), // vindex
6561       Offsets.first,    // voffset
6562       Op.getOperand(6), // soffset
6563       Offsets.second,   // offset
6564       Op.getOperand(7), // cachepolicy
6565       DAG.getConstant(1, DL, MVT::i1), // idxen
6566     };
6567     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
6568                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
6569     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
6570     MemSDNode *M = cast<MemSDNode>(Op);
6571 
6572     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
6573     EVT VDataType = VData.getValueType().getScalarType();
6574     if (VDataType == MVT::i8 || VDataType == MVT::i16)
6575       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
6576 
6577     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
6578                                    M->getMemoryVT(), M->getMemOperand());
6579   }
6580 
6581   case Intrinsic::amdgcn_end_cf:
6582     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
6583                                       Op->getOperand(2), Chain), 0);
6584 
6585   default: {
6586     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6587             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6588       return lowerImage(Op, ImageDimIntr, DAG);
6589 
6590     return Op;
6591   }
6592   }
6593 }
6594 
6595 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
6596 // offset (the offset that is included in bounds checking and swizzling, to be
6597 // split between the instruction's voffset and immoffset fields) and soffset
6598 // (the offset that is excluded from bounds checking and swizzling, to go in
6599 // the instruction's soffset field).  This function takes the first kind of
6600 // offset and figures out how to split it between voffset and immoffset.
6601 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
6602     SDValue Offset, SelectionDAG &DAG) const {
6603   SDLoc DL(Offset);
6604   const unsigned MaxImm = 4095;
6605   SDValue N0 = Offset;
6606   ConstantSDNode *C1 = nullptr;
6607 
6608   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
6609     N0 = SDValue();
6610   else if (DAG.isBaseWithConstantOffset(N0)) {
6611     C1 = cast<ConstantSDNode>(N0.getOperand(1));
6612     N0 = N0.getOperand(0);
6613   }
6614 
6615   if (C1) {
6616     unsigned ImmOffset = C1->getZExtValue();
6617     // If the immediate value is too big for the immoffset field, put the value
6618     // and -4096 into the immoffset field so that the value that is copied/added
6619     // for the voffset field is a multiple of 4096, and it stands more chance
6620     // of being CSEd with the copy/add for another similar load/store.
6621     // However, do not do that rounding down to a multiple of 4096 if that is a
6622     // negative number, as it appears to be illegal to have a negative offset
6623     // in the vgpr, even if adding the immediate offset makes it positive.
6624     unsigned Overflow = ImmOffset & ~MaxImm;
6625     ImmOffset -= Overflow;
6626     if ((int32_t)Overflow < 0) {
6627       Overflow += ImmOffset;
6628       ImmOffset = 0;
6629     }
6630     C1 = cast<ConstantSDNode>(DAG.getConstant(ImmOffset, DL, MVT::i32));
6631     if (Overflow) {
6632       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
6633       if (!N0)
6634         N0 = OverflowVal;
6635       else {
6636         SDValue Ops[] = { N0, OverflowVal };
6637         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
6638       }
6639     }
6640   }
6641   if (!N0)
6642     N0 = DAG.getConstant(0, DL, MVT::i32);
6643   if (!C1)
6644     C1 = cast<ConstantSDNode>(DAG.getConstant(0, DL, MVT::i32));
6645   return {N0, SDValue(C1, 0)};
6646 }
6647 
6648 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
6649 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
6650 // pointed to by Offsets.
6651 void SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
6652                                         SelectionDAG &DAG, SDValue *Offsets,
6653                                         unsigned Align) const {
6654   SDLoc DL(CombinedOffset);
6655   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
6656     uint32_t Imm = C->getZExtValue();
6657     uint32_t SOffset, ImmOffset;
6658     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
6659       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
6660       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
6661       Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
6662       return;
6663     }
6664   }
6665   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
6666     SDValue N0 = CombinedOffset.getOperand(0);
6667     SDValue N1 = CombinedOffset.getOperand(1);
6668     uint32_t SOffset, ImmOffset;
6669     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
6670     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
6671                                                 Subtarget, Align)) {
6672       Offsets[0] = N0;
6673       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
6674       Offsets[2] = DAG.getConstant(ImmOffset, DL, MVT::i32);
6675       return;
6676     }
6677   }
6678   Offsets[0] = CombinedOffset;
6679   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
6680   Offsets[2] = DAG.getConstant(0, DL, MVT::i32);
6681 }
6682 
6683 // Handle 8 bit and 16 bit buffer loads
6684 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
6685                                                      EVT LoadVT, SDLoc DL,
6686                                                      ArrayRef<SDValue> Ops,
6687                                                      MemSDNode *M) const {
6688   EVT IntVT = LoadVT.changeTypeToInteger();
6689   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
6690          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
6691 
6692   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
6693   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
6694                                                Ops, IntVT,
6695                                                M->getMemOperand());
6696   SDValue BufferLoadTrunc = DAG.getNode(ISD::TRUNCATE, DL,
6697                                         LoadVT.getScalarType(), BufferLoad);
6698   return DAG.getMergeValues({BufferLoadTrunc, BufferLoad.getValue(1)}, DL);
6699 }
6700 
6701 // Handle 8 bit and 16 bit buffer stores
6702 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
6703                                                       EVT VDataType, SDLoc DL,
6704                                                       SDValue Ops[],
6705                                                       MemSDNode *M) const {
6706   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
6707   Ops[1] = BufferStoreExt;
6708   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
6709                                  AMDGPUISD::BUFFER_STORE_SHORT;
6710   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
6711   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
6712                                      M->getMemOperand());
6713 }
6714 
6715 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
6716                                  ISD::LoadExtType ExtType, SDValue Op,
6717                                  const SDLoc &SL, EVT VT) {
6718   if (VT.bitsLT(Op.getValueType()))
6719     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
6720 
6721   switch (ExtType) {
6722   case ISD::SEXTLOAD:
6723     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
6724   case ISD::ZEXTLOAD:
6725     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
6726   case ISD::EXTLOAD:
6727     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
6728   case ISD::NON_EXTLOAD:
6729     return Op;
6730   }
6731 
6732   llvm_unreachable("invalid ext type");
6733 }
6734 
6735 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
6736   SelectionDAG &DAG = DCI.DAG;
6737   if (Ld->getAlignment() < 4 || Ld->isDivergent())
6738     return SDValue();
6739 
6740   // FIXME: Constant loads should all be marked invariant.
6741   unsigned AS = Ld->getAddressSpace();
6742   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
6743       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
6744       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
6745     return SDValue();
6746 
6747   // Don't do this early, since it may interfere with adjacent load merging for
6748   // illegal types. We can avoid losing alignment information for exotic types
6749   // pre-legalize.
6750   EVT MemVT = Ld->getMemoryVT();
6751   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
6752       MemVT.getSizeInBits() >= 32)
6753     return SDValue();
6754 
6755   SDLoc SL(Ld);
6756 
6757   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
6758          "unexpected vector extload");
6759 
6760   // TODO: Drop only high part of range.
6761   SDValue Ptr = Ld->getBasePtr();
6762   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
6763                                 MVT::i32, SL, Ld->getChain(), Ptr,
6764                                 Ld->getOffset(),
6765                                 Ld->getPointerInfo(), MVT::i32,
6766                                 Ld->getAlignment(),
6767                                 Ld->getMemOperand()->getFlags(),
6768                                 Ld->getAAInfo(),
6769                                 nullptr); // Drop ranges
6770 
6771   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
6772   if (MemVT.isFloatingPoint()) {
6773     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
6774            "unexpected fp extload");
6775     TruncVT = MemVT.changeTypeToInteger();
6776   }
6777 
6778   SDValue Cvt = NewLoad;
6779   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
6780     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
6781                       DAG.getValueType(TruncVT));
6782   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
6783              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
6784     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
6785   } else {
6786     assert(Ld->getExtensionType() == ISD::EXTLOAD);
6787   }
6788 
6789   EVT VT = Ld->getValueType(0);
6790   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
6791 
6792   DCI.AddToWorklist(Cvt.getNode());
6793 
6794   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
6795   // the appropriate extension from the 32-bit load.
6796   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
6797   DCI.AddToWorklist(Cvt.getNode());
6798 
6799   // Handle conversion back to floating point if necessary.
6800   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
6801 
6802   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
6803 }
6804 
6805 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
6806   SDLoc DL(Op);
6807   LoadSDNode *Load = cast<LoadSDNode>(Op);
6808   ISD::LoadExtType ExtType = Load->getExtensionType();
6809   EVT MemVT = Load->getMemoryVT();
6810 
6811   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
6812     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
6813       return SDValue();
6814 
6815     // FIXME: Copied from PPC
6816     // First, load into 32 bits, then truncate to 1 bit.
6817 
6818     SDValue Chain = Load->getChain();
6819     SDValue BasePtr = Load->getBasePtr();
6820     MachineMemOperand *MMO = Load->getMemOperand();
6821 
6822     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
6823 
6824     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
6825                                    BasePtr, RealMemVT, MMO);
6826 
6827     if (!MemVT.isVector()) {
6828       SDValue Ops[] = {
6829         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
6830         NewLD.getValue(1)
6831       };
6832 
6833       return DAG.getMergeValues(Ops, DL);
6834     }
6835 
6836     SmallVector<SDValue, 3> Elts;
6837     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
6838       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
6839                                 DAG.getConstant(I, DL, MVT::i32));
6840 
6841       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
6842     }
6843 
6844     SDValue Ops[] = {
6845       DAG.getBuildVector(MemVT, DL, Elts),
6846       NewLD.getValue(1)
6847     };
6848 
6849     return DAG.getMergeValues(Ops, DL);
6850   }
6851 
6852   if (!MemVT.isVector())
6853     return SDValue();
6854 
6855   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
6856          "Custom lowering for non-i32 vectors hasn't been implemented.");
6857 
6858   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
6859                           *Load->getMemOperand())) {
6860     SDValue Ops[2];
6861     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
6862     return DAG.getMergeValues(Ops, DL);
6863   }
6864 
6865   unsigned Alignment = Load->getAlignment();
6866   unsigned AS = Load->getAddressSpace();
6867   if (Subtarget->hasLDSMisalignedBug() &&
6868       AS == AMDGPUAS::FLAT_ADDRESS &&
6869       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
6870     return SplitVectorLoad(Op, DAG);
6871   }
6872 
6873   MachineFunction &MF = DAG.getMachineFunction();
6874   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
6875   // If there is a possibilty that flat instruction access scratch memory
6876   // then we need to use the same legalization rules we use for private.
6877   if (AS == AMDGPUAS::FLAT_ADDRESS)
6878     AS = MFI->hasFlatScratchInit() ?
6879          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
6880 
6881   unsigned NumElements = MemVT.getVectorNumElements();
6882 
6883   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
6884       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
6885     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
6886       if (MemVT.isPow2VectorType())
6887         return SDValue();
6888       if (NumElements == 3)
6889         return WidenVectorLoad(Op, DAG);
6890       return SplitVectorLoad(Op, DAG);
6891     }
6892     // Non-uniform loads will be selected to MUBUF instructions, so they
6893     // have the same legalization requirements as global and private
6894     // loads.
6895     //
6896   }
6897 
6898   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
6899       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
6900       AS == AMDGPUAS::GLOBAL_ADDRESS) {
6901     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
6902         !Load->isVolatile() && isMemOpHasNoClobberedMemOperand(Load) &&
6903         Alignment >= 4 && NumElements < 32) {
6904       if (MemVT.isPow2VectorType())
6905         return SDValue();
6906       if (NumElements == 3)
6907         return WidenVectorLoad(Op, DAG);
6908       return SplitVectorLoad(Op, DAG);
6909     }
6910     // Non-uniform loads will be selected to MUBUF instructions, so they
6911     // have the same legalization requirements as global and private
6912     // loads.
6913     //
6914   }
6915   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
6916       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
6917       AS == AMDGPUAS::GLOBAL_ADDRESS ||
6918       AS == AMDGPUAS::FLAT_ADDRESS) {
6919     if (NumElements > 4)
6920       return SplitVectorLoad(Op, DAG);
6921     // v3 loads not supported on SI.
6922     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
6923       return WidenVectorLoad(Op, DAG);
6924     // v3 and v4 loads are supported for private and global memory.
6925     return SDValue();
6926   }
6927   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
6928     // Depending on the setting of the private_element_size field in the
6929     // resource descriptor, we can only make private accesses up to a certain
6930     // size.
6931     switch (Subtarget->getMaxPrivateElementSize()) {
6932     case 4:
6933       return scalarizeVectorLoad(Load, DAG);
6934     case 8:
6935       if (NumElements > 2)
6936         return SplitVectorLoad(Op, DAG);
6937       return SDValue();
6938     case 16:
6939       // Same as global/flat
6940       if (NumElements > 4)
6941         return SplitVectorLoad(Op, DAG);
6942       // v3 loads not supported on SI.
6943       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
6944         return WidenVectorLoad(Op, DAG);
6945       return SDValue();
6946     default:
6947       llvm_unreachable("unsupported private_element_size");
6948     }
6949   } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
6950     // Use ds_read_b128 if possible.
6951     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
6952         MemVT.getStoreSize() == 16)
6953       return SDValue();
6954 
6955     if (NumElements > 2)
6956       return SplitVectorLoad(Op, DAG);
6957 
6958     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
6959     // address is negative, then the instruction is incorrectly treated as
6960     // out-of-bounds even if base + offsets is in bounds. Split vectorized
6961     // loads here to avoid emitting ds_read2_b32. We may re-combine the
6962     // load later in the SILoadStoreOptimizer.
6963     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
6964         NumElements == 2 && MemVT.getStoreSize() == 8 &&
6965         Load->getAlignment() < 8) {
6966       return SplitVectorLoad(Op, DAG);
6967     }
6968   }
6969   return SDValue();
6970 }
6971 
6972 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
6973   EVT VT = Op.getValueType();
6974   assert(VT.getSizeInBits() == 64);
6975 
6976   SDLoc DL(Op);
6977   SDValue Cond = Op.getOperand(0);
6978 
6979   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
6980   SDValue One = DAG.getConstant(1, DL, MVT::i32);
6981 
6982   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
6983   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
6984 
6985   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
6986   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
6987 
6988   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
6989 
6990   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
6991   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
6992 
6993   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
6994 
6995   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
6996   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
6997 }
6998 
6999 // Catch division cases where we can use shortcuts with rcp and rsq
7000 // instructions.
7001 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7002                                               SelectionDAG &DAG) const {
7003   SDLoc SL(Op);
7004   SDValue LHS = Op.getOperand(0);
7005   SDValue RHS = Op.getOperand(1);
7006   EVT VT = Op.getValueType();
7007   const SDNodeFlags Flags = Op->getFlags();
7008   bool Unsafe = DAG.getTarget().Options.UnsafeFPMath || Flags.hasAllowReciprocal();
7009 
7010   if (!Unsafe && VT == MVT::f32 && Subtarget->hasFP32Denormals())
7011     return SDValue();
7012 
7013   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7014     if (Unsafe || VT == MVT::f32 || VT == MVT::f16) {
7015       if (CLHS->isExactlyValue(1.0)) {
7016         // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7017         // the CI documentation has a worst case error of 1 ulp.
7018         // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7019         // use it as long as we aren't trying to use denormals.
7020         //
7021         // v_rcp_f16 and v_rsq_f16 DO support denormals.
7022 
7023         // 1.0 / sqrt(x) -> rsq(x)
7024 
7025         // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7026         // error seems really high at 2^29 ULP.
7027         if (RHS.getOpcode() == ISD::FSQRT)
7028           return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7029 
7030         // 1.0 / x -> rcp(x)
7031         return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7032       }
7033 
7034       // Same as for 1.0, but expand the sign out of the constant.
7035       if (CLHS->isExactlyValue(-1.0)) {
7036         // -1.0 / x -> rcp (fneg x)
7037         SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7038         return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7039       }
7040     }
7041   }
7042 
7043   if (Unsafe) {
7044     // Turn into multiply by the reciprocal.
7045     // x / y -> x * (1.0 / y)
7046     SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7047     return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7048   }
7049 
7050   return SDValue();
7051 }
7052 
7053 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7054                           EVT VT, SDValue A, SDValue B, SDValue GlueChain) {
7055   if (GlueChain->getNumValues() <= 1) {
7056     return DAG.getNode(Opcode, SL, VT, A, B);
7057   }
7058 
7059   assert(GlueChain->getNumValues() == 3);
7060 
7061   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7062   switch (Opcode) {
7063   default: llvm_unreachable("no chain equivalent for opcode");
7064   case ISD::FMUL:
7065     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7066     break;
7067   }
7068 
7069   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B,
7070                      GlueChain.getValue(2));
7071 }
7072 
7073 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7074                            EVT VT, SDValue A, SDValue B, SDValue C,
7075                            SDValue GlueChain) {
7076   if (GlueChain->getNumValues() <= 1) {
7077     return DAG.getNode(Opcode, SL, VT, A, B, C);
7078   }
7079 
7080   assert(GlueChain->getNumValues() == 3);
7081 
7082   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7083   switch (Opcode) {
7084   default: llvm_unreachable("no chain equivalent for opcode");
7085   case ISD::FMA:
7086     Opcode = AMDGPUISD::FMA_W_CHAIN;
7087     break;
7088   }
7089 
7090   return DAG.getNode(Opcode, SL, VTList, GlueChain.getValue(1), A, B, C,
7091                      GlueChain.getValue(2));
7092 }
7093 
7094 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7095   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7096     return FastLowered;
7097 
7098   SDLoc SL(Op);
7099   SDValue Src0 = Op.getOperand(0);
7100   SDValue Src1 = Op.getOperand(1);
7101 
7102   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
7103   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
7104 
7105   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
7106   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
7107 
7108   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
7109   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
7110 
7111   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
7112 }
7113 
7114 // Faster 2.5 ULP division that does not support denormals.
7115 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
7116   SDLoc SL(Op);
7117   SDValue LHS = Op.getOperand(1);
7118   SDValue RHS = Op.getOperand(2);
7119 
7120   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
7121 
7122   const APFloat K0Val(BitsToFloat(0x6f800000));
7123   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
7124 
7125   const APFloat K1Val(BitsToFloat(0x2f800000));
7126   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
7127 
7128   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7129 
7130   EVT SetCCVT =
7131     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
7132 
7133   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
7134 
7135   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
7136 
7137   // TODO: Should this propagate fast-math-flags?
7138   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
7139 
7140   // rcp does not support denormals.
7141   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
7142 
7143   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
7144 
7145   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
7146 }
7147 
7148 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
7149   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7150     return FastLowered;
7151 
7152   SDLoc SL(Op);
7153   SDValue LHS = Op.getOperand(0);
7154   SDValue RHS = Op.getOperand(1);
7155 
7156   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
7157 
7158   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
7159 
7160   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7161                                           RHS, RHS, LHS);
7162   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
7163                                         LHS, RHS, LHS);
7164 
7165   // Denominator is scaled to not be denormal, so using rcp is ok.
7166   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
7167                                   DenominatorScaled);
7168   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
7169                                      DenominatorScaled);
7170 
7171   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
7172                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
7173                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
7174 
7175   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i16);
7176 
7177   if (!Subtarget->hasFP32Denormals()) {
7178     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
7179     const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
7180                                                       SL, MVT::i32);
7181     SDValue EnableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, BindParamVTs,
7182                                        DAG.getEntryNode(),
7183                                        EnableDenormValue, BitField);
7184     SDValue Ops[3] = {
7185       NegDivScale0,
7186       EnableDenorm.getValue(0),
7187       EnableDenorm.getValue(1)
7188     };
7189 
7190     NegDivScale0 = DAG.getMergeValues(Ops, SL);
7191   }
7192 
7193   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
7194                              ApproxRcp, One, NegDivScale0);
7195 
7196   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
7197                              ApproxRcp, Fma0);
7198 
7199   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
7200                            Fma1, Fma1);
7201 
7202   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
7203                              NumeratorScaled, Mul);
7204 
7205   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA,SL, MVT::f32, Fma2, Fma1, Mul, Fma2);
7206 
7207   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
7208                              NumeratorScaled, Fma3);
7209 
7210   if (!Subtarget->hasFP32Denormals()) {
7211     const SDValue DisableDenormValue =
7212         DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
7213     SDValue DisableDenorm = DAG.getNode(AMDGPUISD::SETREG, SL, MVT::Other,
7214                                         Fma4.getValue(1),
7215                                         DisableDenormValue,
7216                                         BitField,
7217                                         Fma4.getValue(2));
7218 
7219     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
7220                                       DisableDenorm, DAG.getRoot());
7221     DAG.setRoot(OutputChain);
7222   }
7223 
7224   SDValue Scale = NumeratorScaled.getValue(1);
7225   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
7226                              Fma4, Fma1, Fma3, Scale);
7227 
7228   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS);
7229 }
7230 
7231 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
7232   if (DAG.getTarget().Options.UnsafeFPMath)
7233     return lowerFastUnsafeFDIV(Op, DAG);
7234 
7235   SDLoc SL(Op);
7236   SDValue X = Op.getOperand(0);
7237   SDValue Y = Op.getOperand(1);
7238 
7239   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
7240 
7241   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
7242 
7243   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
7244 
7245   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
7246 
7247   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
7248 
7249   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
7250 
7251   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
7252 
7253   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
7254 
7255   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
7256 
7257   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
7258   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
7259 
7260   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
7261                              NegDivScale0, Mul, DivScale1);
7262 
7263   SDValue Scale;
7264 
7265   if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
7266     // Workaround a hardware bug on SI where the condition output from div_scale
7267     // is not usable.
7268 
7269     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
7270 
7271     // Figure out if the scale to use for div_fmas.
7272     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
7273     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
7274     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
7275     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
7276 
7277     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
7278     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
7279 
7280     SDValue Scale0Hi
7281       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
7282     SDValue Scale1Hi
7283       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
7284 
7285     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
7286     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
7287     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
7288   } else {
7289     Scale = DivScale1.getValue(1);
7290   }
7291 
7292   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
7293                              Fma4, Fma3, Mul, Scale);
7294 
7295   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
7296 }
7297 
7298 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
7299   EVT VT = Op.getValueType();
7300 
7301   if (VT == MVT::f32)
7302     return LowerFDIV32(Op, DAG);
7303 
7304   if (VT == MVT::f64)
7305     return LowerFDIV64(Op, DAG);
7306 
7307   if (VT == MVT::f16)
7308     return LowerFDIV16(Op, DAG);
7309 
7310   llvm_unreachable("Unexpected type for fdiv");
7311 }
7312 
7313 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
7314   SDLoc DL(Op);
7315   StoreSDNode *Store = cast<StoreSDNode>(Op);
7316   EVT VT = Store->getMemoryVT();
7317 
7318   if (VT == MVT::i1) {
7319     return DAG.getTruncStore(Store->getChain(), DL,
7320        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
7321        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
7322   }
7323 
7324   assert(VT.isVector() &&
7325          Store->getValue().getValueType().getScalarType() == MVT::i32);
7326 
7327   if (!allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
7328                           *Store->getMemOperand())) {
7329     return expandUnalignedStore(Store, DAG);
7330   }
7331 
7332   unsigned AS = Store->getAddressSpace();
7333   if (Subtarget->hasLDSMisalignedBug() &&
7334       AS == AMDGPUAS::FLAT_ADDRESS &&
7335       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
7336     return SplitVectorStore(Op, DAG);
7337   }
7338 
7339   MachineFunction &MF = DAG.getMachineFunction();
7340   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7341   // If there is a possibilty that flat instruction access scratch memory
7342   // then we need to use the same legalization rules we use for private.
7343   if (AS == AMDGPUAS::FLAT_ADDRESS)
7344     AS = MFI->hasFlatScratchInit() ?
7345          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7346 
7347   unsigned NumElements = VT.getVectorNumElements();
7348   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
7349       AS == AMDGPUAS::FLAT_ADDRESS) {
7350     if (NumElements > 4)
7351       return SplitVectorStore(Op, DAG);
7352     // v3 stores not supported on SI.
7353     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7354       return SplitVectorStore(Op, DAG);
7355     return SDValue();
7356   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7357     switch (Subtarget->getMaxPrivateElementSize()) {
7358     case 4:
7359       return scalarizeVectorStore(Store, DAG);
7360     case 8:
7361       if (NumElements > 2)
7362         return SplitVectorStore(Op, DAG);
7363       return SDValue();
7364     case 16:
7365       if (NumElements > 4 || NumElements == 3)
7366         return SplitVectorStore(Op, DAG);
7367       return SDValue();
7368     default:
7369       llvm_unreachable("unsupported private_element_size");
7370     }
7371   } else if (AS == AMDGPUAS::LOCAL_ADDRESS) {
7372     // Use ds_write_b128 if possible.
7373     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
7374         VT.getStoreSize() == 16 && NumElements != 3)
7375       return SDValue();
7376 
7377     if (NumElements > 2)
7378       return SplitVectorStore(Op, DAG);
7379 
7380     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7381     // address is negative, then the instruction is incorrectly treated as
7382     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7383     // stores here to avoid emitting ds_write2_b32. We may re-combine the
7384     // store later in the SILoadStoreOptimizer.
7385     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7386         NumElements == 2 && VT.getStoreSize() == 8 &&
7387         Store->getAlignment() < 8) {
7388       return SplitVectorStore(Op, DAG);
7389     }
7390 
7391     return SDValue();
7392   } else {
7393     llvm_unreachable("unhandled address space");
7394   }
7395 }
7396 
7397 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
7398   SDLoc DL(Op);
7399   EVT VT = Op.getValueType();
7400   SDValue Arg = Op.getOperand(0);
7401   SDValue TrigVal;
7402 
7403   // TODO: Should this propagate fast-math-flags?
7404 
7405   SDValue OneOver2Pi = DAG.getConstantFP(0.5 / M_PI, DL, VT);
7406 
7407   if (Subtarget->hasTrigReducedRange()) {
7408     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7409     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal);
7410   } else {
7411     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi);
7412   }
7413 
7414   switch (Op.getOpcode()) {
7415   case ISD::FCOS:
7416     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal);
7417   case ISD::FSIN:
7418     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal);
7419   default:
7420     llvm_unreachable("Wrong trig opcode");
7421   }
7422 }
7423 
7424 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
7425   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
7426   assert(AtomicNode->isCompareAndSwap());
7427   unsigned AS = AtomicNode->getAddressSpace();
7428 
7429   // No custom lowering required for local address space
7430   if (!isFlatGlobalAddrSpace(AS))
7431     return Op;
7432 
7433   // Non-local address space requires custom lowering for atomic compare
7434   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
7435   SDLoc DL(Op);
7436   SDValue ChainIn = Op.getOperand(0);
7437   SDValue Addr = Op.getOperand(1);
7438   SDValue Old = Op.getOperand(2);
7439   SDValue New = Op.getOperand(3);
7440   EVT VT = Op.getValueType();
7441   MVT SimpleVT = VT.getSimpleVT();
7442   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
7443 
7444   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
7445   SDValue Ops[] = { ChainIn, Addr, NewOld };
7446 
7447   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
7448                                  Ops, VT, AtomicNode->getMemOperand());
7449 }
7450 
7451 //===----------------------------------------------------------------------===//
7452 // Custom DAG optimizations
7453 //===----------------------------------------------------------------------===//
7454 
7455 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
7456                                                      DAGCombinerInfo &DCI) const {
7457   EVT VT = N->getValueType(0);
7458   EVT ScalarVT = VT.getScalarType();
7459   if (ScalarVT != MVT::f32)
7460     return SDValue();
7461 
7462   SelectionDAG &DAG = DCI.DAG;
7463   SDLoc DL(N);
7464 
7465   SDValue Src = N->getOperand(0);
7466   EVT SrcVT = Src.getValueType();
7467 
7468   // TODO: We could try to match extracting the higher bytes, which would be
7469   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
7470   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
7471   // about in practice.
7472   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
7473     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
7474       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, VT, Src);
7475       DCI.AddToWorklist(Cvt.getNode());
7476       return Cvt;
7477     }
7478   }
7479 
7480   return SDValue();
7481 }
7482 
7483 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
7484 
7485 // This is a variant of
7486 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
7487 //
7488 // The normal DAG combiner will do this, but only if the add has one use since
7489 // that would increase the number of instructions.
7490 //
7491 // This prevents us from seeing a constant offset that can be folded into a
7492 // memory instruction's addressing mode. If we know the resulting add offset of
7493 // a pointer can be folded into an addressing offset, we can replace the pointer
7494 // operand with the add of new constant offset. This eliminates one of the uses,
7495 // and may allow the remaining use to also be simplified.
7496 //
7497 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
7498                                                unsigned AddrSpace,
7499                                                EVT MemVT,
7500                                                DAGCombinerInfo &DCI) const {
7501   SDValue N0 = N->getOperand(0);
7502   SDValue N1 = N->getOperand(1);
7503 
7504   // We only do this to handle cases where it's profitable when there are
7505   // multiple uses of the add, so defer to the standard combine.
7506   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
7507       N0->hasOneUse())
7508     return SDValue();
7509 
7510   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
7511   if (!CN1)
7512     return SDValue();
7513 
7514   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
7515   if (!CAdd)
7516     return SDValue();
7517 
7518   // If the resulting offset is too large, we can't fold it into the addressing
7519   // mode offset.
7520   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
7521   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
7522 
7523   AddrMode AM;
7524   AM.HasBaseReg = true;
7525   AM.BaseOffs = Offset.getSExtValue();
7526   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
7527     return SDValue();
7528 
7529   SelectionDAG &DAG = DCI.DAG;
7530   SDLoc SL(N);
7531   EVT VT = N->getValueType(0);
7532 
7533   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
7534   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
7535 
7536   SDNodeFlags Flags;
7537   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
7538                           (N0.getOpcode() == ISD::OR ||
7539                            N0->getFlags().hasNoUnsignedWrap()));
7540 
7541   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
7542 }
7543 
7544 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
7545                                                   DAGCombinerInfo &DCI) const {
7546   SDValue Ptr = N->getBasePtr();
7547   SelectionDAG &DAG = DCI.DAG;
7548   SDLoc SL(N);
7549 
7550   // TODO: We could also do this for multiplies.
7551   if (Ptr.getOpcode() == ISD::SHL) {
7552     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
7553                                           N->getMemoryVT(), DCI);
7554     if (NewPtr) {
7555       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
7556 
7557       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
7558       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
7559     }
7560   }
7561 
7562   return SDValue();
7563 }
7564 
7565 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
7566   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
7567          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
7568          (Opc == ISD::XOR && Val == 0);
7569 }
7570 
7571 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
7572 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
7573 // integer combine opportunities since most 64-bit operations are decomposed
7574 // this way.  TODO: We won't want this for SALU especially if it is an inline
7575 // immediate.
7576 SDValue SITargetLowering::splitBinaryBitConstantOp(
7577   DAGCombinerInfo &DCI,
7578   const SDLoc &SL,
7579   unsigned Opc, SDValue LHS,
7580   const ConstantSDNode *CRHS) const {
7581   uint64_t Val = CRHS->getZExtValue();
7582   uint32_t ValLo = Lo_32(Val);
7583   uint32_t ValHi = Hi_32(Val);
7584   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7585 
7586     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
7587          bitOpWithConstantIsReducible(Opc, ValHi)) ||
7588         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
7589     // If we need to materialize a 64-bit immediate, it will be split up later
7590     // anyway. Avoid creating the harder to understand 64-bit immediate
7591     // materialization.
7592     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
7593   }
7594 
7595   return SDValue();
7596 }
7597 
7598 // Returns true if argument is a boolean value which is not serialized into
7599 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
7600 static bool isBoolSGPR(SDValue V) {
7601   if (V.getValueType() != MVT::i1)
7602     return false;
7603   switch (V.getOpcode()) {
7604   default: break;
7605   case ISD::SETCC:
7606   case ISD::AND:
7607   case ISD::OR:
7608   case ISD::XOR:
7609   case AMDGPUISD::FP_CLASS:
7610     return true;
7611   }
7612   return false;
7613 }
7614 
7615 // If a constant has all zeroes or all ones within each byte return it.
7616 // Otherwise return 0.
7617 static uint32_t getConstantPermuteMask(uint32_t C) {
7618   // 0xff for any zero byte in the mask
7619   uint32_t ZeroByteMask = 0;
7620   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
7621   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
7622   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
7623   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
7624   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
7625   if ((NonZeroByteMask & C) != NonZeroByteMask)
7626     return 0; // Partial bytes selected.
7627   return C;
7628 }
7629 
7630 // Check if a node selects whole bytes from its operand 0 starting at a byte
7631 // boundary while masking the rest. Returns select mask as in the v_perm_b32
7632 // or -1 if not succeeded.
7633 // Note byte select encoding:
7634 // value 0-3 selects corresponding source byte;
7635 // value 0xc selects zero;
7636 // value 0xff selects 0xff.
7637 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
7638   assert(V.getValueSizeInBits() == 32);
7639 
7640   if (V.getNumOperands() != 2)
7641     return ~0;
7642 
7643   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
7644   if (!N1)
7645     return ~0;
7646 
7647   uint32_t C = N1->getZExtValue();
7648 
7649   switch (V.getOpcode()) {
7650   default:
7651     break;
7652   case ISD::AND:
7653     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
7654       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
7655     }
7656     break;
7657 
7658   case ISD::OR:
7659     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
7660       return (0x03020100 & ~ConstMask) | ConstMask;
7661     }
7662     break;
7663 
7664   case ISD::SHL:
7665     if (C % 8)
7666       return ~0;
7667 
7668     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
7669 
7670   case ISD::SRL:
7671     if (C % 8)
7672       return ~0;
7673 
7674     return uint32_t(0x0c0c0c0c03020100ull >> C);
7675   }
7676 
7677   return ~0;
7678 }
7679 
7680 SDValue SITargetLowering::performAndCombine(SDNode *N,
7681                                             DAGCombinerInfo &DCI) const {
7682   if (DCI.isBeforeLegalize())
7683     return SDValue();
7684 
7685   SelectionDAG &DAG = DCI.DAG;
7686   EVT VT = N->getValueType(0);
7687   SDValue LHS = N->getOperand(0);
7688   SDValue RHS = N->getOperand(1);
7689 
7690 
7691   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
7692   if (VT == MVT::i64 && CRHS) {
7693     if (SDValue Split
7694         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
7695       return Split;
7696   }
7697 
7698   if (CRHS && VT == MVT::i32) {
7699     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
7700     // nb = number of trailing zeroes in mask
7701     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
7702     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
7703     uint64_t Mask = CRHS->getZExtValue();
7704     unsigned Bits = countPopulation(Mask);
7705     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
7706         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
7707       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
7708         unsigned Shift = CShift->getZExtValue();
7709         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
7710         unsigned Offset = NB + Shift;
7711         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
7712           SDLoc SL(N);
7713           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
7714                                     LHS->getOperand(0),
7715                                     DAG.getConstant(Offset, SL, MVT::i32),
7716                                     DAG.getConstant(Bits, SL, MVT::i32));
7717           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
7718           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
7719                                     DAG.getValueType(NarrowVT));
7720           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
7721                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
7722           return Shl;
7723         }
7724       }
7725     }
7726 
7727     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
7728     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
7729         isa<ConstantSDNode>(LHS.getOperand(2))) {
7730       uint32_t Sel = getConstantPermuteMask(Mask);
7731       if (!Sel)
7732         return SDValue();
7733 
7734       // Select 0xc for all zero bytes
7735       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
7736       SDLoc DL(N);
7737       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
7738                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
7739     }
7740   }
7741 
7742   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
7743   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
7744   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
7745     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7746     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
7747 
7748     SDValue X = LHS.getOperand(0);
7749     SDValue Y = RHS.getOperand(0);
7750     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
7751       return SDValue();
7752 
7753     if (LCC == ISD::SETO) {
7754       if (X != LHS.getOperand(1))
7755         return SDValue();
7756 
7757       if (RCC == ISD::SETUNE) {
7758         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
7759         if (!C1 || !C1->isInfinity() || C1->isNegative())
7760           return SDValue();
7761 
7762         const uint32_t Mask = SIInstrFlags::N_NORMAL |
7763                               SIInstrFlags::N_SUBNORMAL |
7764                               SIInstrFlags::N_ZERO |
7765                               SIInstrFlags::P_ZERO |
7766                               SIInstrFlags::P_SUBNORMAL |
7767                               SIInstrFlags::P_NORMAL;
7768 
7769         static_assert(((~(SIInstrFlags::S_NAN |
7770                           SIInstrFlags::Q_NAN |
7771                           SIInstrFlags::N_INFINITY |
7772                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
7773                       "mask not equal");
7774 
7775         SDLoc DL(N);
7776         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
7777                            X, DAG.getConstant(Mask, DL, MVT::i32));
7778       }
7779     }
7780   }
7781 
7782   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
7783     std::swap(LHS, RHS);
7784 
7785   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
7786       RHS.hasOneUse()) {
7787     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
7788     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
7789     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
7790     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
7791     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
7792         (RHS.getOperand(0) == LHS.getOperand(0) &&
7793          LHS.getOperand(0) == LHS.getOperand(1))) {
7794       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
7795       unsigned NewMask = LCC == ISD::SETO ?
7796         Mask->getZExtValue() & ~OrdMask :
7797         Mask->getZExtValue() & OrdMask;
7798 
7799       SDLoc DL(N);
7800       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
7801                          DAG.getConstant(NewMask, DL, MVT::i32));
7802     }
7803   }
7804 
7805   if (VT == MVT::i32 &&
7806       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
7807     // and x, (sext cc from i1) => select cc, x, 0
7808     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
7809       std::swap(LHS, RHS);
7810     if (isBoolSGPR(RHS.getOperand(0)))
7811       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
7812                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
7813   }
7814 
7815   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
7816   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7817   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
7818       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
7819     uint32_t LHSMask = getPermuteMask(DAG, LHS);
7820     uint32_t RHSMask = getPermuteMask(DAG, RHS);
7821     if (LHSMask != ~0u && RHSMask != ~0u) {
7822       // Canonicalize the expression in an attempt to have fewer unique masks
7823       // and therefore fewer registers used to hold the masks.
7824       if (LHSMask > RHSMask) {
7825         std::swap(LHSMask, RHSMask);
7826         std::swap(LHS, RHS);
7827       }
7828 
7829       // Select 0xc for each lane used from source operand. Zero has 0xc mask
7830       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
7831       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7832       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7833 
7834       // Check of we need to combine values from two sources within a byte.
7835       if (!(LHSUsedLanes & RHSUsedLanes) &&
7836           // If we select high and lower word keep it for SDWA.
7837           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
7838           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
7839         // Each byte in each mask is either selector mask 0-3, or has higher
7840         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
7841         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
7842         // mask which is not 0xff wins. By anding both masks we have a correct
7843         // result except that 0x0c shall be corrected to give 0x0c only.
7844         uint32_t Mask = LHSMask & RHSMask;
7845         for (unsigned I = 0; I < 32; I += 8) {
7846           uint32_t ByteSel = 0xff << I;
7847           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
7848             Mask &= (0x0c << I) & 0xffffffff;
7849         }
7850 
7851         // Add 4 to each active LHS lane. It will not affect any existing 0xff
7852         // or 0x0c.
7853         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
7854         SDLoc DL(N);
7855 
7856         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
7857                            LHS.getOperand(0), RHS.getOperand(0),
7858                            DAG.getConstant(Sel, DL, MVT::i32));
7859       }
7860     }
7861   }
7862 
7863   return SDValue();
7864 }
7865 
7866 SDValue SITargetLowering::performOrCombine(SDNode *N,
7867                                            DAGCombinerInfo &DCI) const {
7868   SelectionDAG &DAG = DCI.DAG;
7869   SDValue LHS = N->getOperand(0);
7870   SDValue RHS = N->getOperand(1);
7871 
7872   EVT VT = N->getValueType(0);
7873   if (VT == MVT::i1) {
7874     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
7875     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
7876         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
7877       SDValue Src = LHS.getOperand(0);
7878       if (Src != RHS.getOperand(0))
7879         return SDValue();
7880 
7881       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
7882       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
7883       if (!CLHS || !CRHS)
7884         return SDValue();
7885 
7886       // Only 10 bits are used.
7887       static const uint32_t MaxMask = 0x3ff;
7888 
7889       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
7890       SDLoc DL(N);
7891       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
7892                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
7893     }
7894 
7895     return SDValue();
7896   }
7897 
7898   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
7899   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
7900       LHS.getOpcode() == AMDGPUISD::PERM &&
7901       isa<ConstantSDNode>(LHS.getOperand(2))) {
7902     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
7903     if (!Sel)
7904       return SDValue();
7905 
7906     Sel |= LHS.getConstantOperandVal(2);
7907     SDLoc DL(N);
7908     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
7909                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
7910   }
7911 
7912   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
7913   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
7914   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
7915       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
7916     uint32_t LHSMask = getPermuteMask(DAG, LHS);
7917     uint32_t RHSMask = getPermuteMask(DAG, RHS);
7918     if (LHSMask != ~0u && RHSMask != ~0u) {
7919       // Canonicalize the expression in an attempt to have fewer unique masks
7920       // and therefore fewer registers used to hold the masks.
7921       if (LHSMask > RHSMask) {
7922         std::swap(LHSMask, RHSMask);
7923         std::swap(LHS, RHS);
7924       }
7925 
7926       // Select 0xc for each lane used from source operand. Zero has 0xc mask
7927       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
7928       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7929       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
7930 
7931       // Check of we need to combine values from two sources within a byte.
7932       if (!(LHSUsedLanes & RHSUsedLanes) &&
7933           // If we select high and lower word keep it for SDWA.
7934           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
7935           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
7936         // Kill zero bytes selected by other mask. Zero value is 0xc.
7937         LHSMask &= ~RHSUsedLanes;
7938         RHSMask &= ~LHSUsedLanes;
7939         // Add 4 to each active LHS lane
7940         LHSMask |= LHSUsedLanes & 0x04040404;
7941         // Combine masks
7942         uint32_t Sel = LHSMask | RHSMask;
7943         SDLoc DL(N);
7944 
7945         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
7946                            LHS.getOperand(0), RHS.getOperand(0),
7947                            DAG.getConstant(Sel, DL, MVT::i32));
7948       }
7949     }
7950   }
7951 
7952   if (VT != MVT::i64)
7953     return SDValue();
7954 
7955   // TODO: This could be a generic combine with a predicate for extracting the
7956   // high half of an integer being free.
7957 
7958   // (or i64:x, (zero_extend i32:y)) ->
7959   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
7960   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
7961       RHS.getOpcode() != ISD::ZERO_EXTEND)
7962     std::swap(LHS, RHS);
7963 
7964   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
7965     SDValue ExtSrc = RHS.getOperand(0);
7966     EVT SrcVT = ExtSrc.getValueType();
7967     if (SrcVT == MVT::i32) {
7968       SDLoc SL(N);
7969       SDValue LowLHS, HiBits;
7970       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
7971       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
7972 
7973       DCI.AddToWorklist(LowOr.getNode());
7974       DCI.AddToWorklist(HiBits.getNode());
7975 
7976       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
7977                                 LowOr, HiBits);
7978       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
7979     }
7980   }
7981 
7982   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
7983   if (CRHS) {
7984     if (SDValue Split
7985           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
7986       return Split;
7987   }
7988 
7989   return SDValue();
7990 }
7991 
7992 SDValue SITargetLowering::performXorCombine(SDNode *N,
7993                                             DAGCombinerInfo &DCI) const {
7994   EVT VT = N->getValueType(0);
7995   if (VT != MVT::i64)
7996     return SDValue();
7997 
7998   SDValue LHS = N->getOperand(0);
7999   SDValue RHS = N->getOperand(1);
8000 
8001   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8002   if (CRHS) {
8003     if (SDValue Split
8004           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8005       return Split;
8006   }
8007 
8008   return SDValue();
8009 }
8010 
8011 // Instructions that will be lowered with a final instruction that zeros the
8012 // high result bits.
8013 // XXX - probably only need to list legal operations.
8014 static bool fp16SrcZerosHighBits(unsigned Opc) {
8015   switch (Opc) {
8016   case ISD::FADD:
8017   case ISD::FSUB:
8018   case ISD::FMUL:
8019   case ISD::FDIV:
8020   case ISD::FREM:
8021   case ISD::FMA:
8022   case ISD::FMAD:
8023   case ISD::FCANONICALIZE:
8024   case ISD::FP_ROUND:
8025   case ISD::UINT_TO_FP:
8026   case ISD::SINT_TO_FP:
8027   case ISD::FABS:
8028     // Fabs is lowered to a bit operation, but it's an and which will clear the
8029     // high bits anyway.
8030   case ISD::FSQRT:
8031   case ISD::FSIN:
8032   case ISD::FCOS:
8033   case ISD::FPOWI:
8034   case ISD::FPOW:
8035   case ISD::FLOG:
8036   case ISD::FLOG2:
8037   case ISD::FLOG10:
8038   case ISD::FEXP:
8039   case ISD::FEXP2:
8040   case ISD::FCEIL:
8041   case ISD::FTRUNC:
8042   case ISD::FRINT:
8043   case ISD::FNEARBYINT:
8044   case ISD::FROUND:
8045   case ISD::FFLOOR:
8046   case ISD::FMINNUM:
8047   case ISD::FMAXNUM:
8048   case AMDGPUISD::FRACT:
8049   case AMDGPUISD::CLAMP:
8050   case AMDGPUISD::COS_HW:
8051   case AMDGPUISD::SIN_HW:
8052   case AMDGPUISD::FMIN3:
8053   case AMDGPUISD::FMAX3:
8054   case AMDGPUISD::FMED3:
8055   case AMDGPUISD::FMAD_FTZ:
8056   case AMDGPUISD::RCP:
8057   case AMDGPUISD::RSQ:
8058   case AMDGPUISD::RCP_IFLAG:
8059   case AMDGPUISD::LDEXP:
8060     return true;
8061   default:
8062     // fcopysign, select and others may be lowered to 32-bit bit operations
8063     // which don't zero the high bits.
8064     return false;
8065   }
8066 }
8067 
8068 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
8069                                                    DAGCombinerInfo &DCI) const {
8070   if (!Subtarget->has16BitInsts() ||
8071       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
8072     return SDValue();
8073 
8074   EVT VT = N->getValueType(0);
8075   if (VT != MVT::i32)
8076     return SDValue();
8077 
8078   SDValue Src = N->getOperand(0);
8079   if (Src.getValueType() != MVT::i16)
8080     return SDValue();
8081 
8082   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
8083   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
8084   if (Src.getOpcode() == ISD::BITCAST) {
8085     SDValue BCSrc = Src.getOperand(0);
8086     if (BCSrc.getValueType() == MVT::f16 &&
8087         fp16SrcZerosHighBits(BCSrc.getOpcode()))
8088       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
8089   }
8090 
8091   return SDValue();
8092 }
8093 
8094 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
8095                                                         DAGCombinerInfo &DCI)
8096                                                         const {
8097   SDValue Src = N->getOperand(0);
8098   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
8099 
8100   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
8101       VTSign->getVT() == MVT::i8) ||
8102       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
8103       VTSign->getVT() == MVT::i16)) &&
8104       Src.hasOneUse()) {
8105     auto *M = cast<MemSDNode>(Src);
8106     SDValue Ops[] = {
8107       Src.getOperand(0), // Chain
8108       Src.getOperand(1), // rsrc
8109       Src.getOperand(2), // vindex
8110       Src.getOperand(3), // voffset
8111       Src.getOperand(4), // soffset
8112       Src.getOperand(5), // offset
8113       Src.getOperand(6),
8114       Src.getOperand(7)
8115     };
8116     // replace with BUFFER_LOAD_BYTE/SHORT
8117     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
8118                                          Src.getOperand(0).getValueType());
8119     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
8120                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
8121     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
8122                                                           ResList,
8123                                                           Ops, M->getMemoryVT(),
8124                                                           M->getMemOperand());
8125     return DCI.DAG.getMergeValues({BufferLoadSignExt,
8126                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
8127   }
8128   return SDValue();
8129 }
8130 
8131 SDValue SITargetLowering::performClassCombine(SDNode *N,
8132                                               DAGCombinerInfo &DCI) const {
8133   SelectionDAG &DAG = DCI.DAG;
8134   SDValue Mask = N->getOperand(1);
8135 
8136   // fp_class x, 0 -> false
8137   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
8138     if (CMask->isNullValue())
8139       return DAG.getConstant(0, SDLoc(N), MVT::i1);
8140   }
8141 
8142   if (N->getOperand(0).isUndef())
8143     return DAG.getUNDEF(MVT::i1);
8144 
8145   return SDValue();
8146 }
8147 
8148 SDValue SITargetLowering::performRcpCombine(SDNode *N,
8149                                             DAGCombinerInfo &DCI) const {
8150   EVT VT = N->getValueType(0);
8151   SDValue N0 = N->getOperand(0);
8152 
8153   if (N0.isUndef())
8154     return N0;
8155 
8156   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
8157                          N0.getOpcode() == ISD::SINT_TO_FP)) {
8158     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
8159                            N->getFlags());
8160   }
8161 
8162   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
8163 }
8164 
8165 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
8166                                        unsigned MaxDepth) const {
8167   unsigned Opcode = Op.getOpcode();
8168   if (Opcode == ISD::FCANONICALIZE)
8169     return true;
8170 
8171   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8172     auto F = CFP->getValueAPF();
8173     if (F.isNaN() && F.isSignaling())
8174       return false;
8175     return !F.isDenormal() || denormalsEnabledForType(Op.getValueType());
8176   }
8177 
8178   // If source is a result of another standard FP operation it is already in
8179   // canonical form.
8180   if (MaxDepth == 0)
8181     return false;
8182 
8183   switch (Opcode) {
8184   // These will flush denorms if required.
8185   case ISD::FADD:
8186   case ISD::FSUB:
8187   case ISD::FMUL:
8188   case ISD::FCEIL:
8189   case ISD::FFLOOR:
8190   case ISD::FMA:
8191   case ISD::FMAD:
8192   case ISD::FSQRT:
8193   case ISD::FDIV:
8194   case ISD::FREM:
8195   case ISD::FP_ROUND:
8196   case ISD::FP_EXTEND:
8197   case AMDGPUISD::FMUL_LEGACY:
8198   case AMDGPUISD::FMAD_FTZ:
8199   case AMDGPUISD::RCP:
8200   case AMDGPUISD::RSQ:
8201   case AMDGPUISD::RSQ_CLAMP:
8202   case AMDGPUISD::RCP_LEGACY:
8203   case AMDGPUISD::RSQ_LEGACY:
8204   case AMDGPUISD::RCP_IFLAG:
8205   case AMDGPUISD::TRIG_PREOP:
8206   case AMDGPUISD::DIV_SCALE:
8207   case AMDGPUISD::DIV_FMAS:
8208   case AMDGPUISD::DIV_FIXUP:
8209   case AMDGPUISD::FRACT:
8210   case AMDGPUISD::LDEXP:
8211   case AMDGPUISD::CVT_PKRTZ_F16_F32:
8212   case AMDGPUISD::CVT_F32_UBYTE0:
8213   case AMDGPUISD::CVT_F32_UBYTE1:
8214   case AMDGPUISD::CVT_F32_UBYTE2:
8215   case AMDGPUISD::CVT_F32_UBYTE3:
8216     return true;
8217 
8218   // It can/will be lowered or combined as a bit operation.
8219   // Need to check their input recursively to handle.
8220   case ISD::FNEG:
8221   case ISD::FABS:
8222   case ISD::FCOPYSIGN:
8223     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8224 
8225   case ISD::FSIN:
8226   case ISD::FCOS:
8227   case ISD::FSINCOS:
8228     return Op.getValueType().getScalarType() != MVT::f16;
8229 
8230   case ISD::FMINNUM:
8231   case ISD::FMAXNUM:
8232   case ISD::FMINNUM_IEEE:
8233   case ISD::FMAXNUM_IEEE:
8234   case AMDGPUISD::CLAMP:
8235   case AMDGPUISD::FMED3:
8236   case AMDGPUISD::FMAX3:
8237   case AMDGPUISD::FMIN3: {
8238     // FIXME: Shouldn't treat the generic operations different based these.
8239     // However, we aren't really required to flush the result from
8240     // minnum/maxnum..
8241 
8242     // snans will be quieted, so we only need to worry about denormals.
8243     if (Subtarget->supportsMinMaxDenormModes() ||
8244         denormalsEnabledForType(Op.getValueType()))
8245       return true;
8246 
8247     // Flushing may be required.
8248     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
8249     // targets need to check their input recursively.
8250 
8251     // FIXME: Does this apply with clamp? It's implemented with max.
8252     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
8253       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
8254         return false;
8255     }
8256 
8257     return true;
8258   }
8259   case ISD::SELECT: {
8260     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
8261            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
8262   }
8263   case ISD::BUILD_VECTOR: {
8264     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
8265       SDValue SrcOp = Op.getOperand(i);
8266       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
8267         return false;
8268     }
8269 
8270     return true;
8271   }
8272   case ISD::EXTRACT_VECTOR_ELT:
8273   case ISD::EXTRACT_SUBVECTOR: {
8274     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
8275   }
8276   case ISD::INSERT_VECTOR_ELT: {
8277     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
8278            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
8279   }
8280   case ISD::UNDEF:
8281     // Could be anything.
8282     return false;
8283 
8284   case ISD::BITCAST: {
8285     // Hack round the mess we make when legalizing extract_vector_elt
8286     SDValue Src = Op.getOperand(0);
8287     if (Src.getValueType() == MVT::i16 &&
8288         Src.getOpcode() == ISD::TRUNCATE) {
8289       SDValue TruncSrc = Src.getOperand(0);
8290       if (TruncSrc.getValueType() == MVT::i32 &&
8291           TruncSrc.getOpcode() == ISD::BITCAST &&
8292           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
8293         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
8294       }
8295     }
8296 
8297     return false;
8298   }
8299   case ISD::INTRINSIC_WO_CHAIN: {
8300     unsigned IntrinsicID
8301       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
8302     // TODO: Handle more intrinsics
8303     switch (IntrinsicID) {
8304     case Intrinsic::amdgcn_cvt_pkrtz:
8305     case Intrinsic::amdgcn_cubeid:
8306     case Intrinsic::amdgcn_frexp_mant:
8307     case Intrinsic::amdgcn_fdot2:
8308       return true;
8309     default:
8310       break;
8311     }
8312 
8313     LLVM_FALLTHROUGH;
8314   }
8315   default:
8316     return denormalsEnabledForType(Op.getValueType()) &&
8317            DAG.isKnownNeverSNaN(Op);
8318   }
8319 
8320   llvm_unreachable("invalid operation");
8321 }
8322 
8323 // Constant fold canonicalize.
8324 SDValue SITargetLowering::getCanonicalConstantFP(
8325   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
8326   // Flush denormals to 0 if not enabled.
8327   if (C.isDenormal() && !denormalsEnabledForType(VT))
8328     return DAG.getConstantFP(0.0, SL, VT);
8329 
8330   if (C.isNaN()) {
8331     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
8332     if (C.isSignaling()) {
8333       // Quiet a signaling NaN.
8334       // FIXME: Is this supposed to preserve payload bits?
8335       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8336     }
8337 
8338     // Make sure it is the canonical NaN bitpattern.
8339     //
8340     // TODO: Can we use -1 as the canonical NaN value since it's an inline
8341     // immediate?
8342     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
8343       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
8344   }
8345 
8346   // Already canonical.
8347   return DAG.getConstantFP(C, SL, VT);
8348 }
8349 
8350 static bool vectorEltWillFoldAway(SDValue Op) {
8351   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
8352 }
8353 
8354 SDValue SITargetLowering::performFCanonicalizeCombine(
8355   SDNode *N,
8356   DAGCombinerInfo &DCI) const {
8357   SelectionDAG &DAG = DCI.DAG;
8358   SDValue N0 = N->getOperand(0);
8359   EVT VT = N->getValueType(0);
8360 
8361   // fcanonicalize undef -> qnan
8362   if (N0.isUndef()) {
8363     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
8364     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
8365   }
8366 
8367   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
8368     EVT VT = N->getValueType(0);
8369     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
8370   }
8371 
8372   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
8373   //                                                   (fcanonicalize k)
8374   //
8375   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
8376 
8377   // TODO: This could be better with wider vectors that will be split to v2f16,
8378   // and to consider uses since there aren't that many packed operations.
8379   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
8380       isTypeLegal(MVT::v2f16)) {
8381     SDLoc SL(N);
8382     SDValue NewElts[2];
8383     SDValue Lo = N0.getOperand(0);
8384     SDValue Hi = N0.getOperand(1);
8385     EVT EltVT = Lo.getValueType();
8386 
8387     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
8388       for (unsigned I = 0; I != 2; ++I) {
8389         SDValue Op = N0.getOperand(I);
8390         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
8391           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
8392                                               CFP->getValueAPF());
8393         } else if (Op.isUndef()) {
8394           // Handled below based on what the other operand is.
8395           NewElts[I] = Op;
8396         } else {
8397           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
8398         }
8399       }
8400 
8401       // If one half is undef, and one is constant, perfer a splat vector rather
8402       // than the normal qNaN. If it's a register, prefer 0.0 since that's
8403       // cheaper to use and may be free with a packed operation.
8404       if (NewElts[0].isUndef()) {
8405         if (isa<ConstantFPSDNode>(NewElts[1]))
8406           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
8407             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
8408       }
8409 
8410       if (NewElts[1].isUndef()) {
8411         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
8412           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
8413       }
8414 
8415       return DAG.getBuildVector(VT, SL, NewElts);
8416     }
8417   }
8418 
8419   unsigned SrcOpc = N0.getOpcode();
8420 
8421   // If it's free to do so, push canonicalizes further up the source, which may
8422   // find a canonical source.
8423   //
8424   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
8425   // sNaNs.
8426   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
8427     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
8428     if (CRHS && N0.hasOneUse()) {
8429       SDLoc SL(N);
8430       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
8431                                    N0.getOperand(0));
8432       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
8433       DCI.AddToWorklist(Canon0.getNode());
8434 
8435       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
8436     }
8437   }
8438 
8439   return isCanonicalized(DAG, N0) ? N0 : SDValue();
8440 }
8441 
8442 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
8443   switch (Opc) {
8444   case ISD::FMAXNUM:
8445   case ISD::FMAXNUM_IEEE:
8446     return AMDGPUISD::FMAX3;
8447   case ISD::SMAX:
8448     return AMDGPUISD::SMAX3;
8449   case ISD::UMAX:
8450     return AMDGPUISD::UMAX3;
8451   case ISD::FMINNUM:
8452   case ISD::FMINNUM_IEEE:
8453     return AMDGPUISD::FMIN3;
8454   case ISD::SMIN:
8455     return AMDGPUISD::SMIN3;
8456   case ISD::UMIN:
8457     return AMDGPUISD::UMIN3;
8458   default:
8459     llvm_unreachable("Not a min/max opcode");
8460   }
8461 }
8462 
8463 SDValue SITargetLowering::performIntMed3ImmCombine(
8464   SelectionDAG &DAG, const SDLoc &SL,
8465   SDValue Op0, SDValue Op1, bool Signed) const {
8466   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
8467   if (!K1)
8468     return SDValue();
8469 
8470   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
8471   if (!K0)
8472     return SDValue();
8473 
8474   if (Signed) {
8475     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
8476       return SDValue();
8477   } else {
8478     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
8479       return SDValue();
8480   }
8481 
8482   EVT VT = K0->getValueType(0);
8483   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
8484   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
8485     return DAG.getNode(Med3Opc, SL, VT,
8486                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
8487   }
8488 
8489   // If there isn't a 16-bit med3 operation, convert to 32-bit.
8490   MVT NVT = MVT::i32;
8491   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
8492 
8493   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
8494   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
8495   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
8496 
8497   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
8498   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
8499 }
8500 
8501 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
8502   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
8503     return C;
8504 
8505   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
8506     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
8507       return C;
8508   }
8509 
8510   return nullptr;
8511 }
8512 
8513 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
8514                                                   const SDLoc &SL,
8515                                                   SDValue Op0,
8516                                                   SDValue Op1) const {
8517   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
8518   if (!K1)
8519     return SDValue();
8520 
8521   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
8522   if (!K0)
8523     return SDValue();
8524 
8525   // Ordered >= (although NaN inputs should have folded away by now).
8526   APFloat::cmpResult Cmp = K0->getValueAPF().compare(K1->getValueAPF());
8527   if (Cmp == APFloat::cmpGreaterThan)
8528     return SDValue();
8529 
8530   const MachineFunction &MF = DAG.getMachineFunction();
8531   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8532 
8533   // TODO: Check IEEE bit enabled?
8534   EVT VT = Op0.getValueType();
8535   if (Info->getMode().DX10Clamp) {
8536     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
8537     // hardware fmed3 behavior converting to a min.
8538     // FIXME: Should this be allowing -0.0?
8539     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
8540       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
8541   }
8542 
8543   // med3 for f16 is only available on gfx9+, and not available for v2f16.
8544   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
8545     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
8546     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
8547     // then give the other result, which is different from med3 with a NaN
8548     // input.
8549     SDValue Var = Op0.getOperand(0);
8550     if (!DAG.isKnownNeverSNaN(Var))
8551       return SDValue();
8552 
8553     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8554 
8555     if ((!K0->hasOneUse() ||
8556          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
8557         (!K1->hasOneUse() ||
8558          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
8559       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
8560                          Var, SDValue(K0, 0), SDValue(K1, 0));
8561     }
8562   }
8563 
8564   return SDValue();
8565 }
8566 
8567 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
8568                                                DAGCombinerInfo &DCI) const {
8569   SelectionDAG &DAG = DCI.DAG;
8570 
8571   EVT VT = N->getValueType(0);
8572   unsigned Opc = N->getOpcode();
8573   SDValue Op0 = N->getOperand(0);
8574   SDValue Op1 = N->getOperand(1);
8575 
8576   // Only do this if the inner op has one use since this will just increases
8577   // register pressure for no benefit.
8578 
8579   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
8580       !VT.isVector() &&
8581       (VT == MVT::i32 || VT == MVT::f32 ||
8582        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
8583     // max(max(a, b), c) -> max3(a, b, c)
8584     // min(min(a, b), c) -> min3(a, b, c)
8585     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
8586       SDLoc DL(N);
8587       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
8588                          DL,
8589                          N->getValueType(0),
8590                          Op0.getOperand(0),
8591                          Op0.getOperand(1),
8592                          Op1);
8593     }
8594 
8595     // Try commuted.
8596     // max(a, max(b, c)) -> max3(a, b, c)
8597     // min(a, min(b, c)) -> min3(a, b, c)
8598     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
8599       SDLoc DL(N);
8600       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
8601                          DL,
8602                          N->getValueType(0),
8603                          Op0,
8604                          Op1.getOperand(0),
8605                          Op1.getOperand(1));
8606     }
8607   }
8608 
8609   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
8610   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
8611     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
8612       return Med3;
8613   }
8614 
8615   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
8616     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
8617       return Med3;
8618   }
8619 
8620   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
8621   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
8622        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
8623        (Opc == AMDGPUISD::FMIN_LEGACY &&
8624         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
8625       (VT == MVT::f32 || VT == MVT::f64 ||
8626        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
8627        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
8628       Op0.hasOneUse()) {
8629     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
8630       return Res;
8631   }
8632 
8633   return SDValue();
8634 }
8635 
8636 static bool isClampZeroToOne(SDValue A, SDValue B) {
8637   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
8638     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
8639       // FIXME: Should this be allowing -0.0?
8640       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
8641              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
8642     }
8643   }
8644 
8645   return false;
8646 }
8647 
8648 // FIXME: Should only worry about snans for version with chain.
8649 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
8650                                               DAGCombinerInfo &DCI) const {
8651   EVT VT = N->getValueType(0);
8652   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
8653   // NaNs. With a NaN input, the order of the operands may change the result.
8654 
8655   SelectionDAG &DAG = DCI.DAG;
8656   SDLoc SL(N);
8657 
8658   SDValue Src0 = N->getOperand(0);
8659   SDValue Src1 = N->getOperand(1);
8660   SDValue Src2 = N->getOperand(2);
8661 
8662   if (isClampZeroToOne(Src0, Src1)) {
8663     // const_a, const_b, x -> clamp is safe in all cases including signaling
8664     // nans.
8665     // FIXME: Should this be allowing -0.0?
8666     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
8667   }
8668 
8669   const MachineFunction &MF = DAG.getMachineFunction();
8670   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
8671 
8672   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
8673   // handling no dx10-clamp?
8674   if (Info->getMode().DX10Clamp) {
8675     // If NaNs is clamped to 0, we are free to reorder the inputs.
8676 
8677     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
8678       std::swap(Src0, Src1);
8679 
8680     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
8681       std::swap(Src1, Src2);
8682 
8683     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
8684       std::swap(Src0, Src1);
8685 
8686     if (isClampZeroToOne(Src1, Src2))
8687       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
8688   }
8689 
8690   return SDValue();
8691 }
8692 
8693 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
8694                                                  DAGCombinerInfo &DCI) const {
8695   SDValue Src0 = N->getOperand(0);
8696   SDValue Src1 = N->getOperand(1);
8697   if (Src0.isUndef() && Src1.isUndef())
8698     return DCI.DAG.getUNDEF(N->getValueType(0));
8699   return SDValue();
8700 }
8701 
8702 SDValue SITargetLowering::performExtractVectorEltCombine(
8703   SDNode *N, DAGCombinerInfo &DCI) const {
8704   SDValue Vec = N->getOperand(0);
8705   SelectionDAG &DAG = DCI.DAG;
8706 
8707   EVT VecVT = Vec.getValueType();
8708   EVT EltVT = VecVT.getVectorElementType();
8709 
8710   if ((Vec.getOpcode() == ISD::FNEG ||
8711        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
8712     SDLoc SL(N);
8713     EVT EltVT = N->getValueType(0);
8714     SDValue Idx = N->getOperand(1);
8715     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8716                               Vec.getOperand(0), Idx);
8717     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
8718   }
8719 
8720   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
8721   //    =>
8722   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
8723   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
8724   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
8725   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
8726     SDLoc SL(N);
8727     EVT EltVT = N->getValueType(0);
8728     SDValue Idx = N->getOperand(1);
8729     unsigned Opc = Vec.getOpcode();
8730 
8731     switch(Opc) {
8732     default:
8733       break;
8734       // TODO: Support other binary operations.
8735     case ISD::FADD:
8736     case ISD::FSUB:
8737     case ISD::FMUL:
8738     case ISD::ADD:
8739     case ISD::UMIN:
8740     case ISD::UMAX:
8741     case ISD::SMIN:
8742     case ISD::SMAX:
8743     case ISD::FMAXNUM:
8744     case ISD::FMINNUM:
8745     case ISD::FMAXNUM_IEEE:
8746     case ISD::FMINNUM_IEEE: {
8747       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8748                                  Vec.getOperand(0), Idx);
8749       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
8750                                  Vec.getOperand(1), Idx);
8751 
8752       DCI.AddToWorklist(Elt0.getNode());
8753       DCI.AddToWorklist(Elt1.getNode());
8754       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
8755     }
8756     }
8757   }
8758 
8759   unsigned VecSize = VecVT.getSizeInBits();
8760   unsigned EltSize = EltVT.getSizeInBits();
8761 
8762   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
8763   // This elminates non-constant index and subsequent movrel or scratch access.
8764   // Sub-dword vectors of size 2 dword or less have better implementation.
8765   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
8766   // instructions.
8767   if (VecSize <= 256 && (VecSize > 64 || EltSize >= 32) &&
8768       !isa<ConstantSDNode>(N->getOperand(1))) {
8769     SDLoc SL(N);
8770     SDValue Idx = N->getOperand(1);
8771     EVT IdxVT = Idx.getValueType();
8772     SDValue V;
8773     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
8774       SDValue IC = DAG.getConstant(I, SL, IdxVT);
8775       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
8776       if (I == 0)
8777         V = Elt;
8778       else
8779         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
8780     }
8781     return V;
8782   }
8783 
8784   if (!DCI.isBeforeLegalize())
8785     return SDValue();
8786 
8787   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
8788   // elements. This exposes more load reduction opportunities by replacing
8789   // multiple small extract_vector_elements with a single 32-bit extract.
8790   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
8791   if (isa<MemSDNode>(Vec) &&
8792       EltSize <= 16 &&
8793       EltVT.isByteSized() &&
8794       VecSize > 32 &&
8795       VecSize % 32 == 0 &&
8796       Idx) {
8797     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
8798 
8799     unsigned BitIndex = Idx->getZExtValue() * EltSize;
8800     unsigned EltIdx = BitIndex / 32;
8801     unsigned LeftoverBitIdx = BitIndex % 32;
8802     SDLoc SL(N);
8803 
8804     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
8805     DCI.AddToWorklist(Cast.getNode());
8806 
8807     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
8808                               DAG.getConstant(EltIdx, SL, MVT::i32));
8809     DCI.AddToWorklist(Elt.getNode());
8810     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
8811                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
8812     DCI.AddToWorklist(Srl.getNode());
8813 
8814     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
8815     DCI.AddToWorklist(Trunc.getNode());
8816     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
8817   }
8818 
8819   return SDValue();
8820 }
8821 
8822 SDValue
8823 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
8824                                                 DAGCombinerInfo &DCI) const {
8825   SDValue Vec = N->getOperand(0);
8826   SDValue Idx = N->getOperand(2);
8827   EVT VecVT = Vec.getValueType();
8828   EVT EltVT = VecVT.getVectorElementType();
8829   unsigned VecSize = VecVT.getSizeInBits();
8830   unsigned EltSize = EltVT.getSizeInBits();
8831 
8832   // INSERT_VECTOR_ELT (<n x e>, var-idx)
8833   // => BUILD_VECTOR n x select (e, const-idx)
8834   // This elminates non-constant index and subsequent movrel or scratch access.
8835   // Sub-dword vectors of size 2 dword or less have better implementation.
8836   // Vectors of size bigger than 8 dwords would yield too many v_cndmask_b32
8837   // instructions.
8838   if (isa<ConstantSDNode>(Idx) ||
8839       VecSize > 256 || (VecSize <= 64 && EltSize < 32))
8840     return SDValue();
8841 
8842   SelectionDAG &DAG = DCI.DAG;
8843   SDLoc SL(N);
8844   SDValue Ins = N->getOperand(1);
8845   EVT IdxVT = Idx.getValueType();
8846 
8847   SmallVector<SDValue, 16> Ops;
8848   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
8849     SDValue IC = DAG.getConstant(I, SL, IdxVT);
8850     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
8851     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
8852     Ops.push_back(V);
8853   }
8854 
8855   return DAG.getBuildVector(VecVT, SL, Ops);
8856 }
8857 
8858 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
8859                                           const SDNode *N0,
8860                                           const SDNode *N1) const {
8861   EVT VT = N0->getValueType(0);
8862 
8863   // Only do this if we are not trying to support denormals. v_mad_f32 does not
8864   // support denormals ever.
8865   if (((VT == MVT::f32 && !Subtarget->hasFP32Denormals()) ||
8866        (VT == MVT::f16 && !Subtarget->hasFP16Denormals() &&
8867         getSubtarget()->hasMadF16())) &&
8868        isOperationLegal(ISD::FMAD, VT))
8869     return ISD::FMAD;
8870 
8871   const TargetOptions &Options = DAG.getTarget().Options;
8872   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
8873        (N0->getFlags().hasAllowContract() &&
8874         N1->getFlags().hasAllowContract())) &&
8875       isFMAFasterThanFMulAndFAdd(VT)) {
8876     return ISD::FMA;
8877   }
8878 
8879   return 0;
8880 }
8881 
8882 // For a reassociatable opcode perform:
8883 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
8884 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
8885                                                SelectionDAG &DAG) const {
8886   EVT VT = N->getValueType(0);
8887   if (VT != MVT::i32 && VT != MVT::i64)
8888     return SDValue();
8889 
8890   unsigned Opc = N->getOpcode();
8891   SDValue Op0 = N->getOperand(0);
8892   SDValue Op1 = N->getOperand(1);
8893 
8894   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
8895     return SDValue();
8896 
8897   if (Op0->isDivergent())
8898     std::swap(Op0, Op1);
8899 
8900   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
8901     return SDValue();
8902 
8903   SDValue Op2 = Op1.getOperand(1);
8904   Op1 = Op1.getOperand(0);
8905   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
8906     return SDValue();
8907 
8908   if (Op1->isDivergent())
8909     std::swap(Op1, Op2);
8910 
8911   // If either operand is constant this will conflict with
8912   // DAGCombiner::ReassociateOps().
8913   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
8914       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
8915     return SDValue();
8916 
8917   SDLoc SL(N);
8918   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
8919   return DAG.getNode(Opc, SL, VT, Add1, Op2);
8920 }
8921 
8922 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
8923                            EVT VT,
8924                            SDValue N0, SDValue N1, SDValue N2,
8925                            bool Signed) {
8926   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
8927   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
8928   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
8929   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
8930 }
8931 
8932 SDValue SITargetLowering::performAddCombine(SDNode *N,
8933                                             DAGCombinerInfo &DCI) const {
8934   SelectionDAG &DAG = DCI.DAG;
8935   EVT VT = N->getValueType(0);
8936   SDLoc SL(N);
8937   SDValue LHS = N->getOperand(0);
8938   SDValue RHS = N->getOperand(1);
8939 
8940   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
8941       && Subtarget->hasMad64_32() &&
8942       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
8943       VT.getScalarSizeInBits() <= 64) {
8944     if (LHS.getOpcode() != ISD::MUL)
8945       std::swap(LHS, RHS);
8946 
8947     SDValue MulLHS = LHS.getOperand(0);
8948     SDValue MulRHS = LHS.getOperand(1);
8949     SDValue AddRHS = RHS;
8950 
8951     // TODO: Maybe restrict if SGPR inputs.
8952     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
8953         numBitsUnsigned(MulRHS, DAG) <= 32) {
8954       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
8955       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
8956       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
8957       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
8958     }
8959 
8960     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
8961       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
8962       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
8963       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
8964       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
8965     }
8966 
8967     return SDValue();
8968   }
8969 
8970   if (SDValue V = reassociateScalarOps(N, DAG)) {
8971     return V;
8972   }
8973 
8974   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
8975     return SDValue();
8976 
8977   // add x, zext (setcc) => addcarry x, 0, setcc
8978   // add x, sext (setcc) => subcarry x, 0, setcc
8979   unsigned Opc = LHS.getOpcode();
8980   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
8981       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
8982     std::swap(RHS, LHS);
8983 
8984   Opc = RHS.getOpcode();
8985   switch (Opc) {
8986   default: break;
8987   case ISD::ZERO_EXTEND:
8988   case ISD::SIGN_EXTEND:
8989   case ISD::ANY_EXTEND: {
8990     auto Cond = RHS.getOperand(0);
8991     if (!isBoolSGPR(Cond))
8992       break;
8993     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
8994     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
8995     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
8996     return DAG.getNode(Opc, SL, VTList, Args);
8997   }
8998   case ISD::ADDCARRY: {
8999     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9000     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9001     if (!C || C->getZExtValue() != 0) break;
9002     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
9003     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
9004   }
9005   }
9006   return SDValue();
9007 }
9008 
9009 SDValue SITargetLowering::performSubCombine(SDNode *N,
9010                                             DAGCombinerInfo &DCI) const {
9011   SelectionDAG &DAG = DCI.DAG;
9012   EVT VT = N->getValueType(0);
9013 
9014   if (VT != MVT::i32)
9015     return SDValue();
9016 
9017   SDLoc SL(N);
9018   SDValue LHS = N->getOperand(0);
9019   SDValue RHS = N->getOperand(1);
9020 
9021   if (LHS.getOpcode() == ISD::SUBCARRY) {
9022     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
9023     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9024     if (!C || !C->isNullValue())
9025       return SDValue();
9026     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
9027     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
9028   }
9029   return SDValue();
9030 }
9031 
9032 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
9033   DAGCombinerInfo &DCI) const {
9034 
9035   if (N->getValueType(0) != MVT::i32)
9036     return SDValue();
9037 
9038   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
9039   if (!C || C->getZExtValue() != 0)
9040     return SDValue();
9041 
9042   SelectionDAG &DAG = DCI.DAG;
9043   SDValue LHS = N->getOperand(0);
9044 
9045   // addcarry (add x, y), 0, cc => addcarry x, y, cc
9046   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
9047   unsigned LHSOpc = LHS.getOpcode();
9048   unsigned Opc = N->getOpcode();
9049   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
9050       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
9051     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
9052     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
9053   }
9054   return SDValue();
9055 }
9056 
9057 SDValue SITargetLowering::performFAddCombine(SDNode *N,
9058                                              DAGCombinerInfo &DCI) const {
9059   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9060     return SDValue();
9061 
9062   SelectionDAG &DAG = DCI.DAG;
9063   EVT VT = N->getValueType(0);
9064 
9065   SDLoc SL(N);
9066   SDValue LHS = N->getOperand(0);
9067   SDValue RHS = N->getOperand(1);
9068 
9069   // These should really be instruction patterns, but writing patterns with
9070   // source modiifiers is a pain.
9071 
9072   // fadd (fadd (a, a), b) -> mad 2.0, a, b
9073   if (LHS.getOpcode() == ISD::FADD) {
9074     SDValue A = LHS.getOperand(0);
9075     if (A == LHS.getOperand(1)) {
9076       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9077       if (FusedOp != 0) {
9078         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9079         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
9080       }
9081     }
9082   }
9083 
9084   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
9085   if (RHS.getOpcode() == ISD::FADD) {
9086     SDValue A = RHS.getOperand(0);
9087     if (A == RHS.getOperand(1)) {
9088       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9089       if (FusedOp != 0) {
9090         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9091         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
9092       }
9093     }
9094   }
9095 
9096   return SDValue();
9097 }
9098 
9099 SDValue SITargetLowering::performFSubCombine(SDNode *N,
9100                                              DAGCombinerInfo &DCI) const {
9101   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9102     return SDValue();
9103 
9104   SelectionDAG &DAG = DCI.DAG;
9105   SDLoc SL(N);
9106   EVT VT = N->getValueType(0);
9107   assert(!VT.isVector());
9108 
9109   // Try to get the fneg to fold into the source modifier. This undoes generic
9110   // DAG combines and folds them into the mad.
9111   //
9112   // Only do this if we are not trying to support denormals. v_mad_f32 does
9113   // not support denormals ever.
9114   SDValue LHS = N->getOperand(0);
9115   SDValue RHS = N->getOperand(1);
9116   if (LHS.getOpcode() == ISD::FADD) {
9117     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
9118     SDValue A = LHS.getOperand(0);
9119     if (A == LHS.getOperand(1)) {
9120       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
9121       if (FusedOp != 0){
9122         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
9123         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
9124 
9125         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
9126       }
9127     }
9128   }
9129 
9130   if (RHS.getOpcode() == ISD::FADD) {
9131     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
9132 
9133     SDValue A = RHS.getOperand(0);
9134     if (A == RHS.getOperand(1)) {
9135       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
9136       if (FusedOp != 0){
9137         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
9138         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
9139       }
9140     }
9141   }
9142 
9143   return SDValue();
9144 }
9145 
9146 SDValue SITargetLowering::performFMACombine(SDNode *N,
9147                                             DAGCombinerInfo &DCI) const {
9148   SelectionDAG &DAG = DCI.DAG;
9149   EVT VT = N->getValueType(0);
9150   SDLoc SL(N);
9151 
9152   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
9153     return SDValue();
9154 
9155   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
9156   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
9157   SDValue Op1 = N->getOperand(0);
9158   SDValue Op2 = N->getOperand(1);
9159   SDValue FMA = N->getOperand(2);
9160 
9161   if (FMA.getOpcode() != ISD::FMA ||
9162       Op1.getOpcode() != ISD::FP_EXTEND ||
9163       Op2.getOpcode() != ISD::FP_EXTEND)
9164     return SDValue();
9165 
9166   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
9167   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
9168   // is sufficient to allow generaing fdot2.
9169   const TargetOptions &Options = DAG.getTarget().Options;
9170   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9171       (N->getFlags().hasAllowContract() &&
9172        FMA->getFlags().hasAllowContract())) {
9173     Op1 = Op1.getOperand(0);
9174     Op2 = Op2.getOperand(0);
9175     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9176         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9177       return SDValue();
9178 
9179     SDValue Vec1 = Op1.getOperand(0);
9180     SDValue Idx1 = Op1.getOperand(1);
9181     SDValue Vec2 = Op2.getOperand(0);
9182 
9183     SDValue FMAOp1 = FMA.getOperand(0);
9184     SDValue FMAOp2 = FMA.getOperand(1);
9185     SDValue FMAAcc = FMA.getOperand(2);
9186 
9187     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
9188         FMAOp2.getOpcode() != ISD::FP_EXTEND)
9189       return SDValue();
9190 
9191     FMAOp1 = FMAOp1.getOperand(0);
9192     FMAOp2 = FMAOp2.getOperand(0);
9193     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9194         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
9195       return SDValue();
9196 
9197     SDValue Vec3 = FMAOp1.getOperand(0);
9198     SDValue Vec4 = FMAOp2.getOperand(0);
9199     SDValue Idx2 = FMAOp1.getOperand(1);
9200 
9201     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
9202         // Idx1 and Idx2 cannot be the same.
9203         Idx1 == Idx2)
9204       return SDValue();
9205 
9206     if (Vec1 == Vec2 || Vec3 == Vec4)
9207       return SDValue();
9208 
9209     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
9210       return SDValue();
9211 
9212     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
9213         (Vec1 == Vec4 && Vec2 == Vec3)) {
9214       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
9215                          DAG.getTargetConstant(0, SL, MVT::i1));
9216     }
9217   }
9218   return SDValue();
9219 }
9220 
9221 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
9222                                               DAGCombinerInfo &DCI) const {
9223   SelectionDAG &DAG = DCI.DAG;
9224   SDLoc SL(N);
9225 
9226   SDValue LHS = N->getOperand(0);
9227   SDValue RHS = N->getOperand(1);
9228   EVT VT = LHS.getValueType();
9229   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
9230 
9231   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
9232   if (!CRHS) {
9233     CRHS = dyn_cast<ConstantSDNode>(LHS);
9234     if (CRHS) {
9235       std::swap(LHS, RHS);
9236       CC = getSetCCSwappedOperands(CC);
9237     }
9238   }
9239 
9240   if (CRHS) {
9241     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
9242         isBoolSGPR(LHS.getOperand(0))) {
9243       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
9244       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
9245       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
9246       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
9247       if ((CRHS->isAllOnesValue() &&
9248            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
9249           (CRHS->isNullValue() &&
9250            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
9251         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9252                            DAG.getConstant(-1, SL, MVT::i1));
9253       if ((CRHS->isAllOnesValue() &&
9254            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
9255           (CRHS->isNullValue() &&
9256            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
9257         return LHS.getOperand(0);
9258     }
9259 
9260     uint64_t CRHSVal = CRHS->getZExtValue();
9261     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
9262         LHS.getOpcode() == ISD::SELECT &&
9263         isa<ConstantSDNode>(LHS.getOperand(1)) &&
9264         isa<ConstantSDNode>(LHS.getOperand(2)) &&
9265         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
9266         isBoolSGPR(LHS.getOperand(0))) {
9267       // Given CT != FT:
9268       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
9269       // setcc (select cc, CT, CF), CF, ne => cc
9270       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
9271       // setcc (select cc, CT, CF), CT, eq => cc
9272       uint64_t CT = LHS.getConstantOperandVal(1);
9273       uint64_t CF = LHS.getConstantOperandVal(2);
9274 
9275       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
9276           (CT == CRHSVal && CC == ISD::SETNE))
9277         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
9278                            DAG.getConstant(-1, SL, MVT::i1));
9279       if ((CF == CRHSVal && CC == ISD::SETNE) ||
9280           (CT == CRHSVal && CC == ISD::SETEQ))
9281         return LHS.getOperand(0);
9282     }
9283   }
9284 
9285   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
9286                                            VT != MVT::f16))
9287     return SDValue();
9288 
9289   // Match isinf/isfinite pattern
9290   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
9291   // (fcmp one (fabs x), inf) -> (fp_class x,
9292   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
9293   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
9294     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
9295     if (!CRHS)
9296       return SDValue();
9297 
9298     const APFloat &APF = CRHS->getValueAPF();
9299     if (APF.isInfinity() && !APF.isNegative()) {
9300       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
9301                                  SIInstrFlags::N_INFINITY;
9302       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
9303                                     SIInstrFlags::P_ZERO |
9304                                     SIInstrFlags::N_NORMAL |
9305                                     SIInstrFlags::P_NORMAL |
9306                                     SIInstrFlags::N_SUBNORMAL |
9307                                     SIInstrFlags::P_SUBNORMAL;
9308       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
9309       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
9310                          DAG.getConstant(Mask, SL, MVT::i32));
9311     }
9312   }
9313 
9314   return SDValue();
9315 }
9316 
9317 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
9318                                                      DAGCombinerInfo &DCI) const {
9319   SelectionDAG &DAG = DCI.DAG;
9320   SDLoc SL(N);
9321   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
9322 
9323   SDValue Src = N->getOperand(0);
9324   SDValue Srl = N->getOperand(0);
9325   if (Srl.getOpcode() == ISD::ZERO_EXTEND)
9326     Srl = Srl.getOperand(0);
9327 
9328   // TODO: Handle (or x, (srl y, 8)) pattern when known bits are zero.
9329   if (Srl.getOpcode() == ISD::SRL) {
9330     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
9331     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
9332     // cvt_f32_ubyte0 (srl x, 8) -> cvt_f32_ubyte1 x
9333 
9334     if (const ConstantSDNode *C =
9335         dyn_cast<ConstantSDNode>(Srl.getOperand(1))) {
9336       Srl = DAG.getZExtOrTrunc(Srl.getOperand(0), SDLoc(Srl.getOperand(0)),
9337                                EVT(MVT::i32));
9338 
9339       unsigned SrcOffset = C->getZExtValue() + 8 * Offset;
9340       if (SrcOffset < 32 && SrcOffset % 8 == 0) {
9341         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + SrcOffset / 8, SL,
9342                            MVT::f32, Srl);
9343       }
9344     }
9345   }
9346 
9347   APInt Demanded = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
9348 
9349   KnownBits Known;
9350   TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
9351                                         !DCI.isBeforeLegalizeOps());
9352   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
9353   if (TLI.SimplifyDemandedBits(Src, Demanded, Known, TLO)) {
9354     DCI.CommitTargetLoweringOpt(TLO);
9355   }
9356 
9357   return SDValue();
9358 }
9359 
9360 SDValue SITargetLowering::performClampCombine(SDNode *N,
9361                                               DAGCombinerInfo &DCI) const {
9362   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
9363   if (!CSrc)
9364     return SDValue();
9365 
9366   const MachineFunction &MF = DCI.DAG.getMachineFunction();
9367   const APFloat &F = CSrc->getValueAPF();
9368   APFloat Zero = APFloat::getZero(F.getSemantics());
9369   APFloat::cmpResult Cmp0 = F.compare(Zero);
9370   if (Cmp0 == APFloat::cmpLessThan ||
9371       (Cmp0 == APFloat::cmpUnordered &&
9372        MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
9373     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
9374   }
9375 
9376   APFloat One(F.getSemantics(), "1.0");
9377   APFloat::cmpResult Cmp1 = F.compare(One);
9378   if (Cmp1 == APFloat::cmpGreaterThan)
9379     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
9380 
9381   return SDValue(CSrc, 0);
9382 }
9383 
9384 
9385 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
9386                                             DAGCombinerInfo &DCI) const {
9387   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
9388     return SDValue();
9389   switch (N->getOpcode()) {
9390   default:
9391     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9392   case ISD::ADD:
9393     return performAddCombine(N, DCI);
9394   case ISD::SUB:
9395     return performSubCombine(N, DCI);
9396   case ISD::ADDCARRY:
9397   case ISD::SUBCARRY:
9398     return performAddCarrySubCarryCombine(N, DCI);
9399   case ISD::FADD:
9400     return performFAddCombine(N, DCI);
9401   case ISD::FSUB:
9402     return performFSubCombine(N, DCI);
9403   case ISD::SETCC:
9404     return performSetCCCombine(N, DCI);
9405   case ISD::FMAXNUM:
9406   case ISD::FMINNUM:
9407   case ISD::FMAXNUM_IEEE:
9408   case ISD::FMINNUM_IEEE:
9409   case ISD::SMAX:
9410   case ISD::SMIN:
9411   case ISD::UMAX:
9412   case ISD::UMIN:
9413   case AMDGPUISD::FMIN_LEGACY:
9414   case AMDGPUISD::FMAX_LEGACY:
9415     return performMinMaxCombine(N, DCI);
9416   case ISD::FMA:
9417     return performFMACombine(N, DCI);
9418   case ISD::LOAD: {
9419     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
9420       return Widended;
9421     LLVM_FALLTHROUGH;
9422   }
9423   case ISD::STORE:
9424   case ISD::ATOMIC_LOAD:
9425   case ISD::ATOMIC_STORE:
9426   case ISD::ATOMIC_CMP_SWAP:
9427   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
9428   case ISD::ATOMIC_SWAP:
9429   case ISD::ATOMIC_LOAD_ADD:
9430   case ISD::ATOMIC_LOAD_SUB:
9431   case ISD::ATOMIC_LOAD_AND:
9432   case ISD::ATOMIC_LOAD_OR:
9433   case ISD::ATOMIC_LOAD_XOR:
9434   case ISD::ATOMIC_LOAD_NAND:
9435   case ISD::ATOMIC_LOAD_MIN:
9436   case ISD::ATOMIC_LOAD_MAX:
9437   case ISD::ATOMIC_LOAD_UMIN:
9438   case ISD::ATOMIC_LOAD_UMAX:
9439   case ISD::ATOMIC_LOAD_FADD:
9440   case AMDGPUISD::ATOMIC_INC:
9441   case AMDGPUISD::ATOMIC_DEC:
9442   case AMDGPUISD::ATOMIC_LOAD_FMIN:
9443   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
9444     if (DCI.isBeforeLegalize())
9445       break;
9446     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
9447   case ISD::AND:
9448     return performAndCombine(N, DCI);
9449   case ISD::OR:
9450     return performOrCombine(N, DCI);
9451   case ISD::XOR:
9452     return performXorCombine(N, DCI);
9453   case ISD::ZERO_EXTEND:
9454     return performZeroExtendCombine(N, DCI);
9455   case ISD::SIGN_EXTEND_INREG:
9456     return performSignExtendInRegCombine(N , DCI);
9457   case AMDGPUISD::FP_CLASS:
9458     return performClassCombine(N, DCI);
9459   case ISD::FCANONICALIZE:
9460     return performFCanonicalizeCombine(N, DCI);
9461   case AMDGPUISD::RCP:
9462     return performRcpCombine(N, DCI);
9463   case AMDGPUISD::FRACT:
9464   case AMDGPUISD::RSQ:
9465   case AMDGPUISD::RCP_LEGACY:
9466   case AMDGPUISD::RSQ_LEGACY:
9467   case AMDGPUISD::RCP_IFLAG:
9468   case AMDGPUISD::RSQ_CLAMP:
9469   case AMDGPUISD::LDEXP: {
9470     SDValue Src = N->getOperand(0);
9471     if (Src.isUndef())
9472       return Src;
9473     break;
9474   }
9475   case ISD::SINT_TO_FP:
9476   case ISD::UINT_TO_FP:
9477     return performUCharToFloatCombine(N, DCI);
9478   case AMDGPUISD::CVT_F32_UBYTE0:
9479   case AMDGPUISD::CVT_F32_UBYTE1:
9480   case AMDGPUISD::CVT_F32_UBYTE2:
9481   case AMDGPUISD::CVT_F32_UBYTE3:
9482     return performCvtF32UByteNCombine(N, DCI);
9483   case AMDGPUISD::FMED3:
9484     return performFMed3Combine(N, DCI);
9485   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9486     return performCvtPkRTZCombine(N, DCI);
9487   case AMDGPUISD::CLAMP:
9488     return performClampCombine(N, DCI);
9489   case ISD::SCALAR_TO_VECTOR: {
9490     SelectionDAG &DAG = DCI.DAG;
9491     EVT VT = N->getValueType(0);
9492 
9493     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
9494     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
9495       SDLoc SL(N);
9496       SDValue Src = N->getOperand(0);
9497       EVT EltVT = Src.getValueType();
9498       if (EltVT == MVT::f16)
9499         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
9500 
9501       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
9502       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
9503     }
9504 
9505     break;
9506   }
9507   case ISD::EXTRACT_VECTOR_ELT:
9508     return performExtractVectorEltCombine(N, DCI);
9509   case ISD::INSERT_VECTOR_ELT:
9510     return performInsertVectorEltCombine(N, DCI);
9511   }
9512   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
9513 }
9514 
9515 /// Helper function for adjustWritemask
9516 static unsigned SubIdx2Lane(unsigned Idx) {
9517   switch (Idx) {
9518   default: return 0;
9519   case AMDGPU::sub0: return 0;
9520   case AMDGPU::sub1: return 1;
9521   case AMDGPU::sub2: return 2;
9522   case AMDGPU::sub3: return 3;
9523   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
9524   }
9525 }
9526 
9527 /// Adjust the writemask of MIMG instructions
9528 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
9529                                           SelectionDAG &DAG) const {
9530   unsigned Opcode = Node->getMachineOpcode();
9531 
9532   // Subtract 1 because the vdata output is not a MachineSDNode operand.
9533   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
9534   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
9535     return Node; // not implemented for D16
9536 
9537   SDNode *Users[5] = { nullptr };
9538   unsigned Lane = 0;
9539   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
9540   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
9541   unsigned NewDmask = 0;
9542   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
9543   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
9544   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
9545                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
9546   unsigned TFCLane = 0;
9547   bool HasChain = Node->getNumValues() > 1;
9548 
9549   if (OldDmask == 0) {
9550     // These are folded out, but on the chance it happens don't assert.
9551     return Node;
9552   }
9553 
9554   unsigned OldBitsSet = countPopulation(OldDmask);
9555   // Work out which is the TFE/LWE lane if that is enabled.
9556   if (UsesTFC) {
9557     TFCLane = OldBitsSet;
9558   }
9559 
9560   // Try to figure out the used register components
9561   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
9562        I != E; ++I) {
9563 
9564     // Don't look at users of the chain.
9565     if (I.getUse().getResNo() != 0)
9566       continue;
9567 
9568     // Abort if we can't understand the usage
9569     if (!I->isMachineOpcode() ||
9570         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
9571       return Node;
9572 
9573     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
9574     // Note that subregs are packed, i.e. Lane==0 is the first bit set
9575     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
9576     // set, etc.
9577     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
9578 
9579     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
9580     if (UsesTFC && Lane == TFCLane) {
9581       Users[Lane] = *I;
9582     } else {
9583       // Set which texture component corresponds to the lane.
9584       unsigned Comp;
9585       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
9586         Comp = countTrailingZeros(Dmask);
9587         Dmask &= ~(1 << Comp);
9588       }
9589 
9590       // Abort if we have more than one user per component.
9591       if (Users[Lane])
9592         return Node;
9593 
9594       Users[Lane] = *I;
9595       NewDmask |= 1 << Comp;
9596     }
9597   }
9598 
9599   // Don't allow 0 dmask, as hardware assumes one channel enabled.
9600   bool NoChannels = !NewDmask;
9601   if (NoChannels) {
9602     if (!UsesTFC) {
9603       // No uses of the result and not using TFC. Then do nothing.
9604       return Node;
9605     }
9606     // If the original dmask has one channel - then nothing to do
9607     if (OldBitsSet == 1)
9608       return Node;
9609     // Use an arbitrary dmask - required for the instruction to work
9610     NewDmask = 1;
9611   }
9612   // Abort if there's no change
9613   if (NewDmask == OldDmask)
9614     return Node;
9615 
9616   unsigned BitsSet = countPopulation(NewDmask);
9617 
9618   // Check for TFE or LWE - increase the number of channels by one to account
9619   // for the extra return value
9620   // This will need adjustment for D16 if this is also included in
9621   // adjustWriteMask (this function) but at present D16 are excluded.
9622   unsigned NewChannels = BitsSet + UsesTFC;
9623 
9624   int NewOpcode =
9625       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
9626   assert(NewOpcode != -1 &&
9627          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
9628          "failed to find equivalent MIMG op");
9629 
9630   // Adjust the writemask in the node
9631   SmallVector<SDValue, 12> Ops;
9632   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
9633   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
9634   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
9635 
9636   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
9637 
9638   MVT ResultVT = NewChannels == 1 ?
9639     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
9640                            NewChannels == 5 ? 8 : NewChannels);
9641   SDVTList NewVTList = HasChain ?
9642     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
9643 
9644 
9645   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
9646                                               NewVTList, Ops);
9647 
9648   if (HasChain) {
9649     // Update chain.
9650     DAG.setNodeMemRefs(NewNode, Node->memoperands());
9651     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
9652   }
9653 
9654   if (NewChannels == 1) {
9655     assert(Node->hasNUsesOfValue(1, 0));
9656     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
9657                                       SDLoc(Node), Users[Lane]->getValueType(0),
9658                                       SDValue(NewNode, 0));
9659     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
9660     return nullptr;
9661   }
9662 
9663   // Update the users of the node with the new indices
9664   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
9665     SDNode *User = Users[i];
9666     if (!User) {
9667       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
9668       // Users[0] is still nullptr because channel 0 doesn't really have a use.
9669       if (i || !NoChannels)
9670         continue;
9671     } else {
9672       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
9673       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
9674     }
9675 
9676     switch (Idx) {
9677     default: break;
9678     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
9679     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
9680     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
9681     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
9682     }
9683   }
9684 
9685   DAG.RemoveDeadNode(Node);
9686   return nullptr;
9687 }
9688 
9689 static bool isFrameIndexOp(SDValue Op) {
9690   if (Op.getOpcode() == ISD::AssertZext)
9691     Op = Op.getOperand(0);
9692 
9693   return isa<FrameIndexSDNode>(Op);
9694 }
9695 
9696 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
9697 /// with frame index operands.
9698 /// LLVM assumes that inputs are to these instructions are registers.
9699 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
9700                                                         SelectionDAG &DAG) const {
9701   if (Node->getOpcode() == ISD::CopyToReg) {
9702     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
9703     SDValue SrcVal = Node->getOperand(2);
9704 
9705     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
9706     // to try understanding copies to physical registers.
9707     if (SrcVal.getValueType() == MVT::i1 &&
9708         TargetRegisterInfo::isPhysicalRegister(DestReg->getReg())) {
9709       SDLoc SL(Node);
9710       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
9711       SDValue VReg = DAG.getRegister(
9712         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
9713 
9714       SDNode *Glued = Node->getGluedNode();
9715       SDValue ToVReg
9716         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
9717                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
9718       SDValue ToResultReg
9719         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
9720                            VReg, ToVReg.getValue(1));
9721       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
9722       DAG.RemoveDeadNode(Node);
9723       return ToResultReg.getNode();
9724     }
9725   }
9726 
9727   SmallVector<SDValue, 8> Ops;
9728   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
9729     if (!isFrameIndexOp(Node->getOperand(i))) {
9730       Ops.push_back(Node->getOperand(i));
9731       continue;
9732     }
9733 
9734     SDLoc DL(Node);
9735     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
9736                                      Node->getOperand(i).getValueType(),
9737                                      Node->getOperand(i)), 0));
9738   }
9739 
9740   return DAG.UpdateNodeOperands(Node, Ops);
9741 }
9742 
9743 /// Fold the instructions after selecting them.
9744 /// Returns null if users were already updated.
9745 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
9746                                           SelectionDAG &DAG) const {
9747   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9748   unsigned Opcode = Node->getMachineOpcode();
9749 
9750   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
9751       !TII->isGather4(Opcode)) {
9752     return adjustWritemask(Node, DAG);
9753   }
9754 
9755   if (Opcode == AMDGPU::INSERT_SUBREG ||
9756       Opcode == AMDGPU::REG_SEQUENCE) {
9757     legalizeTargetIndependentNode(Node, DAG);
9758     return Node;
9759   }
9760 
9761   switch (Opcode) {
9762   case AMDGPU::V_DIV_SCALE_F32:
9763   case AMDGPU::V_DIV_SCALE_F64: {
9764     // Satisfy the operand register constraint when one of the inputs is
9765     // undefined. Ordinarily each undef value will have its own implicit_def of
9766     // a vreg, so force these to use a single register.
9767     SDValue Src0 = Node->getOperand(0);
9768     SDValue Src1 = Node->getOperand(1);
9769     SDValue Src2 = Node->getOperand(2);
9770 
9771     if ((Src0.isMachineOpcode() &&
9772          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
9773         (Src0 == Src1 || Src0 == Src2))
9774       break;
9775 
9776     MVT VT = Src0.getValueType().getSimpleVT();
9777     const TargetRegisterClass *RC =
9778         getRegClassFor(VT, Src0.getNode()->isDivergent());
9779 
9780     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
9781     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
9782 
9783     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
9784                                       UndefReg, Src0, SDValue());
9785 
9786     // src0 must be the same register as src1 or src2, even if the value is
9787     // undefined, so make sure we don't violate this constraint.
9788     if (Src0.isMachineOpcode() &&
9789         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
9790       if (Src1.isMachineOpcode() &&
9791           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
9792         Src0 = Src1;
9793       else if (Src2.isMachineOpcode() &&
9794                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
9795         Src0 = Src2;
9796       else {
9797         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
9798         Src0 = UndefReg;
9799         Src1 = UndefReg;
9800       }
9801     } else
9802       break;
9803 
9804     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
9805     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
9806       Ops.push_back(Node->getOperand(I));
9807 
9808     Ops.push_back(ImpDef.getValue(1));
9809     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
9810   }
9811   case AMDGPU::V_PERMLANE16_B32:
9812   case AMDGPU::V_PERMLANEX16_B32: {
9813     ConstantSDNode *FI = cast<ConstantSDNode>(Node->getOperand(0));
9814     ConstantSDNode *BC = cast<ConstantSDNode>(Node->getOperand(2));
9815     if (!FI->getZExtValue() && !BC->getZExtValue())
9816       break;
9817     SDValue VDstIn = Node->getOperand(6);
9818     if (VDstIn.isMachineOpcode()
9819         && VDstIn.getMachineOpcode() == AMDGPU::IMPLICIT_DEF)
9820       break;
9821     MachineSDNode *ImpDef = DAG.getMachineNode(TargetOpcode::IMPLICIT_DEF,
9822                                                SDLoc(Node), MVT::i32);
9823     SmallVector<SDValue, 8> Ops = { SDValue(FI, 0), Node->getOperand(1),
9824                                     SDValue(BC, 0), Node->getOperand(3),
9825                                     Node->getOperand(4), Node->getOperand(5),
9826                                     SDValue(ImpDef, 0), Node->getOperand(7) };
9827     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
9828   }
9829   default:
9830     break;
9831   }
9832 
9833   return Node;
9834 }
9835 
9836 /// Assign the register class depending on the number of
9837 /// bits set in the writemask
9838 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
9839                                                      SDNode *Node) const {
9840   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9841 
9842   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
9843 
9844   if (TII->isVOP3(MI.getOpcode())) {
9845     // Make sure constant bus requirements are respected.
9846     TII->legalizeOperandsVOP3(MRI, MI);
9847     return;
9848   }
9849 
9850   // Replace unused atomics with the no return version.
9851   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
9852   if (NoRetAtomicOp != -1) {
9853     if (!Node->hasAnyUseOfValue(0)) {
9854       MI.setDesc(TII->get(NoRetAtomicOp));
9855       MI.RemoveOperand(0);
9856       return;
9857     }
9858 
9859     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
9860     // instruction, because the return type of these instructions is a vec2 of
9861     // the memory type, so it can be tied to the input operand.
9862     // This means these instructions always have a use, so we need to add a
9863     // special case to check if the atomic has only one extract_subreg use,
9864     // which itself has no uses.
9865     if ((Node->hasNUsesOfValue(1, 0) &&
9866          Node->use_begin()->isMachineOpcode() &&
9867          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
9868          !Node->use_begin()->hasAnyUseOfValue(0))) {
9869       unsigned Def = MI.getOperand(0).getReg();
9870 
9871       // Change this into a noret atomic.
9872       MI.setDesc(TII->get(NoRetAtomicOp));
9873       MI.RemoveOperand(0);
9874 
9875       // If we only remove the def operand from the atomic instruction, the
9876       // extract_subreg will be left with a use of a vreg without a def.
9877       // So we need to insert an implicit_def to avoid machine verifier
9878       // errors.
9879       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
9880               TII->get(AMDGPU::IMPLICIT_DEF), Def);
9881     }
9882     return;
9883   }
9884 }
9885 
9886 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
9887                               uint64_t Val) {
9888   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
9889   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
9890 }
9891 
9892 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
9893                                                 const SDLoc &DL,
9894                                                 SDValue Ptr) const {
9895   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9896 
9897   // Build the half of the subregister with the constants before building the
9898   // full 128-bit register. If we are building multiple resource descriptors,
9899   // this will allow CSEing of the 2-component register.
9900   const SDValue Ops0[] = {
9901     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
9902     buildSMovImm32(DAG, DL, 0),
9903     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
9904     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
9905     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
9906   };
9907 
9908   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
9909                                                 MVT::v2i32, Ops0), 0);
9910 
9911   // Combine the constants and the pointer.
9912   const SDValue Ops1[] = {
9913     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
9914     Ptr,
9915     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
9916     SubRegHi,
9917     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
9918   };
9919 
9920   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
9921 }
9922 
9923 /// Return a resource descriptor with the 'Add TID' bit enabled
9924 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
9925 ///        of the resource descriptor) to create an offset, which is added to
9926 ///        the resource pointer.
9927 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
9928                                            SDValue Ptr, uint32_t RsrcDword1,
9929                                            uint64_t RsrcDword2And3) const {
9930   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
9931   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
9932   if (RsrcDword1) {
9933     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
9934                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
9935                     0);
9936   }
9937 
9938   SDValue DataLo = buildSMovImm32(DAG, DL,
9939                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
9940   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
9941 
9942   const SDValue Ops[] = {
9943     DAG.getTargetConstant(AMDGPU::SReg_128RegClassID, DL, MVT::i32),
9944     PtrLo,
9945     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
9946     PtrHi,
9947     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
9948     DataLo,
9949     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
9950     DataHi,
9951     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
9952   };
9953 
9954   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
9955 }
9956 
9957 //===----------------------------------------------------------------------===//
9958 //                         SI Inline Assembly Support
9959 //===----------------------------------------------------------------------===//
9960 
9961 std::pair<unsigned, const TargetRegisterClass *>
9962 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
9963                                                StringRef Constraint,
9964                                                MVT VT) const {
9965   const TargetRegisterClass *RC = nullptr;
9966   if (Constraint.size() == 1) {
9967     switch (Constraint[0]) {
9968     default:
9969       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
9970     case 's':
9971     case 'r':
9972       switch (VT.getSizeInBits()) {
9973       default:
9974         return std::make_pair(0U, nullptr);
9975       case 32:
9976       case 16:
9977         RC = &AMDGPU::SReg_32_XM0RegClass;
9978         break;
9979       case 64:
9980         RC = &AMDGPU::SGPR_64RegClass;
9981         break;
9982       case 96:
9983         RC = &AMDGPU::SReg_96RegClass;
9984         break;
9985       case 128:
9986         RC = &AMDGPU::SReg_128RegClass;
9987         break;
9988       case 160:
9989         RC = &AMDGPU::SReg_160RegClass;
9990         break;
9991       case 256:
9992         RC = &AMDGPU::SReg_256RegClass;
9993         break;
9994       case 512:
9995         RC = &AMDGPU::SReg_512RegClass;
9996         break;
9997       }
9998       break;
9999     case 'v':
10000       switch (VT.getSizeInBits()) {
10001       default:
10002         return std::make_pair(0U, nullptr);
10003       case 32:
10004       case 16:
10005         RC = &AMDGPU::VGPR_32RegClass;
10006         break;
10007       case 64:
10008         RC = &AMDGPU::VReg_64RegClass;
10009         break;
10010       case 96:
10011         RC = &AMDGPU::VReg_96RegClass;
10012         break;
10013       case 128:
10014         RC = &AMDGPU::VReg_128RegClass;
10015         break;
10016       case 160:
10017         RC = &AMDGPU::VReg_160RegClass;
10018         break;
10019       case 256:
10020         RC = &AMDGPU::VReg_256RegClass;
10021         break;
10022       case 512:
10023         RC = &AMDGPU::VReg_512RegClass;
10024         break;
10025       }
10026       break;
10027     }
10028     // We actually support i128, i16 and f16 as inline parameters
10029     // even if they are not reported as legal
10030     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
10031                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
10032       return std::make_pair(0U, RC);
10033   }
10034 
10035   if (Constraint.size() > 1) {
10036     if (Constraint[1] == 'v') {
10037       RC = &AMDGPU::VGPR_32RegClass;
10038     } else if (Constraint[1] == 's') {
10039       RC = &AMDGPU::SGPR_32RegClass;
10040     }
10041 
10042     if (RC) {
10043       uint32_t Idx;
10044       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
10045       if (!Failed && Idx < RC->getNumRegs())
10046         return std::make_pair(RC->getRegister(Idx), RC);
10047     }
10048   }
10049   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
10050 }
10051 
10052 SITargetLowering::ConstraintType
10053 SITargetLowering::getConstraintType(StringRef Constraint) const {
10054   if (Constraint.size() == 1) {
10055     switch (Constraint[0]) {
10056     default: break;
10057     case 's':
10058     case 'v':
10059       return C_RegisterClass;
10060     }
10061   }
10062   return TargetLowering::getConstraintType(Constraint);
10063 }
10064 
10065 // Figure out which registers should be reserved for stack access. Only after
10066 // the function is legalized do we know all of the non-spill stack objects or if
10067 // calls are present.
10068 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
10069   MachineRegisterInfo &MRI = MF.getRegInfo();
10070   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10071   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
10072   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10073 
10074   if (Info->isEntryFunction()) {
10075     // Callable functions have fixed registers used for stack access.
10076     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
10077   }
10078 
10079   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
10080                              Info->getStackPtrOffsetReg()));
10081   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
10082     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
10083 
10084   // We need to worry about replacing the default register with itself in case
10085   // of MIR testcases missing the MFI.
10086   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
10087     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
10088 
10089   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
10090     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
10091 
10092   if (Info->getScratchWaveOffsetReg() != AMDGPU::SCRATCH_WAVE_OFFSET_REG) {
10093     MRI.replaceRegWith(AMDGPU::SCRATCH_WAVE_OFFSET_REG,
10094                        Info->getScratchWaveOffsetReg());
10095   }
10096 
10097   Info->limitOccupancy(MF);
10098 
10099   if (ST.isWave32() && !MF.empty()) {
10100     // Add VCC_HI def because many instructions marked as imp-use VCC where
10101     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
10102     // having a use of undef.
10103 
10104     const SIInstrInfo *TII = ST.getInstrInfo();
10105     DebugLoc DL;
10106 
10107     MachineBasicBlock &MBB = MF.front();
10108     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
10109     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
10110 
10111     for (auto &MBB : MF) {
10112       for (auto &MI : MBB) {
10113         TII->fixImplicitOperands(MI);
10114       }
10115     }
10116   }
10117 
10118   TargetLoweringBase::finalizeLowering(MF);
10119 }
10120 
10121 void SITargetLowering::computeKnownBitsForFrameIndex(const SDValue Op,
10122                                                      KnownBits &Known,
10123                                                      const APInt &DemandedElts,
10124                                                      const SelectionDAG &DAG,
10125                                                      unsigned Depth) const {
10126   TargetLowering::computeKnownBitsForFrameIndex(Op, Known, DemandedElts,
10127                                                 DAG, Depth);
10128 
10129   // Set the high bits to zero based on the maximum allowed scratch size per
10130   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
10131   // calculation won't overflow, so assume the sign bit is never set.
10132   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
10133 }
10134 
10135 unsigned SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
10136   const unsigned PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
10137   const unsigned CacheLineAlign = 6; // log2(64)
10138 
10139   // Pre-GFX10 target did not benefit from loop alignment
10140   if (!ML || DisableLoopAlignment ||
10141       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
10142       getSubtarget()->hasInstFwdPrefetchBug())
10143     return PrefAlign;
10144 
10145   // On GFX10 I$ is 4 x 64 bytes cache lines.
10146   // By default prefetcher keeps one cache line behind and reads two ahead.
10147   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
10148   // behind and one ahead.
10149   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
10150   // If loop fits 64 bytes it always spans no more than two cache lines and
10151   // does not need an alignment.
10152   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
10153   // Else if loop is less or equal 192 bytes we need two lines behind.
10154 
10155   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10156   const MachineBasicBlock *Header = ML->getHeader();
10157   if (Header->getAlignment() != PrefAlign)
10158     return Header->getAlignment(); // Already processed.
10159 
10160   unsigned LoopSize = 0;
10161   for (const MachineBasicBlock *MBB : ML->blocks()) {
10162     // If inner loop block is aligned assume in average half of the alignment
10163     // size to be added as nops.
10164     if (MBB != Header)
10165       LoopSize += (1 << MBB->getAlignment()) / 2;
10166 
10167     for (const MachineInstr &MI : *MBB) {
10168       LoopSize += TII->getInstSizeInBytes(MI);
10169       if (LoopSize > 192)
10170         return PrefAlign;
10171     }
10172   }
10173 
10174   if (LoopSize <= 64)
10175     return PrefAlign;
10176 
10177   if (LoopSize <= 128)
10178     return CacheLineAlign;
10179 
10180   // If any of parent loops is surrounded by prefetch instructions do not
10181   // insert new for inner loop, which would reset parent's settings.
10182   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
10183     if (MachineBasicBlock *Exit = P->getExitBlock()) {
10184       auto I = Exit->getFirstNonDebugInstr();
10185       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
10186         return CacheLineAlign;
10187     }
10188   }
10189 
10190   MachineBasicBlock *Pre = ML->getLoopPreheader();
10191   MachineBasicBlock *Exit = ML->getExitBlock();
10192 
10193   if (Pre && Exit) {
10194     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
10195             TII->get(AMDGPU::S_INST_PREFETCH))
10196       .addImm(1); // prefetch 2 lines behind PC
10197 
10198     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
10199             TII->get(AMDGPU::S_INST_PREFETCH))
10200       .addImm(2); // prefetch 1 line behind PC
10201   }
10202 
10203   return CacheLineAlign;
10204 }
10205 
10206 LLVM_ATTRIBUTE_UNUSED
10207 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
10208   assert(N->getOpcode() == ISD::CopyFromReg);
10209   do {
10210     // Follow the chain until we find an INLINEASM node.
10211     N = N->getOperand(0).getNode();
10212     if (N->getOpcode() == ISD::INLINEASM ||
10213         N->getOpcode() == ISD::INLINEASM_BR)
10214       return true;
10215   } while (N->getOpcode() == ISD::CopyFromReg);
10216   return false;
10217 }
10218 
10219 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
10220   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
10221 {
10222   switch (N->getOpcode()) {
10223     case ISD::CopyFromReg:
10224     {
10225       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
10226       const MachineFunction * MF = FLI->MF;
10227       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
10228       const MachineRegisterInfo &MRI = MF->getRegInfo();
10229       const SIRegisterInfo &TRI = ST.getInstrInfo()->getRegisterInfo();
10230       unsigned Reg = R->getReg();
10231       if (TRI.isPhysicalRegister(Reg))
10232         return !TRI.isSGPRReg(MRI, Reg);
10233 
10234       if (MRI.isLiveIn(Reg)) {
10235         // workitem.id.x workitem.id.y workitem.id.z
10236         // Any VGPR formal argument is also considered divergent
10237         if (!TRI.isSGPRReg(MRI, Reg))
10238           return true;
10239         // Formal arguments of non-entry functions
10240         // are conservatively considered divergent
10241         else if (!AMDGPU::isEntryFunctionCC(FLI->Fn->getCallingConv()))
10242           return true;
10243         return false;
10244       }
10245       const Value *V = FLI->getValueFromVirtualReg(Reg);
10246       if (V)
10247         return KDA->isDivergent(V);
10248       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
10249       return !TRI.isSGPRReg(MRI, Reg);
10250     }
10251     break;
10252     case ISD::LOAD: {
10253       const LoadSDNode *L = cast<LoadSDNode>(N);
10254       unsigned AS = L->getAddressSpace();
10255       // A flat load may access private memory.
10256       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
10257     } break;
10258     case ISD::CALLSEQ_END:
10259     return true;
10260     break;
10261     case ISD::INTRINSIC_WO_CHAIN:
10262     {
10263 
10264     }
10265       return AMDGPU::isIntrinsicSourceOfDivergence(
10266       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
10267     case ISD::INTRINSIC_W_CHAIN:
10268       return AMDGPU::isIntrinsicSourceOfDivergence(
10269       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
10270     // In some cases intrinsics that are a source of divergence have been
10271     // lowered to AMDGPUISD so we also need to check those too.
10272     case AMDGPUISD::INTERP_MOV:
10273     case AMDGPUISD::INTERP_P1:
10274     case AMDGPUISD::INTERP_P2:
10275       return true;
10276   }
10277   return false;
10278 }
10279 
10280 bool SITargetLowering::denormalsEnabledForType(EVT VT) const {
10281   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
10282   case MVT::f32:
10283     return Subtarget->hasFP32Denormals();
10284   case MVT::f64:
10285     return Subtarget->hasFP64Denormals();
10286   case MVT::f16:
10287     return Subtarget->hasFP16Denormals();
10288   default:
10289     return false;
10290   }
10291 }
10292 
10293 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
10294                                                     const SelectionDAG &DAG,
10295                                                     bool SNaN,
10296                                                     unsigned Depth) const {
10297   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
10298     const MachineFunction &MF = DAG.getMachineFunction();
10299     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
10300 
10301     if (Info->getMode().DX10Clamp)
10302       return true; // Clamped to 0.
10303     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
10304   }
10305 
10306   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
10307                                                             SNaN, Depth);
10308 }
10309 
10310 TargetLowering::AtomicExpansionKind
10311 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
10312   switch (RMW->getOperation()) {
10313   case AtomicRMWInst::FAdd: {
10314     Type *Ty = RMW->getType();
10315 
10316     // We don't have a way to support 16-bit atomics now, so just leave them
10317     // as-is.
10318     if (Ty->isHalfTy())
10319       return AtomicExpansionKind::None;
10320 
10321     if (!Ty->isFloatTy())
10322       return AtomicExpansionKind::CmpXChg;
10323 
10324     // TODO: Do have these for flat. Older targets also had them for buffers.
10325     unsigned AS = RMW->getPointerAddressSpace();
10326     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
10327       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
10328   }
10329   default:
10330     break;
10331   }
10332 
10333   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
10334 }
10335