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 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUSubtarget.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
19 #include "SIDefines.h"
20 #include "SIInstrInfo.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "SIRegisterInfo.h"
23 #include "Utils/AMDGPUBaseInfo.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/DAGCombine.h"
37 #include "llvm/CodeGen/ISDOpcodes.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstr.h"
42 #include "llvm/CodeGen/MachineInstrBuilder.h"
43 #include "llvm/CodeGen/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachineMemOperand.h"
45 #include "llvm/CodeGen/MachineModuleInfo.h"
46 #include "llvm/CodeGen/MachineOperand.h"
47 #include "llvm/CodeGen/MachineRegisterInfo.h"
48 #include "llvm/CodeGen/SelectionDAG.h"
49 #include "llvm/CodeGen/SelectionDAGNodes.h"
50 #include "llvm/CodeGen/TargetCallingConv.h"
51 #include "llvm/CodeGen/TargetRegisterInfo.h"
52 #include "llvm/CodeGen/ValueTypes.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/DebugLoc.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/DiagnosticInfo.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/GlobalValue.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Type.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/CodeGen.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/KnownBits.h"
71 #include "llvm/Support/MachineValueType.h"
72 #include "llvm/Support/MathExtras.h"
73 #include "llvm/Target/TargetOptions.h"
74 #include <cassert>
75 #include <cmath>
76 #include <cstdint>
77 #include <iterator>
78 #include <tuple>
79 #include <utility>
80 #include <vector>
81 
82 using namespace llvm;
83 
84 #define DEBUG_TYPE "si-lower"
85 
86 STATISTIC(NumTailCalls, "Number of tail calls");
87 
88 static cl::opt<bool> DisableLoopAlignment(
89   "amdgpu-disable-loop-alignment",
90   cl::desc("Do not align and prefetch loops"),
91   cl::init(false));
92 
93 static cl::opt<bool> VGPRReserveforSGPRSpill(
94     "amdgpu-reserve-vgpr-for-sgpr-spill",
95     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
96 
97 static cl::opt<bool> UseDivergentRegisterIndexing(
98   "amdgpu-use-divergent-register-indexing",
99   cl::Hidden,
100   cl::desc("Use indirect register addressing for divergent indexes"),
101   cl::init(false));
102 
103 static bool hasFP32Denormals(const MachineFunction &MF) {
104   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
105   return Info->getMode().allFP32Denormals();
106 }
107 
108 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
109   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
110   return Info->getMode().allFP64FP16Denormals();
111 }
112 
113 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
114   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
115   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
116     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
117       return AMDGPU::SGPR0 + Reg;
118     }
119   }
120   llvm_unreachable("Cannot allocate sgpr");
121 }
122 
123 SITargetLowering::SITargetLowering(const TargetMachine &TM,
124                                    const GCNSubtarget &STI)
125     : AMDGPUTargetLowering(TM, STI),
126       Subtarget(&STI) {
127   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
128   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
129 
130   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
131   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
132 
133   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
134   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
135   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
136 
137   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
138   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
139 
140   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
141   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
142 
143   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
144   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
145 
146   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
147   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
148 
149   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
150   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
151 
152   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
153   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
154 
155   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
156   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
157 
158   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
159   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
160 
161   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
162   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
163 
164   if (Subtarget->has16BitInsts()) {
165     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
166     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
167 
168     // Unless there are also VOP3P operations, not operations are really legal.
169     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
170     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
171     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
172     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
173   }
174 
175   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
176   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
177 
178   computeRegisterProperties(Subtarget->getRegisterInfo());
179 
180   // The boolean content concept here is too inflexible. Compares only ever
181   // really produce a 1-bit result. Any copy/extend from these will turn into a
182   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
183   // it's what most targets use.
184   setBooleanContents(ZeroOrOneBooleanContent);
185   setBooleanVectorContents(ZeroOrOneBooleanContent);
186 
187   // We need to custom lower vector stores from local memory
188   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
189   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
190   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::i1, Custom);
195   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
196 
197   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
198   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
199   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
202   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
203   setOperationAction(ISD::STORE, MVT::i1, Custom);
204   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
205 
206   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
207   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
208   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
209   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
210   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
211   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
212   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
213   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
214   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
215   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
216   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
217   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
218   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
219   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
220   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
221   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
222 
223   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
224   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
225   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
226   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
227   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
228 
229   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
230   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
231 
232   setOperationAction(ISD::SELECT, MVT::i1, Promote);
233   setOperationAction(ISD::SELECT, MVT::i64, Custom);
234   setOperationAction(ISD::SELECT, MVT::f64, Promote);
235   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
236 
237   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
238   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
239   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
241   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
242 
243   setOperationAction(ISD::SETCC, MVT::i1, Promote);
244   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
245   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
246   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
247 
248   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
249   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
250   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
251   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
252   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
253   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
254   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
255   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
256 
257   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
258   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
265 
266   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
267   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
268   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
269   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
270   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
271   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
272 
273   setOperationAction(ISD::UADDO, MVT::i32, Legal);
274   setOperationAction(ISD::USUBO, MVT::i32, Legal);
275 
276   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
277   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
278 
279   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
280   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
281   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
282 
283 #if 0
284   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
285   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
286 #endif
287 
288   // We only support LOAD/STORE and vector manipulation ops for vectors
289   // with > 4 elements.
290   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
291                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
292                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
293                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
294     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
295       switch (Op) {
296       case ISD::LOAD:
297       case ISD::STORE:
298       case ISD::BUILD_VECTOR:
299       case ISD::BITCAST:
300       case ISD::EXTRACT_VECTOR_ELT:
301       case ISD::INSERT_VECTOR_ELT:
302       case ISD::INSERT_SUBVECTOR:
303       case ISD::EXTRACT_SUBVECTOR:
304       case ISD::SCALAR_TO_VECTOR:
305         break;
306       case ISD::CONCAT_VECTORS:
307         setOperationAction(Op, VT, Custom);
308         break;
309       default:
310         setOperationAction(Op, VT, Expand);
311         break;
312       }
313     }
314   }
315 
316   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
317 
318   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
319   // is expanded to avoid having two separate loops in case the index is a VGPR.
320 
321   // Most operations are naturally 32-bit vector operations. We only support
322   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
323   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
324     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
325     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
326 
327     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
328     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
329 
330     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
331     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
332 
333     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
334     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
335   }
336 
337   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
338     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
339     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
340 
341     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
342     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
343 
344     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
345     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
346 
347     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
348     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
349   }
350 
351   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
352     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
353     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
354 
355     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
356     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
357 
358     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
359     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
360 
361     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
362     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
363   }
364 
365   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
366     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
367     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
368 
369     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
370     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
371 
372     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
373     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
374 
375     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
376     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
377   }
378 
379   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
380   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
382   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
383 
384   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
385   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
386 
387   // Avoid stack access for these.
388   // TODO: Generalize to more vector types.
389   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
390   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
393 
394   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
395   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
399 
400   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
403 
404   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
405   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
406   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
407   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
408 
409   // Deal with vec3 vector operations when widened to vec4.
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
414 
415   // Deal with vec5 vector operations when widened to vec8.
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
419   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
420 
421   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
422   // and output demarshalling
423   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
424   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
425 
426   // We can't return success/failure, only the old value,
427   // let LLVM add the comparison
428   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
429   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
430 
431   if (Subtarget->hasFlatAddressSpace()) {
432     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
433     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
434   }
435 
436   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
437 
438   // FIXME: This should be narrowed to i32, but that only happens if i64 is
439   // illegal.
440   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
441   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
442   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
443 
444   // On SI this is s_memtime and s_memrealtime on VI.
445   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
446   setOperationAction(ISD::TRAP, MVT::Other, Custom);
447   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
448 
449   if (Subtarget->has16BitInsts()) {
450     setOperationAction(ISD::FPOW, MVT::f16, Promote);
451     setOperationAction(ISD::FLOG, MVT::f16, Custom);
452     setOperationAction(ISD::FEXP, MVT::f16, Custom);
453     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
454   }
455 
456   if (Subtarget->hasMadMacF32Insts())
457     setOperationAction(ISD::FMAD, MVT::f32, Legal);
458 
459   if (!Subtarget->hasBFI()) {
460     // fcopysign can be done in a single instruction with BFI.
461     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
462     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
463   }
464 
465   if (!Subtarget->hasBCNT(32))
466     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
467 
468   if (!Subtarget->hasBCNT(64))
469     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
470 
471   if (Subtarget->hasFFBH())
472     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
473 
474   if (Subtarget->hasFFBL())
475     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
476 
477   // We only really have 32-bit BFE instructions (and 16-bit on VI).
478   //
479   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
480   // effort to match them now. We want this to be false for i64 cases when the
481   // extraction isn't restricted to the upper or lower half. Ideally we would
482   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
483   // span the midpoint are probably relatively rare, so don't worry about them
484   // for now.
485   if (Subtarget->hasBFE())
486     setHasExtractBitsInsn(true);
487 
488   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
489   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
490   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
491   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
492 
493 
494   // These are really only legal for ieee_mode functions. We should be avoiding
495   // them for functions that don't have ieee_mode enabled, so just say they are
496   // legal.
497   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
498   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
499   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
500   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
501 
502 
503   if (Subtarget->haveRoundOpsF64()) {
504     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
505     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
506     setOperationAction(ISD::FRINT, MVT::f64, Legal);
507   } else {
508     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
509     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
510     setOperationAction(ISD::FRINT, MVT::f64, Custom);
511     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
512   }
513 
514   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
515 
516   setOperationAction(ISD::FSIN, MVT::f32, Custom);
517   setOperationAction(ISD::FCOS, MVT::f32, Custom);
518   setOperationAction(ISD::FDIV, MVT::f32, Custom);
519   setOperationAction(ISD::FDIV, MVT::f64, Custom);
520 
521   if (Subtarget->has16BitInsts()) {
522     setOperationAction(ISD::Constant, MVT::i16, Legal);
523 
524     setOperationAction(ISD::SMIN, MVT::i16, Legal);
525     setOperationAction(ISD::SMAX, MVT::i16, Legal);
526 
527     setOperationAction(ISD::UMIN, MVT::i16, Legal);
528     setOperationAction(ISD::UMAX, MVT::i16, Legal);
529 
530     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
531     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
532 
533     setOperationAction(ISD::ROTR, MVT::i16, Promote);
534     setOperationAction(ISD::ROTL, MVT::i16, Promote);
535 
536     setOperationAction(ISD::SDIV, MVT::i16, Promote);
537     setOperationAction(ISD::UDIV, MVT::i16, Promote);
538     setOperationAction(ISD::SREM, MVT::i16, Promote);
539     setOperationAction(ISD::UREM, MVT::i16, Promote);
540 
541     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
542 
543     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
544     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
545     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
546     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
547     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
548 
549     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
550 
551     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
552 
553     setOperationAction(ISD::LOAD, MVT::i16, Custom);
554 
555     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
556 
557     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
558     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
559     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
560     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
561 
562     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
563     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
564 
565     // F16 - Constant Actions.
566     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
567 
568     // F16 - Load/Store Actions.
569     setOperationAction(ISD::LOAD, MVT::f16, Promote);
570     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
571     setOperationAction(ISD::STORE, MVT::f16, Promote);
572     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
573 
574     // F16 - VOP1 Actions.
575     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
576     setOperationAction(ISD::FCOS, MVT::f16, Custom);
577     setOperationAction(ISD::FSIN, MVT::f16, Custom);
578 
579     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
580     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
581 
582     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
583     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
584     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
585     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
586     setOperationAction(ISD::FROUND, MVT::f16, Custom);
587 
588     // F16 - VOP2 Actions.
589     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
590     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
591 
592     setOperationAction(ISD::FDIV, MVT::f16, Custom);
593 
594     // F16 - VOP3 Actions.
595     setOperationAction(ISD::FMA, MVT::f16, Legal);
596     if (STI.hasMadF16())
597       setOperationAction(ISD::FMAD, MVT::f16, Legal);
598 
599     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
600       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
601         switch (Op) {
602         case ISD::LOAD:
603         case ISD::STORE:
604         case ISD::BUILD_VECTOR:
605         case ISD::BITCAST:
606         case ISD::EXTRACT_VECTOR_ELT:
607         case ISD::INSERT_VECTOR_ELT:
608         case ISD::INSERT_SUBVECTOR:
609         case ISD::EXTRACT_SUBVECTOR:
610         case ISD::SCALAR_TO_VECTOR:
611           break;
612         case ISD::CONCAT_VECTORS:
613           setOperationAction(Op, VT, Custom);
614           break;
615         default:
616           setOperationAction(Op, VT, Expand);
617           break;
618         }
619       }
620     }
621 
622     // v_perm_b32 can handle either of these.
623     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
624     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
625     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
626 
627     // XXX - Do these do anything? Vector constants turn into build_vector.
628     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
629     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
630 
631     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
632     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
633 
634     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
635     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
636     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
637     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
638 
639     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
640     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
641     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
642     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
643 
644     setOperationAction(ISD::AND, MVT::v2i16, Promote);
645     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
646     setOperationAction(ISD::OR, MVT::v2i16, Promote);
647     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
648     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
649     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
650 
651     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
652     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
653     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
654     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
655 
656     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
657     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
658     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
659     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
660 
661     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
662     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
663     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
664     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
665 
666     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
667     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
668     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
669 
670     if (!Subtarget->hasVOP3PInsts()) {
671       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
672       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
673     }
674 
675     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
676     // This isn't really legal, but this avoids the legalizer unrolling it (and
677     // allows matching fneg (fabs x) patterns)
678     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
679 
680     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
681     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
682     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
683     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
684 
685     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
686     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
687 
688     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
689     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
690   }
691 
692   if (Subtarget->hasVOP3PInsts()) {
693     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
694     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
695     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
696     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
697     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
698     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
699     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
700     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
701     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
702     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
703 
704     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
705     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
706     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
707 
708     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
709     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
710 
711     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
712 
713     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
714     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
715 
716     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
717     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
718 
719     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
720     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
721     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
722     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
723     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
724     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
725 
726     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
727     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
728     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
729     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
730 
731     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
732     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
733     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
734 
735     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
736     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
737 
738     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
739     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
740     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
741 
742     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
743     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
744     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
745   }
746 
747   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
748   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
749 
750   if (Subtarget->has16BitInsts()) {
751     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
752     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
753     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
754     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
755   } else {
756     // Legalization hack.
757     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
758     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
759 
760     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
761     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
762   }
763 
764   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
765     setOperationAction(ISD::SELECT, VT, Custom);
766   }
767 
768   setOperationAction(ISD::SMULO, MVT::i64, Custom);
769   setOperationAction(ISD::UMULO, MVT::i64, Custom);
770 
771   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
772   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
773   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
774   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
775   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
776   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
777   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
778 
779   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
780   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
781   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
782   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
783   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
784   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
785   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
786   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
787   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
788 
789   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
790   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
791   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
792   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
793   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
794   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
795   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
796   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
797 
798   setTargetDAGCombine(ISD::ADD);
799   setTargetDAGCombine(ISD::ADDCARRY);
800   setTargetDAGCombine(ISD::SUB);
801   setTargetDAGCombine(ISD::SUBCARRY);
802   setTargetDAGCombine(ISD::FADD);
803   setTargetDAGCombine(ISD::FSUB);
804   setTargetDAGCombine(ISD::FMINNUM);
805   setTargetDAGCombine(ISD::FMAXNUM);
806   setTargetDAGCombine(ISD::FMINNUM_IEEE);
807   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
808   setTargetDAGCombine(ISD::FMA);
809   setTargetDAGCombine(ISD::SMIN);
810   setTargetDAGCombine(ISD::SMAX);
811   setTargetDAGCombine(ISD::UMIN);
812   setTargetDAGCombine(ISD::UMAX);
813   setTargetDAGCombine(ISD::SETCC);
814   setTargetDAGCombine(ISD::AND);
815   setTargetDAGCombine(ISD::OR);
816   setTargetDAGCombine(ISD::XOR);
817   setTargetDAGCombine(ISD::SINT_TO_FP);
818   setTargetDAGCombine(ISD::UINT_TO_FP);
819   setTargetDAGCombine(ISD::FCANONICALIZE);
820   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
821   setTargetDAGCombine(ISD::ZERO_EXTEND);
822   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
823   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
824   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
825 
826   // All memory operations. Some folding on the pointer operand is done to help
827   // matching the constant offsets in the addressing modes.
828   setTargetDAGCombine(ISD::LOAD);
829   setTargetDAGCombine(ISD::STORE);
830   setTargetDAGCombine(ISD::ATOMIC_LOAD);
831   setTargetDAGCombine(ISD::ATOMIC_STORE);
832   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
833   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
834   setTargetDAGCombine(ISD::ATOMIC_SWAP);
835   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
836   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
837   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
838   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
839   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
840   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
841   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
842   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
843   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
844   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
845   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
846 
847   // FIXME: In other contexts we pretend this is a per-function property.
848   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
849 
850   setSchedulingPreference(Sched::RegPressure);
851 }
852 
853 const GCNSubtarget *SITargetLowering::getSubtarget() const {
854   return Subtarget;
855 }
856 
857 //===----------------------------------------------------------------------===//
858 // TargetLowering queries
859 //===----------------------------------------------------------------------===//
860 
861 // v_mad_mix* support a conversion from f16 to f32.
862 //
863 // There is only one special case when denormals are enabled we don't currently,
864 // where this is OK to use.
865 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
866                                        EVT DestVT, EVT SrcVT) const {
867   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
868           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
869     DestVT.getScalarType() == MVT::f32 &&
870     SrcVT.getScalarType() == MVT::f16 &&
871     // TODO: This probably only requires no input flushing?
872     !hasFP32Denormals(DAG.getMachineFunction());
873 }
874 
875 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
876   // SI has some legal vector types, but no legal vector operations. Say no
877   // shuffles are legal in order to prefer scalarizing some vector operations.
878   return false;
879 }
880 
881 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
882                                                     CallingConv::ID CC,
883                                                     EVT VT) const {
884   if (CC == CallingConv::AMDGPU_KERNEL)
885     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
886 
887   if (VT.isVector()) {
888     EVT ScalarVT = VT.getScalarType();
889     unsigned Size = ScalarVT.getSizeInBits();
890     if (Size == 32)
891       return ScalarVT.getSimpleVT();
892 
893     if (Size > 32)
894       return MVT::i32;
895 
896     if (Size == 16 && Subtarget->has16BitInsts())
897       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
898   } else if (VT.getSizeInBits() > 32)
899     return MVT::i32;
900 
901   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
902 }
903 
904 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
905                                                          CallingConv::ID CC,
906                                                          EVT VT) const {
907   if (CC == CallingConv::AMDGPU_KERNEL)
908     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
909 
910   if (VT.isVector()) {
911     unsigned NumElts = VT.getVectorNumElements();
912     EVT ScalarVT = VT.getScalarType();
913     unsigned Size = ScalarVT.getSizeInBits();
914 
915     if (Size == 32)
916       return NumElts;
917 
918     if (Size > 32)
919       return NumElts * ((Size + 31) / 32);
920 
921     if (Size == 16 && Subtarget->has16BitInsts())
922       return (NumElts + 1) / 2;
923   } else if (VT.getSizeInBits() > 32)
924     return (VT.getSizeInBits() + 31) / 32;
925 
926   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
927 }
928 
929 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
930   LLVMContext &Context, CallingConv::ID CC,
931   EVT VT, EVT &IntermediateVT,
932   unsigned &NumIntermediates, MVT &RegisterVT) const {
933   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
934     unsigned NumElts = VT.getVectorNumElements();
935     EVT ScalarVT = VT.getScalarType();
936     unsigned Size = ScalarVT.getSizeInBits();
937     if (Size == 32) {
938       RegisterVT = ScalarVT.getSimpleVT();
939       IntermediateVT = RegisterVT;
940       NumIntermediates = NumElts;
941       return NumIntermediates;
942     }
943 
944     if (Size > 32) {
945       RegisterVT = MVT::i32;
946       IntermediateVT = RegisterVT;
947       NumIntermediates = NumElts * ((Size + 31) / 32);
948       return NumIntermediates;
949     }
950 
951     // FIXME: We should fix the ABI to be the same on targets without 16-bit
952     // support, but unless we can properly handle 3-vectors, it will be still be
953     // inconsistent.
954     if (Size == 16 && Subtarget->has16BitInsts()) {
955       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
956       IntermediateVT = RegisterVT;
957       NumIntermediates = (NumElts + 1) / 2;
958       return NumIntermediates;
959     }
960   }
961 
962   return TargetLowering::getVectorTypeBreakdownForCallingConv(
963     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
964 }
965 
966 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
967   assert(DMaskLanes != 0);
968 
969   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
970     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
971     return EVT::getVectorVT(Ty->getContext(),
972                             EVT::getEVT(VT->getElementType()),
973                             NumElts);
974   }
975 
976   return EVT::getEVT(Ty);
977 }
978 
979 // Peek through TFE struct returns to only use the data size.
980 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
981   auto *ST = dyn_cast<StructType>(Ty);
982   if (!ST)
983     return memVTFromImageData(Ty, DMaskLanes);
984 
985   // Some intrinsics return an aggregate type - special case to work out the
986   // correct memVT.
987   //
988   // Only limited forms of aggregate type currently expected.
989   if (ST->getNumContainedTypes() != 2 ||
990       !ST->getContainedType(1)->isIntegerTy(32))
991     return EVT();
992   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
993 }
994 
995 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
996                                           const CallInst &CI,
997                                           MachineFunction &MF,
998                                           unsigned IntrID) const {
999   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1000           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1001     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1002                                                   (Intrinsic::ID)IntrID);
1003     if (Attr.hasFnAttribute(Attribute::ReadNone))
1004       return false;
1005 
1006     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1007 
1008     if (RsrcIntr->IsImage) {
1009       Info.ptrVal = MFI->getImagePSV(
1010         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1011         CI.getArgOperand(RsrcIntr->RsrcArg));
1012       Info.align.reset();
1013     } else {
1014       Info.ptrVal = MFI->getBufferPSV(
1015         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1016         CI.getArgOperand(RsrcIntr->RsrcArg));
1017     }
1018 
1019     Info.flags = MachineMemOperand::MODereferenceable;
1020     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1021       unsigned DMaskLanes = 4;
1022 
1023       if (RsrcIntr->IsImage) {
1024         const AMDGPU::ImageDimIntrinsicInfo *Intr
1025           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1026         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1027           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1028 
1029         if (!BaseOpcode->Gather4) {
1030           // If this isn't a gather, we may have excess loaded elements in the
1031           // IR type. Check the dmask for the real number of elements loaded.
1032           unsigned DMask
1033             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1034           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1035         }
1036 
1037         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1038       } else
1039         Info.memVT = EVT::getEVT(CI.getType());
1040 
1041       // FIXME: What does alignment mean for an image?
1042       Info.opc = ISD::INTRINSIC_W_CHAIN;
1043       Info.flags |= MachineMemOperand::MOLoad;
1044     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1045       Info.opc = ISD::INTRINSIC_VOID;
1046 
1047       Type *DataTy = CI.getArgOperand(0)->getType();
1048       if (RsrcIntr->IsImage) {
1049         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1050         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1051         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1052       } else
1053         Info.memVT = EVT::getEVT(DataTy);
1054 
1055       Info.flags |= MachineMemOperand::MOStore;
1056     } else {
1057       // Atomic
1058       Info.opc = ISD::INTRINSIC_W_CHAIN;
1059       Info.memVT = MVT::getVT(CI.getType());
1060       Info.flags = MachineMemOperand::MOLoad |
1061                    MachineMemOperand::MOStore |
1062                    MachineMemOperand::MODereferenceable;
1063 
1064       // XXX - Should this be volatile without known ordering?
1065       Info.flags |= MachineMemOperand::MOVolatile;
1066     }
1067     return true;
1068   }
1069 
1070   switch (IntrID) {
1071   case Intrinsic::amdgcn_atomic_inc:
1072   case Intrinsic::amdgcn_atomic_dec:
1073   case Intrinsic::amdgcn_ds_ordered_add:
1074   case Intrinsic::amdgcn_ds_ordered_swap:
1075   case Intrinsic::amdgcn_ds_fadd:
1076   case Intrinsic::amdgcn_ds_fmin:
1077   case Intrinsic::amdgcn_ds_fmax: {
1078     Info.opc = ISD::INTRINSIC_W_CHAIN;
1079     Info.memVT = MVT::getVT(CI.getType());
1080     Info.ptrVal = CI.getOperand(0);
1081     Info.align.reset();
1082     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1083 
1084     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1085     if (!Vol->isZero())
1086       Info.flags |= MachineMemOperand::MOVolatile;
1087 
1088     return true;
1089   }
1090   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1091     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1092 
1093     Info.opc = ISD::INTRINSIC_VOID;
1094     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1095     Info.ptrVal = MFI->getBufferPSV(
1096       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1097       CI.getArgOperand(1));
1098     Info.align.reset();
1099     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1100 
1101     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1102     if (!Vol || !Vol->isZero())
1103       Info.flags |= MachineMemOperand::MOVolatile;
1104 
1105     return true;
1106   }
1107   case Intrinsic::amdgcn_global_atomic_fadd: {
1108     Info.opc = ISD::INTRINSIC_VOID;
1109     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1110                             ->getPointerElementType());
1111     Info.ptrVal = CI.getOperand(0);
1112     Info.align.reset();
1113     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1114 
1115     return true;
1116   }
1117   case Intrinsic::amdgcn_ds_append:
1118   case Intrinsic::amdgcn_ds_consume: {
1119     Info.opc = ISD::INTRINSIC_W_CHAIN;
1120     Info.memVT = MVT::getVT(CI.getType());
1121     Info.ptrVal = CI.getOperand(0);
1122     Info.align.reset();
1123     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1124 
1125     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1126     if (!Vol->isZero())
1127       Info.flags |= MachineMemOperand::MOVolatile;
1128 
1129     return true;
1130   }
1131   case Intrinsic::amdgcn_global_atomic_csub: {
1132     Info.opc = ISD::INTRINSIC_W_CHAIN;
1133     Info.memVT = MVT::getVT(CI.getType());
1134     Info.ptrVal = CI.getOperand(0);
1135     Info.align.reset();
1136     Info.flags = MachineMemOperand::MOLoad |
1137                  MachineMemOperand::MOStore |
1138                  MachineMemOperand::MODereferenceable |
1139                  MachineMemOperand::MOVolatile;
1140     return true;
1141   }
1142   case Intrinsic::amdgcn_ds_gws_init:
1143   case Intrinsic::amdgcn_ds_gws_barrier:
1144   case Intrinsic::amdgcn_ds_gws_sema_v:
1145   case Intrinsic::amdgcn_ds_gws_sema_br:
1146   case Intrinsic::amdgcn_ds_gws_sema_p:
1147   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1148     Info.opc = ISD::INTRINSIC_VOID;
1149 
1150     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1151     Info.ptrVal =
1152         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1153 
1154     // This is an abstract access, but we need to specify a type and size.
1155     Info.memVT = MVT::i32;
1156     Info.size = 4;
1157     Info.align = Align(4);
1158 
1159     Info.flags = MachineMemOperand::MOStore;
1160     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1161       Info.flags = MachineMemOperand::MOLoad;
1162     return true;
1163   }
1164   default:
1165     return false;
1166   }
1167 }
1168 
1169 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1170                                             SmallVectorImpl<Value*> &Ops,
1171                                             Type *&AccessTy) const {
1172   switch (II->getIntrinsicID()) {
1173   case Intrinsic::amdgcn_atomic_inc:
1174   case Intrinsic::amdgcn_atomic_dec:
1175   case Intrinsic::amdgcn_ds_ordered_add:
1176   case Intrinsic::amdgcn_ds_ordered_swap:
1177   case Intrinsic::amdgcn_ds_fadd:
1178   case Intrinsic::amdgcn_ds_fmin:
1179   case Intrinsic::amdgcn_ds_fmax: {
1180     Value *Ptr = II->getArgOperand(0);
1181     AccessTy = II->getType();
1182     Ops.push_back(Ptr);
1183     return true;
1184   }
1185   default:
1186     return false;
1187   }
1188 }
1189 
1190 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1191   if (!Subtarget->hasFlatInstOffsets()) {
1192     // Flat instructions do not have offsets, and only have the register
1193     // address.
1194     return AM.BaseOffs == 0 && AM.Scale == 0;
1195   }
1196 
1197   return AM.Scale == 0 &&
1198          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1199                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1200                                   /*Signed=*/false));
1201 }
1202 
1203 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1204   if (Subtarget->hasFlatGlobalInsts())
1205     return AM.Scale == 0 &&
1206            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1207                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1208                                     /*Signed=*/true));
1209 
1210   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1211       // Assume the we will use FLAT for all global memory accesses
1212       // on VI.
1213       // FIXME: This assumption is currently wrong.  On VI we still use
1214       // MUBUF instructions for the r + i addressing mode.  As currently
1215       // implemented, the MUBUF instructions only work on buffer < 4GB.
1216       // It may be possible to support > 4GB buffers with MUBUF instructions,
1217       // by setting the stride value in the resource descriptor which would
1218       // increase the size limit to (stride * 4GB).  However, this is risky,
1219       // because it has never been validated.
1220     return isLegalFlatAddressingMode(AM);
1221   }
1222 
1223   return isLegalMUBUFAddressingMode(AM);
1224 }
1225 
1226 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1227   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1228   // additionally can do r + r + i with addr64. 32-bit has more addressing
1229   // mode options. Depending on the resource constant, it can also do
1230   // (i64 r0) + (i32 r1) * (i14 i).
1231   //
1232   // Private arrays end up using a scratch buffer most of the time, so also
1233   // assume those use MUBUF instructions. Scratch loads / stores are currently
1234   // implemented as mubuf instructions with offen bit set, so slightly
1235   // different than the normal addr64.
1236   if (!isUInt<12>(AM.BaseOffs))
1237     return false;
1238 
1239   // FIXME: Since we can split immediate into soffset and immediate offset,
1240   // would it make sense to allow any immediate?
1241 
1242   switch (AM.Scale) {
1243   case 0: // r + i or just i, depending on HasBaseReg.
1244     return true;
1245   case 1:
1246     return true; // We have r + r or r + i.
1247   case 2:
1248     if (AM.HasBaseReg) {
1249       // Reject 2 * r + r.
1250       return false;
1251     }
1252 
1253     // Allow 2 * r as r + r
1254     // Or  2 * r + i is allowed as r + r + i.
1255     return true;
1256   default: // Don't allow n * r
1257     return false;
1258   }
1259 }
1260 
1261 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1262                                              const AddrMode &AM, Type *Ty,
1263                                              unsigned AS, Instruction *I) const {
1264   // No global is ever allowed as a base.
1265   if (AM.BaseGV)
1266     return false;
1267 
1268   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1269     return isLegalGlobalAddressingMode(AM);
1270 
1271   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1272       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1273       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1274     // If the offset isn't a multiple of 4, it probably isn't going to be
1275     // correctly aligned.
1276     // FIXME: Can we get the real alignment here?
1277     if (AM.BaseOffs % 4 != 0)
1278       return isLegalMUBUFAddressingMode(AM);
1279 
1280     // There are no SMRD extloads, so if we have to do a small type access we
1281     // will use a MUBUF load.
1282     // FIXME?: We also need to do this if unaligned, but we don't know the
1283     // alignment here.
1284     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1285       return isLegalGlobalAddressingMode(AM);
1286 
1287     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1288       // SMRD instructions have an 8-bit, dword offset on SI.
1289       if (!isUInt<8>(AM.BaseOffs / 4))
1290         return false;
1291     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1292       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1293       // in 8-bits, it can use a smaller encoding.
1294       if (!isUInt<32>(AM.BaseOffs / 4))
1295         return false;
1296     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1297       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1298       if (!isUInt<20>(AM.BaseOffs))
1299         return false;
1300     } else
1301       llvm_unreachable("unhandled generation");
1302 
1303     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1304       return true;
1305 
1306     if (AM.Scale == 1 && AM.HasBaseReg)
1307       return true;
1308 
1309     return false;
1310 
1311   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1312     return isLegalMUBUFAddressingMode(AM);
1313   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1314              AS == AMDGPUAS::REGION_ADDRESS) {
1315     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1316     // field.
1317     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1318     // an 8-bit dword offset but we don't know the alignment here.
1319     if (!isUInt<16>(AM.BaseOffs))
1320       return false;
1321 
1322     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1323       return true;
1324 
1325     if (AM.Scale == 1 && AM.HasBaseReg)
1326       return true;
1327 
1328     return false;
1329   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1330              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1331     // For an unknown address space, this usually means that this is for some
1332     // reason being used for pure arithmetic, and not based on some addressing
1333     // computation. We don't have instructions that compute pointers with any
1334     // addressing modes, so treat them as having no offset like flat
1335     // instructions.
1336     return isLegalFlatAddressingMode(AM);
1337   }
1338 
1339   // Assume a user alias of global for unknown address spaces.
1340   return isLegalGlobalAddressingMode(AM);
1341 }
1342 
1343 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1344                                         const SelectionDAG &DAG) const {
1345   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1346     return (MemVT.getSizeInBits() <= 4 * 32);
1347   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1348     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1349     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1350   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1351     return (MemVT.getSizeInBits() <= 2 * 32);
1352   }
1353   return true;
1354 }
1355 
1356 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1357     unsigned Size, unsigned AddrSpace, unsigned Align,
1358     MachineMemOperand::Flags Flags, bool *IsFast) const {
1359   if (IsFast)
1360     *IsFast = false;
1361 
1362   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1363       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1364     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1365     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1366     // with adjacent offsets.
1367     bool AlignedBy4 = (Align % 4 == 0);
1368     if (IsFast)
1369       *IsFast = AlignedBy4;
1370 
1371     return AlignedBy4;
1372   }
1373 
1374   // FIXME: We have to be conservative here and assume that flat operations
1375   // will access scratch.  If we had access to the IR function, then we
1376   // could determine if any private memory was used in the function.
1377   if (!Subtarget->hasUnalignedScratchAccess() &&
1378       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1379        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1380     bool AlignedBy4 = Align >= 4;
1381     if (IsFast)
1382       *IsFast = AlignedBy4;
1383 
1384     return AlignedBy4;
1385   }
1386 
1387   if (Subtarget->hasUnalignedBufferAccess()) {
1388     // If we have an uniform constant load, it still requires using a slow
1389     // buffer instruction if unaligned.
1390     if (IsFast) {
1391       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1392       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1393       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1394                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1395         Align >= 4 : Align != 2;
1396     }
1397 
1398     return true;
1399   }
1400 
1401   // Smaller than dword value must be aligned.
1402   if (Size < 32)
1403     return false;
1404 
1405   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1406   // byte-address are ignored, thus forcing Dword alignment.
1407   // This applies to private, global, and constant memory.
1408   if (IsFast)
1409     *IsFast = true;
1410 
1411   return Size >= 32 && Align >= 4;
1412 }
1413 
1414 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1415     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1416     bool *IsFast) const {
1417   if (IsFast)
1418     *IsFast = false;
1419 
1420   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1421   // which isn't a simple VT.
1422   // Until MVT is extended to handle this, simply check for the size and
1423   // rely on the condition below: allow accesses if the size is a multiple of 4.
1424   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1425                            VT.getStoreSize() > 16)) {
1426     return false;
1427   }
1428 
1429   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1430                                             Align, Flags, IsFast);
1431 }
1432 
1433 EVT SITargetLowering::getOptimalMemOpType(
1434     const MemOp &Op, const AttributeList &FuncAttributes) const {
1435   // FIXME: Should account for address space here.
1436 
1437   // The default fallback uses the private pointer size as a guess for a type to
1438   // use. Make sure we switch these to 64-bit accesses.
1439 
1440   if (Op.size() >= 16 &&
1441       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1442     return MVT::v4i32;
1443 
1444   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1445     return MVT::v2i32;
1446 
1447   // Use the default.
1448   return MVT::Other;
1449 }
1450 
1451 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1452                                            unsigned DestAS) const {
1453   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1454 }
1455 
1456 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1457   const MemSDNode *MemNode = cast<MemSDNode>(N);
1458   const Value *Ptr = MemNode->getMemOperand()->getValue();
1459   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1460   return I && I->getMetadata("amdgpu.noclobber");
1461 }
1462 
1463 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1464                                            unsigned DestAS) const {
1465   // Flat -> private/local is a simple truncate.
1466   // Flat -> global is no-op
1467   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1468     return true;
1469 
1470   return isNoopAddrSpaceCast(SrcAS, DestAS);
1471 }
1472 
1473 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1474   const MemSDNode *MemNode = cast<MemSDNode>(N);
1475 
1476   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1477 }
1478 
1479 TargetLoweringBase::LegalizeTypeAction
1480 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1481   int NumElts = VT.getVectorNumElements();
1482   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1483     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1484   return TargetLoweringBase::getPreferredVectorAction(VT);
1485 }
1486 
1487 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1488                                                          Type *Ty) const {
1489   // FIXME: Could be smarter if called for vector constants.
1490   return true;
1491 }
1492 
1493 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1494   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1495     switch (Op) {
1496     case ISD::LOAD:
1497     case ISD::STORE:
1498 
1499     // These operations are done with 32-bit instructions anyway.
1500     case ISD::AND:
1501     case ISD::OR:
1502     case ISD::XOR:
1503     case ISD::SELECT:
1504       // TODO: Extensions?
1505       return true;
1506     default:
1507       return false;
1508     }
1509   }
1510 
1511   // SimplifySetCC uses this function to determine whether or not it should
1512   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1513   if (VT == MVT::i1 && Op == ISD::SETCC)
1514     return false;
1515 
1516   return TargetLowering::isTypeDesirableForOp(Op, VT);
1517 }
1518 
1519 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1520                                                    const SDLoc &SL,
1521                                                    SDValue Chain,
1522                                                    uint64_t Offset) const {
1523   const DataLayout &DL = DAG.getDataLayout();
1524   MachineFunction &MF = DAG.getMachineFunction();
1525   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1526 
1527   const ArgDescriptor *InputPtrReg;
1528   const TargetRegisterClass *RC;
1529 
1530   std::tie(InputPtrReg, RC)
1531     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1532 
1533   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1534   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1535   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1536     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1537 
1538   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1539 }
1540 
1541 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1542                                             const SDLoc &SL) const {
1543   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1544                                                FIRST_IMPLICIT);
1545   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1546 }
1547 
1548 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1549                                          const SDLoc &SL, SDValue Val,
1550                                          bool Signed,
1551                                          const ISD::InputArg *Arg) const {
1552   // First, if it is a widened vector, narrow it.
1553   if (VT.isVector() &&
1554       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1555     EVT NarrowedVT =
1556         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1557                          VT.getVectorNumElements());
1558     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1559                       DAG.getConstant(0, SL, MVT::i32));
1560   }
1561 
1562   // Then convert the vector elements or scalar value.
1563   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1564       VT.bitsLT(MemVT)) {
1565     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1566     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1567   }
1568 
1569   if (MemVT.isFloatingPoint())
1570     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1571   else if (Signed)
1572     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1573   else
1574     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1575 
1576   return Val;
1577 }
1578 
1579 SDValue SITargetLowering::lowerKernargMemParameter(
1580   SelectionDAG &DAG, EVT VT, EVT MemVT,
1581   const SDLoc &SL, SDValue Chain,
1582   uint64_t Offset, unsigned Align, bool Signed,
1583   const ISD::InputArg *Arg) const {
1584   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1585 
1586   // Try to avoid using an extload by loading earlier than the argument address,
1587   // and extracting the relevant bits. The load should hopefully be merged with
1588   // the previous argument.
1589   if (MemVT.getStoreSize() < 4 && Align < 4) {
1590     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1591     int64_t AlignDownOffset = alignDown(Offset, 4);
1592     int64_t OffsetDiff = Offset - AlignDownOffset;
1593 
1594     EVT IntVT = MemVT.changeTypeToInteger();
1595 
1596     // TODO: If we passed in the base kernel offset we could have a better
1597     // alignment than 4, but we don't really need it.
1598     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1599     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1600                                MachineMemOperand::MODereferenceable |
1601                                MachineMemOperand::MOInvariant);
1602 
1603     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1604     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1605 
1606     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1607     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1608     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1609 
1610 
1611     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1612   }
1613 
1614   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1615   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1616                              MachineMemOperand::MODereferenceable |
1617                              MachineMemOperand::MOInvariant);
1618 
1619   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1620   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1621 }
1622 
1623 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1624                                               const SDLoc &SL, SDValue Chain,
1625                                               const ISD::InputArg &Arg) const {
1626   MachineFunction &MF = DAG.getMachineFunction();
1627   MachineFrameInfo &MFI = MF.getFrameInfo();
1628 
1629   if (Arg.Flags.isByVal()) {
1630     unsigned Size = Arg.Flags.getByValSize();
1631     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1632     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1633   }
1634 
1635   unsigned ArgOffset = VA.getLocMemOffset();
1636   unsigned ArgSize = VA.getValVT().getStoreSize();
1637 
1638   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1639 
1640   // Create load nodes to retrieve arguments from the stack.
1641   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1642   SDValue ArgValue;
1643 
1644   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1645   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1646   MVT MemVT = VA.getValVT();
1647 
1648   switch (VA.getLocInfo()) {
1649   default:
1650     break;
1651   case CCValAssign::BCvt:
1652     MemVT = VA.getLocVT();
1653     break;
1654   case CCValAssign::SExt:
1655     ExtType = ISD::SEXTLOAD;
1656     break;
1657   case CCValAssign::ZExt:
1658     ExtType = ISD::ZEXTLOAD;
1659     break;
1660   case CCValAssign::AExt:
1661     ExtType = ISD::EXTLOAD;
1662     break;
1663   }
1664 
1665   ArgValue = DAG.getExtLoad(
1666     ExtType, SL, VA.getLocVT(), Chain, FIN,
1667     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1668     MemVT);
1669   return ArgValue;
1670 }
1671 
1672 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1673   const SIMachineFunctionInfo &MFI,
1674   EVT VT,
1675   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1676   const ArgDescriptor *Reg;
1677   const TargetRegisterClass *RC;
1678 
1679   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1680   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1681 }
1682 
1683 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1684                                    CallingConv::ID CallConv,
1685                                    ArrayRef<ISD::InputArg> Ins,
1686                                    BitVector &Skipped,
1687                                    FunctionType *FType,
1688                                    SIMachineFunctionInfo *Info) {
1689   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1690     const ISD::InputArg *Arg = &Ins[I];
1691 
1692     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1693            "vector type argument should have been split");
1694 
1695     // First check if it's a PS input addr.
1696     if (CallConv == CallingConv::AMDGPU_PS &&
1697         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1698       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1699 
1700       // Inconveniently only the first part of the split is marked as isSplit,
1701       // so skip to the end. We only want to increment PSInputNum once for the
1702       // entire split argument.
1703       if (Arg->Flags.isSplit()) {
1704         while (!Arg->Flags.isSplitEnd()) {
1705           assert((!Arg->VT.isVector() ||
1706                   Arg->VT.getScalarSizeInBits() == 16) &&
1707                  "unexpected vector split in ps argument type");
1708           if (!SkipArg)
1709             Splits.push_back(*Arg);
1710           Arg = &Ins[++I];
1711         }
1712       }
1713 
1714       if (SkipArg) {
1715         // We can safely skip PS inputs.
1716         Skipped.set(Arg->getOrigArgIndex());
1717         ++PSInputNum;
1718         continue;
1719       }
1720 
1721       Info->markPSInputAllocated(PSInputNum);
1722       if (Arg->Used)
1723         Info->markPSInputEnabled(PSInputNum);
1724 
1725       ++PSInputNum;
1726     }
1727 
1728     Splits.push_back(*Arg);
1729   }
1730 }
1731 
1732 // Allocate special inputs passed in VGPRs.
1733 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1734                                                       MachineFunction &MF,
1735                                                       const SIRegisterInfo &TRI,
1736                                                       SIMachineFunctionInfo &Info) const {
1737   const LLT S32 = LLT::scalar(32);
1738   MachineRegisterInfo &MRI = MF.getRegInfo();
1739 
1740   if (Info.hasWorkItemIDX()) {
1741     Register Reg = AMDGPU::VGPR0;
1742     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1743 
1744     CCInfo.AllocateReg(Reg);
1745     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1746   }
1747 
1748   if (Info.hasWorkItemIDY()) {
1749     Register Reg = AMDGPU::VGPR1;
1750     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1751 
1752     CCInfo.AllocateReg(Reg);
1753     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1754   }
1755 
1756   if (Info.hasWorkItemIDZ()) {
1757     Register Reg = AMDGPU::VGPR2;
1758     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1759 
1760     CCInfo.AllocateReg(Reg);
1761     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1762   }
1763 }
1764 
1765 // Try to allocate a VGPR at the end of the argument list, or if no argument
1766 // VGPRs are left allocating a stack slot.
1767 // If \p Mask is is given it indicates bitfield position in the register.
1768 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1769 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1770                                          ArgDescriptor Arg = ArgDescriptor()) {
1771   if (Arg.isSet())
1772     return ArgDescriptor::createArg(Arg, Mask);
1773 
1774   ArrayRef<MCPhysReg> ArgVGPRs
1775     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1776   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1777   if (RegIdx == ArgVGPRs.size()) {
1778     // Spill to stack required.
1779     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1780 
1781     return ArgDescriptor::createStack(Offset, Mask);
1782   }
1783 
1784   unsigned Reg = ArgVGPRs[RegIdx];
1785   Reg = CCInfo.AllocateReg(Reg);
1786   assert(Reg != AMDGPU::NoRegister);
1787 
1788   MachineFunction &MF = CCInfo.getMachineFunction();
1789   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1790   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1791   return ArgDescriptor::createRegister(Reg, Mask);
1792 }
1793 
1794 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1795                                              const TargetRegisterClass *RC,
1796                                              unsigned NumArgRegs) {
1797   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1798   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1799   if (RegIdx == ArgSGPRs.size())
1800     report_fatal_error("ran out of SGPRs for arguments");
1801 
1802   unsigned Reg = ArgSGPRs[RegIdx];
1803   Reg = CCInfo.AllocateReg(Reg);
1804   assert(Reg != AMDGPU::NoRegister);
1805 
1806   MachineFunction &MF = CCInfo.getMachineFunction();
1807   MF.addLiveIn(Reg, RC);
1808   return ArgDescriptor::createRegister(Reg);
1809 }
1810 
1811 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1812   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1813 }
1814 
1815 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1816   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1817 }
1818 
1819 /// Allocate implicit function VGPR arguments at the end of allocated user
1820 /// arguments.
1821 void SITargetLowering::allocateSpecialInputVGPRs(
1822   CCState &CCInfo, MachineFunction &MF,
1823   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1824   const unsigned Mask = 0x3ff;
1825   ArgDescriptor Arg;
1826 
1827   if (Info.hasWorkItemIDX()) {
1828     Arg = allocateVGPR32Input(CCInfo, Mask);
1829     Info.setWorkItemIDX(Arg);
1830   }
1831 
1832   if (Info.hasWorkItemIDY()) {
1833     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1834     Info.setWorkItemIDY(Arg);
1835   }
1836 
1837   if (Info.hasWorkItemIDZ())
1838     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1839 }
1840 
1841 /// Allocate implicit function VGPR arguments in fixed registers.
1842 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1843   CCState &CCInfo, MachineFunction &MF,
1844   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1845   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1846   if (!Reg)
1847     report_fatal_error("failed to allocated VGPR for implicit arguments");
1848 
1849   const unsigned Mask = 0x3ff;
1850   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1851   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1852   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1853 }
1854 
1855 void SITargetLowering::allocateSpecialInputSGPRs(
1856   CCState &CCInfo,
1857   MachineFunction &MF,
1858   const SIRegisterInfo &TRI,
1859   SIMachineFunctionInfo &Info) const {
1860   auto &ArgInfo = Info.getArgInfo();
1861 
1862   // TODO: Unify handling with private memory pointers.
1863 
1864   if (Info.hasDispatchPtr())
1865     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1866 
1867   if (Info.hasQueuePtr())
1868     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1869 
1870   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1871   // constant offset from the kernarg segment.
1872   if (Info.hasImplicitArgPtr())
1873     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1874 
1875   if (Info.hasDispatchID())
1876     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1877 
1878   // flat_scratch_init is not applicable for non-kernel functions.
1879 
1880   if (Info.hasWorkGroupIDX())
1881     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1882 
1883   if (Info.hasWorkGroupIDY())
1884     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1885 
1886   if (Info.hasWorkGroupIDZ())
1887     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1888 }
1889 
1890 // Allocate special inputs passed in user SGPRs.
1891 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1892                                             MachineFunction &MF,
1893                                             const SIRegisterInfo &TRI,
1894                                             SIMachineFunctionInfo &Info) const {
1895   if (Info.hasImplicitBufferPtr()) {
1896     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1897     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1898     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1899   }
1900 
1901   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1902   if (Info.hasPrivateSegmentBuffer()) {
1903     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1904     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1905     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1906   }
1907 
1908   if (Info.hasDispatchPtr()) {
1909     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1910     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1911     CCInfo.AllocateReg(DispatchPtrReg);
1912   }
1913 
1914   if (Info.hasQueuePtr()) {
1915     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1916     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1917     CCInfo.AllocateReg(QueuePtrReg);
1918   }
1919 
1920   if (Info.hasKernargSegmentPtr()) {
1921     MachineRegisterInfo &MRI = MF.getRegInfo();
1922     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1923     CCInfo.AllocateReg(InputPtrReg);
1924 
1925     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1926     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1927   }
1928 
1929   if (Info.hasDispatchID()) {
1930     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1931     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1932     CCInfo.AllocateReg(DispatchIDReg);
1933   }
1934 
1935   if (Info.hasFlatScratchInit()) {
1936     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1937     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1938     CCInfo.AllocateReg(FlatScratchInitReg);
1939   }
1940 
1941   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1942   // these from the dispatch pointer.
1943 }
1944 
1945 // Allocate special input registers that are initialized per-wave.
1946 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1947                                            MachineFunction &MF,
1948                                            SIMachineFunctionInfo &Info,
1949                                            CallingConv::ID CallConv,
1950                                            bool IsShader) const {
1951   if (Info.hasWorkGroupIDX()) {
1952     unsigned Reg = Info.addWorkGroupIDX();
1953     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1954     CCInfo.AllocateReg(Reg);
1955   }
1956 
1957   if (Info.hasWorkGroupIDY()) {
1958     unsigned Reg = Info.addWorkGroupIDY();
1959     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1960     CCInfo.AllocateReg(Reg);
1961   }
1962 
1963   if (Info.hasWorkGroupIDZ()) {
1964     unsigned Reg = Info.addWorkGroupIDZ();
1965     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1966     CCInfo.AllocateReg(Reg);
1967   }
1968 
1969   if (Info.hasWorkGroupInfo()) {
1970     unsigned Reg = Info.addWorkGroupInfo();
1971     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1972     CCInfo.AllocateReg(Reg);
1973   }
1974 
1975   if (Info.hasPrivateSegmentWaveByteOffset()) {
1976     // Scratch wave offset passed in system SGPR.
1977     unsigned PrivateSegmentWaveByteOffsetReg;
1978 
1979     if (IsShader) {
1980       PrivateSegmentWaveByteOffsetReg =
1981         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1982 
1983       // This is true if the scratch wave byte offset doesn't have a fixed
1984       // location.
1985       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1986         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1987         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1988       }
1989     } else
1990       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1991 
1992     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1993     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1994   }
1995 }
1996 
1997 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1998                                      MachineFunction &MF,
1999                                      const SIRegisterInfo &TRI,
2000                                      SIMachineFunctionInfo &Info) {
2001   // Now that we've figured out where the scratch register inputs are, see if
2002   // should reserve the arguments and use them directly.
2003   MachineFrameInfo &MFI = MF.getFrameInfo();
2004   bool HasStackObjects = MFI.hasStackObjects();
2005   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2006 
2007   // Record that we know we have non-spill stack objects so we don't need to
2008   // check all stack objects later.
2009   if (HasStackObjects)
2010     Info.setHasNonSpillStackObjects(true);
2011 
2012   // Everything live out of a block is spilled with fast regalloc, so it's
2013   // almost certain that spilling will be required.
2014   if (TM.getOptLevel() == CodeGenOpt::None)
2015     HasStackObjects = true;
2016 
2017   // For now assume stack access is needed in any callee functions, so we need
2018   // the scratch registers to pass in.
2019   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2020 
2021   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2022     // If we have stack objects, we unquestionably need the private buffer
2023     // resource. For the Code Object V2 ABI, this will be the first 4 user
2024     // SGPR inputs. We can reserve those and use them directly.
2025 
2026     Register PrivateSegmentBufferReg =
2027         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2028     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2029   } else {
2030     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2031     // We tentatively reserve the last registers (skipping the last registers
2032     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2033     // we'll replace these with the ones immediately after those which were
2034     // really allocated. In the prologue copies will be inserted from the
2035     // argument to these reserved registers.
2036 
2037     // Without HSA, relocations are used for the scratch pointer and the
2038     // buffer resource setup is always inserted in the prologue. Scratch wave
2039     // offset is still in an input SGPR.
2040     Info.setScratchRSrcReg(ReservedBufferReg);
2041   }
2042 
2043   MachineRegisterInfo &MRI = MF.getRegInfo();
2044 
2045   // For entry functions we have to set up the stack pointer if we use it,
2046   // whereas non-entry functions get this "for free". This means there is no
2047   // intrinsic advantage to using S32 over S34 in cases where we do not have
2048   // calls but do need a frame pointer (i.e. if we are requested to have one
2049   // because frame pointer elimination is disabled). To keep things simple we
2050   // only ever use S32 as the call ABI stack pointer, and so using it does not
2051   // imply we need a separate frame pointer.
2052   //
2053   // Try to use s32 as the SP, but move it if it would interfere with input
2054   // arguments. This won't work with calls though.
2055   //
2056   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2057   // registers.
2058   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2059     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2060   } else {
2061     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2062 
2063     if (MFI.hasCalls())
2064       report_fatal_error("call in graphics shader with too many input SGPRs");
2065 
2066     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2067       if (!MRI.isLiveIn(Reg)) {
2068         Info.setStackPtrOffsetReg(Reg);
2069         break;
2070       }
2071     }
2072 
2073     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2074       report_fatal_error("failed to find register for SP");
2075   }
2076 
2077   // hasFP should be accurate for entry functions even before the frame is
2078   // finalized, because it does not rely on the known stack size, only
2079   // properties like whether variable sized objects are present.
2080   if (ST.getFrameLowering()->hasFP(MF)) {
2081     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2082   }
2083 }
2084 
2085 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2086   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2087   return !Info->isEntryFunction();
2088 }
2089 
2090 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2091 
2092 }
2093 
2094 void SITargetLowering::insertCopiesSplitCSR(
2095   MachineBasicBlock *Entry,
2096   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2097   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2098 
2099   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2100   if (!IStart)
2101     return;
2102 
2103   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2104   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2105   MachineBasicBlock::iterator MBBI = Entry->begin();
2106   for (const MCPhysReg *I = IStart; *I; ++I) {
2107     const TargetRegisterClass *RC = nullptr;
2108     if (AMDGPU::SReg_64RegClass.contains(*I))
2109       RC = &AMDGPU::SGPR_64RegClass;
2110     else if (AMDGPU::SReg_32RegClass.contains(*I))
2111       RC = &AMDGPU::SGPR_32RegClass;
2112     else
2113       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2114 
2115     Register NewVR = MRI->createVirtualRegister(RC);
2116     // Create copy from CSR to a virtual register.
2117     Entry->addLiveIn(*I);
2118     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2119       .addReg(*I);
2120 
2121     // Insert the copy-back instructions right before the terminator.
2122     for (auto *Exit : Exits)
2123       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2124               TII->get(TargetOpcode::COPY), *I)
2125         .addReg(NewVR);
2126   }
2127 }
2128 
2129 SDValue SITargetLowering::LowerFormalArguments(
2130     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2131     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2132     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2133   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2134 
2135   MachineFunction &MF = DAG.getMachineFunction();
2136   const Function &Fn = MF.getFunction();
2137   FunctionType *FType = MF.getFunction().getFunctionType();
2138   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2139 
2140   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2141     DiagnosticInfoUnsupported NoGraphicsHSA(
2142         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2143     DAG.getContext()->diagnose(NoGraphicsHSA);
2144     return DAG.getEntryNode();
2145   }
2146 
2147   SmallVector<ISD::InputArg, 16> Splits;
2148   SmallVector<CCValAssign, 16> ArgLocs;
2149   BitVector Skipped(Ins.size());
2150   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2151                  *DAG.getContext());
2152 
2153   bool IsShader = AMDGPU::isShader(CallConv);
2154   bool IsKernel = AMDGPU::isKernel(CallConv);
2155   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2156 
2157   if (IsShader) {
2158     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2159 
2160     // At least one interpolation mode must be enabled or else the GPU will
2161     // hang.
2162     //
2163     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2164     // set PSInputAddr, the user wants to enable some bits after the compilation
2165     // based on run-time states. Since we can't know what the final PSInputEna
2166     // will look like, so we shouldn't do anything here and the user should take
2167     // responsibility for the correct programming.
2168     //
2169     // Otherwise, the following restrictions apply:
2170     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2171     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2172     //   enabled too.
2173     if (CallConv == CallingConv::AMDGPU_PS) {
2174       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2175            ((Info->getPSInputAddr() & 0xF) == 0 &&
2176             Info->isPSInputAllocated(11))) {
2177         CCInfo.AllocateReg(AMDGPU::VGPR0);
2178         CCInfo.AllocateReg(AMDGPU::VGPR1);
2179         Info->markPSInputAllocated(0);
2180         Info->markPSInputEnabled(0);
2181       }
2182       if (Subtarget->isAmdPalOS()) {
2183         // For isAmdPalOS, the user does not enable some bits after compilation
2184         // based on run-time states; the register values being generated here are
2185         // the final ones set in hardware. Therefore we need to apply the
2186         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2187         // a bit is set in PSInputAddr but not PSInputEnable is where the
2188         // frontend set up an input arg for a particular interpolation mode, but
2189         // nothing uses that input arg. Really we should have an earlier pass
2190         // that removes such an arg.)
2191         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2192         if ((PsInputBits & 0x7F) == 0 ||
2193             ((PsInputBits & 0xF) == 0 &&
2194              (PsInputBits >> 11 & 1)))
2195           Info->markPSInputEnabled(
2196               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2197       }
2198     }
2199 
2200     assert(!Info->hasDispatchPtr() &&
2201            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2202            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2203            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2204            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2205            !Info->hasWorkItemIDZ());
2206   } else if (IsKernel) {
2207     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2208   } else {
2209     Splits.append(Ins.begin(), Ins.end());
2210   }
2211 
2212   if (IsEntryFunc) {
2213     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2214     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2215   } else {
2216     // For the fixed ABI, pass workitem IDs in the last argument register.
2217     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2218       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2219   }
2220 
2221   if (IsKernel) {
2222     analyzeFormalArgumentsCompute(CCInfo, Ins);
2223   } else {
2224     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2225     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2226   }
2227 
2228   SmallVector<SDValue, 16> Chains;
2229 
2230   // FIXME: This is the minimum kernel argument alignment. We should improve
2231   // this to the maximum alignment of the arguments.
2232   //
2233   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2234   // kern arg offset.
2235   const unsigned KernelArgBaseAlign = 16;
2236 
2237    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2238     const ISD::InputArg &Arg = Ins[i];
2239     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2240       InVals.push_back(DAG.getUNDEF(Arg.VT));
2241       continue;
2242     }
2243 
2244     CCValAssign &VA = ArgLocs[ArgIdx++];
2245     MVT VT = VA.getLocVT();
2246 
2247     if (IsEntryFunc && VA.isMemLoc()) {
2248       VT = Ins[i].VT;
2249       EVT MemVT = VA.getLocVT();
2250 
2251       const uint64_t Offset = VA.getLocMemOffset();
2252       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2253 
2254       SDValue Arg = lowerKernargMemParameter(
2255         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2256       Chains.push_back(Arg.getValue(1));
2257 
2258       auto *ParamTy =
2259         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2260       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2261           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2262                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2263         // On SI local pointers are just offsets into LDS, so they are always
2264         // less than 16-bits.  On CI and newer they could potentially be
2265         // real pointers, so we can't guarantee their size.
2266         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2267                           DAG.getValueType(MVT::i16));
2268       }
2269 
2270       InVals.push_back(Arg);
2271       continue;
2272     } else if (!IsEntryFunc && VA.isMemLoc()) {
2273       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2274       InVals.push_back(Val);
2275       if (!Arg.Flags.isByVal())
2276         Chains.push_back(Val.getValue(1));
2277       continue;
2278     }
2279 
2280     assert(VA.isRegLoc() && "Parameter must be in a register!");
2281 
2282     Register Reg = VA.getLocReg();
2283     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2284     EVT ValVT = VA.getValVT();
2285 
2286     Reg = MF.addLiveIn(Reg, RC);
2287     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2288 
2289     if (Arg.Flags.isSRet()) {
2290       // The return object should be reasonably addressable.
2291 
2292       // FIXME: This helps when the return is a real sret. If it is a
2293       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2294       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2295       unsigned NumBits
2296         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2297       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2298         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2299     }
2300 
2301     // If this is an 8 or 16-bit value, it is really passed promoted
2302     // to 32 bits. Insert an assert[sz]ext to capture this, then
2303     // truncate to the right size.
2304     switch (VA.getLocInfo()) {
2305     case CCValAssign::Full:
2306       break;
2307     case CCValAssign::BCvt:
2308       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2309       break;
2310     case CCValAssign::SExt:
2311       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2312                         DAG.getValueType(ValVT));
2313       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2314       break;
2315     case CCValAssign::ZExt:
2316       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2317                         DAG.getValueType(ValVT));
2318       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2319       break;
2320     case CCValAssign::AExt:
2321       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2322       break;
2323     default:
2324       llvm_unreachable("Unknown loc info!");
2325     }
2326 
2327     InVals.push_back(Val);
2328   }
2329 
2330   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2331     // Special inputs come after user arguments.
2332     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2333   }
2334 
2335   // Start adding system SGPRs.
2336   if (IsEntryFunc) {
2337     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2338   } else {
2339     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2340     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2341   }
2342 
2343   auto &ArgUsageInfo =
2344     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2345   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2346 
2347   unsigned StackArgSize = CCInfo.getNextStackOffset();
2348   Info->setBytesInStackArgArea(StackArgSize);
2349 
2350   return Chains.empty() ? Chain :
2351     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2352 }
2353 
2354 // TODO: If return values can't fit in registers, we should return as many as
2355 // possible in registers before passing on stack.
2356 bool SITargetLowering::CanLowerReturn(
2357   CallingConv::ID CallConv,
2358   MachineFunction &MF, bool IsVarArg,
2359   const SmallVectorImpl<ISD::OutputArg> &Outs,
2360   LLVMContext &Context) const {
2361   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2362   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2363   // for shaders. Vector types should be explicitly handled by CC.
2364   if (AMDGPU::isEntryFunctionCC(CallConv))
2365     return true;
2366 
2367   SmallVector<CCValAssign, 16> RVLocs;
2368   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2369   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2370 }
2371 
2372 SDValue
2373 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2374                               bool isVarArg,
2375                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2376                               const SmallVectorImpl<SDValue> &OutVals,
2377                               const SDLoc &DL, SelectionDAG &DAG) const {
2378   MachineFunction &MF = DAG.getMachineFunction();
2379   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2380 
2381   if (AMDGPU::isKernel(CallConv)) {
2382     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2383                                              OutVals, DL, DAG);
2384   }
2385 
2386   bool IsShader = AMDGPU::isShader(CallConv);
2387 
2388   Info->setIfReturnsVoid(Outs.empty());
2389   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2390 
2391   // CCValAssign - represent the assignment of the return value to a location.
2392   SmallVector<CCValAssign, 48> RVLocs;
2393   SmallVector<ISD::OutputArg, 48> Splits;
2394 
2395   // CCState - Info about the registers and stack slots.
2396   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2397                  *DAG.getContext());
2398 
2399   // Analyze outgoing return values.
2400   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2401 
2402   SDValue Flag;
2403   SmallVector<SDValue, 48> RetOps;
2404   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2405 
2406   // Add return address for callable functions.
2407   if (!Info->isEntryFunction()) {
2408     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2409     SDValue ReturnAddrReg = CreateLiveInRegister(
2410       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2411 
2412     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2413         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2414         MVT::i64);
2415     Chain =
2416         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2417     Flag = Chain.getValue(1);
2418     RetOps.push_back(ReturnAddrVirtualReg);
2419   }
2420 
2421   // Copy the result values into the output registers.
2422   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2423        ++I, ++RealRVLocIdx) {
2424     CCValAssign &VA = RVLocs[I];
2425     assert(VA.isRegLoc() && "Can only return in registers!");
2426     // TODO: Partially return in registers if return values don't fit.
2427     SDValue Arg = OutVals[RealRVLocIdx];
2428 
2429     // Copied from other backends.
2430     switch (VA.getLocInfo()) {
2431     case CCValAssign::Full:
2432       break;
2433     case CCValAssign::BCvt:
2434       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2435       break;
2436     case CCValAssign::SExt:
2437       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2438       break;
2439     case CCValAssign::ZExt:
2440       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2441       break;
2442     case CCValAssign::AExt:
2443       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2444       break;
2445     default:
2446       llvm_unreachable("Unknown loc info!");
2447     }
2448 
2449     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2450     Flag = Chain.getValue(1);
2451     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2452   }
2453 
2454   // FIXME: Does sret work properly?
2455   if (!Info->isEntryFunction()) {
2456     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2457     const MCPhysReg *I =
2458       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2459     if (I) {
2460       for (; *I; ++I) {
2461         if (AMDGPU::SReg_64RegClass.contains(*I))
2462           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2463         else if (AMDGPU::SReg_32RegClass.contains(*I))
2464           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2465         else
2466           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2467       }
2468     }
2469   }
2470 
2471   // Update chain and glue.
2472   RetOps[0] = Chain;
2473   if (Flag.getNode())
2474     RetOps.push_back(Flag);
2475 
2476   unsigned Opc = AMDGPUISD::ENDPGM;
2477   if (!IsWaveEnd)
2478     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2479   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2480 }
2481 
2482 SDValue SITargetLowering::LowerCallResult(
2483     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2484     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2485     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2486     SDValue ThisVal) const {
2487   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2488 
2489   // Assign locations to each value returned by this call.
2490   SmallVector<CCValAssign, 16> RVLocs;
2491   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2492                  *DAG.getContext());
2493   CCInfo.AnalyzeCallResult(Ins, RetCC);
2494 
2495   // Copy all of the result registers out of their specified physreg.
2496   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2497     CCValAssign VA = RVLocs[i];
2498     SDValue Val;
2499 
2500     if (VA.isRegLoc()) {
2501       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2502       Chain = Val.getValue(1);
2503       InFlag = Val.getValue(2);
2504     } else if (VA.isMemLoc()) {
2505       report_fatal_error("TODO: return values in memory");
2506     } else
2507       llvm_unreachable("unknown argument location type");
2508 
2509     switch (VA.getLocInfo()) {
2510     case CCValAssign::Full:
2511       break;
2512     case CCValAssign::BCvt:
2513       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2514       break;
2515     case CCValAssign::ZExt:
2516       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2517                         DAG.getValueType(VA.getValVT()));
2518       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2519       break;
2520     case CCValAssign::SExt:
2521       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2522                         DAG.getValueType(VA.getValVT()));
2523       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2524       break;
2525     case CCValAssign::AExt:
2526       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2527       break;
2528     default:
2529       llvm_unreachable("Unknown loc info!");
2530     }
2531 
2532     InVals.push_back(Val);
2533   }
2534 
2535   return Chain;
2536 }
2537 
2538 // Add code to pass special inputs required depending on used features separate
2539 // from the explicit user arguments present in the IR.
2540 void SITargetLowering::passSpecialInputs(
2541     CallLoweringInfo &CLI,
2542     CCState &CCInfo,
2543     const SIMachineFunctionInfo &Info,
2544     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2545     SmallVectorImpl<SDValue> &MemOpChains,
2546     SDValue Chain) const {
2547   // If we don't have a call site, this was a call inserted by
2548   // legalization. These can never use special inputs.
2549   if (!CLI.CB)
2550     return;
2551 
2552   SelectionDAG &DAG = CLI.DAG;
2553   const SDLoc &DL = CLI.DL;
2554 
2555   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2556   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2557 
2558   const AMDGPUFunctionArgInfo *CalleeArgInfo
2559     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2560   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2561     auto &ArgUsageInfo =
2562       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2563     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2564   }
2565 
2566   // TODO: Unify with private memory register handling. This is complicated by
2567   // the fact that at least in kernels, the input argument is not necessarily
2568   // in the same location as the input.
2569   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2570     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2571     AMDGPUFunctionArgInfo::QUEUE_PTR,
2572     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2573     AMDGPUFunctionArgInfo::DISPATCH_ID,
2574     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2575     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2576     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2577   };
2578 
2579   for (auto InputID : InputRegs) {
2580     const ArgDescriptor *OutgoingArg;
2581     const TargetRegisterClass *ArgRC;
2582 
2583     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID);
2584     if (!OutgoingArg)
2585       continue;
2586 
2587     const ArgDescriptor *IncomingArg;
2588     const TargetRegisterClass *IncomingArgRC;
2589     std::tie(IncomingArg, IncomingArgRC)
2590       = CallerArgInfo.getPreloadedValue(InputID);
2591     assert(IncomingArgRC == ArgRC);
2592 
2593     // All special arguments are ints for now.
2594     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2595     SDValue InputReg;
2596 
2597     if (IncomingArg) {
2598       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2599     } else {
2600       // The implicit arg ptr is special because it doesn't have a corresponding
2601       // input for kernels, and is computed from the kernarg segment pointer.
2602       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2603       InputReg = getImplicitArgPtr(DAG, DL);
2604     }
2605 
2606     if (OutgoingArg->isRegister()) {
2607       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2608       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2609         report_fatal_error("failed to allocate implicit input argument");
2610     } else {
2611       unsigned SpecialArgOffset =
2612           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2613       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2614                                               SpecialArgOffset);
2615       MemOpChains.push_back(ArgStore);
2616     }
2617   }
2618 
2619   // Pack workitem IDs into a single register or pass it as is if already
2620   // packed.
2621   const ArgDescriptor *OutgoingArg;
2622   const TargetRegisterClass *ArgRC;
2623 
2624   std::tie(OutgoingArg, ArgRC) =
2625     CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2626   if (!OutgoingArg)
2627     std::tie(OutgoingArg, ArgRC) =
2628       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2629   if (!OutgoingArg)
2630     std::tie(OutgoingArg, ArgRC) =
2631       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2632   if (!OutgoingArg)
2633     return;
2634 
2635   const ArgDescriptor *IncomingArgX
2636     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2637   const ArgDescriptor *IncomingArgY
2638     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2639   const ArgDescriptor *IncomingArgZ
2640     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2641 
2642   SDValue InputReg;
2643   SDLoc SL;
2644 
2645   // If incoming ids are not packed we need to pack them.
2646   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2647     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2648 
2649   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2650     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2651     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2652                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2653     InputReg = InputReg.getNode() ?
2654                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2655   }
2656 
2657   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2658     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2659     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2660                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2661     InputReg = InputReg.getNode() ?
2662                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2663   }
2664 
2665   if (!InputReg.getNode()) {
2666     // Workitem ids are already packed, any of present incoming arguments
2667     // will carry all required fields.
2668     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2669       IncomingArgX ? *IncomingArgX :
2670       IncomingArgY ? *IncomingArgY :
2671                      *IncomingArgZ, ~0u);
2672     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2673   }
2674 
2675   if (OutgoingArg->isRegister()) {
2676     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2677     CCInfo.AllocateReg(OutgoingArg->getRegister());
2678   } else {
2679     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2680     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2681                                             SpecialArgOffset);
2682     MemOpChains.push_back(ArgStore);
2683   }
2684 }
2685 
2686 static bool canGuaranteeTCO(CallingConv::ID CC) {
2687   return CC == CallingConv::Fast;
2688 }
2689 
2690 /// Return true if we might ever do TCO for calls with this calling convention.
2691 static bool mayTailCallThisCC(CallingConv::ID CC) {
2692   switch (CC) {
2693   case CallingConv::C:
2694     return true;
2695   default:
2696     return canGuaranteeTCO(CC);
2697   }
2698 }
2699 
2700 bool SITargetLowering::isEligibleForTailCallOptimization(
2701     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2702     const SmallVectorImpl<ISD::OutputArg> &Outs,
2703     const SmallVectorImpl<SDValue> &OutVals,
2704     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2705   if (!mayTailCallThisCC(CalleeCC))
2706     return false;
2707 
2708   MachineFunction &MF = DAG.getMachineFunction();
2709   const Function &CallerF = MF.getFunction();
2710   CallingConv::ID CallerCC = CallerF.getCallingConv();
2711   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2712   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2713 
2714   // Kernels aren't callable, and don't have a live in return address so it
2715   // doesn't make sense to do a tail call with entry functions.
2716   if (!CallerPreserved)
2717     return false;
2718 
2719   bool CCMatch = CallerCC == CalleeCC;
2720 
2721   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2722     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2723       return true;
2724     return false;
2725   }
2726 
2727   // TODO: Can we handle var args?
2728   if (IsVarArg)
2729     return false;
2730 
2731   for (const Argument &Arg : CallerF.args()) {
2732     if (Arg.hasByValAttr())
2733       return false;
2734   }
2735 
2736   LLVMContext &Ctx = *DAG.getContext();
2737 
2738   // Check that the call results are passed in the same way.
2739   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2740                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2741                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2742     return false;
2743 
2744   // The callee has to preserve all registers the caller needs to preserve.
2745   if (!CCMatch) {
2746     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2747     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2748       return false;
2749   }
2750 
2751   // Nothing more to check if the callee is taking no arguments.
2752   if (Outs.empty())
2753     return true;
2754 
2755   SmallVector<CCValAssign, 16> ArgLocs;
2756   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2757 
2758   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2759 
2760   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2761   // If the stack arguments for this call do not fit into our own save area then
2762   // the call cannot be made tail.
2763   // TODO: Is this really necessary?
2764   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2765     return false;
2766 
2767   const MachineRegisterInfo &MRI = MF.getRegInfo();
2768   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2769 }
2770 
2771 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2772   if (!CI->isTailCall())
2773     return false;
2774 
2775   const Function *ParentFn = CI->getParent()->getParent();
2776   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2777     return false;
2778   return true;
2779 }
2780 
2781 // The wave scratch offset register is used as the global base pointer.
2782 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2783                                     SmallVectorImpl<SDValue> &InVals) const {
2784   SelectionDAG &DAG = CLI.DAG;
2785   const SDLoc &DL = CLI.DL;
2786   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2787   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2788   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2789   SDValue Chain = CLI.Chain;
2790   SDValue Callee = CLI.Callee;
2791   bool &IsTailCall = CLI.IsTailCall;
2792   CallingConv::ID CallConv = CLI.CallConv;
2793   bool IsVarArg = CLI.IsVarArg;
2794   bool IsSibCall = false;
2795   bool IsThisReturn = false;
2796   MachineFunction &MF = DAG.getMachineFunction();
2797 
2798   if (Callee.isUndef() || isNullConstant(Callee)) {
2799     if (!CLI.IsTailCall) {
2800       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2801         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2802     }
2803 
2804     return Chain;
2805   }
2806 
2807   if (IsVarArg) {
2808     return lowerUnhandledCall(CLI, InVals,
2809                               "unsupported call to variadic function ");
2810   }
2811 
2812   if (!CLI.CB)
2813     report_fatal_error("unsupported libcall legalization");
2814 
2815   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2816       !CLI.CB->getCalledFunction()) {
2817     return lowerUnhandledCall(CLI, InVals,
2818                               "unsupported indirect call to function ");
2819   }
2820 
2821   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2822     return lowerUnhandledCall(CLI, InVals,
2823                               "unsupported required tail call to function ");
2824   }
2825 
2826   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2827     // Note the issue is with the CC of the calling function, not of the call
2828     // itself.
2829     return lowerUnhandledCall(CLI, InVals,
2830                           "unsupported call from graphics shader of function ");
2831   }
2832 
2833   if (IsTailCall) {
2834     IsTailCall = isEligibleForTailCallOptimization(
2835       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2836     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2837       report_fatal_error("failed to perform tail call elimination on a call "
2838                          "site marked musttail");
2839     }
2840 
2841     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2842 
2843     // A sibling call is one where we're under the usual C ABI and not planning
2844     // to change that but can still do a tail call:
2845     if (!TailCallOpt && IsTailCall)
2846       IsSibCall = true;
2847 
2848     if (IsTailCall)
2849       ++NumTailCalls;
2850   }
2851 
2852   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2853   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2854   SmallVector<SDValue, 8> MemOpChains;
2855 
2856   // Analyze operands of the call, assigning locations to each operand.
2857   SmallVector<CCValAssign, 16> ArgLocs;
2858   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2859   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2860 
2861   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2862     // With a fixed ABI, allocate fixed registers before user arguments.
2863     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2864   }
2865 
2866   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2867 
2868   // Get a count of how many bytes are to be pushed on the stack.
2869   unsigned NumBytes = CCInfo.getNextStackOffset();
2870 
2871   if (IsSibCall) {
2872     // Since we're not changing the ABI to make this a tail call, the memory
2873     // operands are already available in the caller's incoming argument space.
2874     NumBytes = 0;
2875   }
2876 
2877   // FPDiff is the byte offset of the call's argument area from the callee's.
2878   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2879   // by this amount for a tail call. In a sibling call it must be 0 because the
2880   // caller will deallocate the entire stack and the callee still expects its
2881   // arguments to begin at SP+0. Completely unused for non-tail calls.
2882   int32_t FPDiff = 0;
2883   MachineFrameInfo &MFI = MF.getFrameInfo();
2884 
2885   // Adjust the stack pointer for the new arguments...
2886   // These operations are automatically eliminated by the prolog/epilog pass
2887   if (!IsSibCall) {
2888     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2889 
2890     SmallVector<SDValue, 4> CopyFromChains;
2891 
2892     // In the HSA case, this should be an identity copy.
2893     SDValue ScratchRSrcReg
2894       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2895     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2896     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2897     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2898   }
2899 
2900   MVT PtrVT = MVT::i32;
2901 
2902   // Walk the register/memloc assignments, inserting copies/loads.
2903   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2904     CCValAssign &VA = ArgLocs[i];
2905     SDValue Arg = OutVals[i];
2906 
2907     // Promote the value if needed.
2908     switch (VA.getLocInfo()) {
2909     case CCValAssign::Full:
2910       break;
2911     case CCValAssign::BCvt:
2912       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2913       break;
2914     case CCValAssign::ZExt:
2915       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2916       break;
2917     case CCValAssign::SExt:
2918       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2919       break;
2920     case CCValAssign::AExt:
2921       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2922       break;
2923     case CCValAssign::FPExt:
2924       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2925       break;
2926     default:
2927       llvm_unreachable("Unknown loc info!");
2928     }
2929 
2930     if (VA.isRegLoc()) {
2931       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2932     } else {
2933       assert(VA.isMemLoc());
2934 
2935       SDValue DstAddr;
2936       MachinePointerInfo DstInfo;
2937 
2938       unsigned LocMemOffset = VA.getLocMemOffset();
2939       int32_t Offset = LocMemOffset;
2940 
2941       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2942       MaybeAlign Alignment;
2943 
2944       if (IsTailCall) {
2945         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2946         unsigned OpSize = Flags.isByVal() ?
2947           Flags.getByValSize() : VA.getValVT().getStoreSize();
2948 
2949         // FIXME: We can have better than the minimum byval required alignment.
2950         Alignment =
2951             Flags.isByVal()
2952                 ? Flags.getNonZeroByValAlign()
2953                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2954 
2955         Offset = Offset + FPDiff;
2956         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2957 
2958         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2959         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2960 
2961         // Make sure any stack arguments overlapping with where we're storing
2962         // are loaded before this eventual operation. Otherwise they'll be
2963         // clobbered.
2964 
2965         // FIXME: Why is this really necessary? This seems to just result in a
2966         // lot of code to copy the stack and write them back to the same
2967         // locations, which are supposed to be immutable?
2968         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2969       } else {
2970         DstAddr = PtrOff;
2971         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2972         Alignment =
2973             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2974       }
2975 
2976       if (Outs[i].Flags.isByVal()) {
2977         SDValue SizeNode =
2978             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2979         SDValue Cpy =
2980             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2981                           Outs[i].Flags.getNonZeroByValAlign(),
2982                           /*isVol = */ false, /*AlwaysInline = */ true,
2983                           /*isTailCall = */ false, DstInfo,
2984                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2985 
2986         MemOpChains.push_back(Cpy);
2987       } else {
2988         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2989                                      Alignment ? Alignment->value() : 0);
2990         MemOpChains.push_back(Store);
2991       }
2992     }
2993   }
2994 
2995   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
2996     // Copy special input registers after user input arguments.
2997     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2998   }
2999 
3000   if (!MemOpChains.empty())
3001     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3002 
3003   // Build a sequence of copy-to-reg nodes chained together with token chain
3004   // and flag operands which copy the outgoing args into the appropriate regs.
3005   SDValue InFlag;
3006   for (auto &RegToPass : RegsToPass) {
3007     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3008                              RegToPass.second, InFlag);
3009     InFlag = Chain.getValue(1);
3010   }
3011 
3012 
3013   SDValue PhysReturnAddrReg;
3014   if (IsTailCall) {
3015     // Since the return is being combined with the call, we need to pass on the
3016     // return address.
3017 
3018     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3019     SDValue ReturnAddrReg = CreateLiveInRegister(
3020       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3021 
3022     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3023                                         MVT::i64);
3024     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3025     InFlag = Chain.getValue(1);
3026   }
3027 
3028   // We don't usually want to end the call-sequence here because we would tidy
3029   // the frame up *after* the call, however in the ABI-changing tail-call case
3030   // we've carefully laid out the parameters so that when sp is reset they'll be
3031   // in the correct location.
3032   if (IsTailCall && !IsSibCall) {
3033     Chain = DAG.getCALLSEQ_END(Chain,
3034                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3035                                DAG.getTargetConstant(0, DL, MVT::i32),
3036                                InFlag, DL);
3037     InFlag = Chain.getValue(1);
3038   }
3039 
3040   std::vector<SDValue> Ops;
3041   Ops.push_back(Chain);
3042   Ops.push_back(Callee);
3043   // Add a redundant copy of the callee global which will not be legalized, as
3044   // we need direct access to the callee later.
3045   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3046     const GlobalValue *GV = GSD->getGlobal();
3047     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3048   } else {
3049     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3050   }
3051 
3052   if (IsTailCall) {
3053     // Each tail call may have to adjust the stack by a different amount, so
3054     // this information must travel along with the operation for eventual
3055     // consumption by emitEpilogue.
3056     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3057 
3058     Ops.push_back(PhysReturnAddrReg);
3059   }
3060 
3061   // Add argument registers to the end of the list so that they are known live
3062   // into the call.
3063   for (auto &RegToPass : RegsToPass) {
3064     Ops.push_back(DAG.getRegister(RegToPass.first,
3065                                   RegToPass.second.getValueType()));
3066   }
3067 
3068   // Add a register mask operand representing the call-preserved registers.
3069 
3070   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3071   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3072   assert(Mask && "Missing call preserved mask for calling convention");
3073   Ops.push_back(DAG.getRegisterMask(Mask));
3074 
3075   if (InFlag.getNode())
3076     Ops.push_back(InFlag);
3077 
3078   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3079 
3080   // If we're doing a tall call, use a TC_RETURN here rather than an
3081   // actual call instruction.
3082   if (IsTailCall) {
3083     MFI.setHasTailCall();
3084     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3085   }
3086 
3087   // Returns a chain and a flag for retval copy to use.
3088   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3089   Chain = Call.getValue(0);
3090   InFlag = Call.getValue(1);
3091 
3092   uint64_t CalleePopBytes = NumBytes;
3093   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3094                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3095                              InFlag, DL);
3096   if (!Ins.empty())
3097     InFlag = Chain.getValue(1);
3098 
3099   // Handle result values, copying them out of physregs into vregs that we
3100   // return.
3101   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3102                          InVals, IsThisReturn,
3103                          IsThisReturn ? OutVals[0] : SDValue());
3104 }
3105 
3106 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3107 // except for applying the wave size scale to the increment amount.
3108 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3109     SDValue Op, SelectionDAG &DAG) const {
3110   const MachineFunction &MF = DAG.getMachineFunction();
3111   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3112 
3113   SDLoc dl(Op);
3114   EVT VT = Op.getValueType();
3115   SDValue Tmp1 = Op;
3116   SDValue Tmp2 = Op.getValue(1);
3117   SDValue Tmp3 = Op.getOperand(2);
3118   SDValue Chain = Tmp1.getOperand(0);
3119 
3120   Register SPReg = Info->getStackPtrOffsetReg();
3121 
3122   // Chain the dynamic stack allocation so that it doesn't modify the stack
3123   // pointer when other instructions are using the stack.
3124   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3125 
3126   SDValue Size  = Tmp2.getOperand(1);
3127   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3128   Chain = SP.getValue(1);
3129   unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
3130   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3131   const TargetFrameLowering *TFL = ST.getFrameLowering();
3132   unsigned Opc =
3133     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3134     ISD::ADD : ISD::SUB;
3135 
3136   SDValue ScaledSize = DAG.getNode(
3137       ISD::SHL, dl, VT, Size,
3138       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3139 
3140   unsigned StackAlign = TFL->getStackAlignment();
3141   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3142   if (Align > StackAlign) {
3143     Tmp1 = DAG.getNode(
3144       ISD::AND, dl, VT, Tmp1,
3145       DAG.getConstant(-(uint64_t)Align << ST.getWavefrontSizeLog2(), dl, VT));
3146   }
3147 
3148   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3149   Tmp2 = DAG.getCALLSEQ_END(
3150       Chain, DAG.getIntPtrConstant(0, dl, true),
3151       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3152 
3153   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3154 }
3155 
3156 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3157                                                   SelectionDAG &DAG) const {
3158   // We only handle constant sizes here to allow non-entry block, static sized
3159   // allocas. A truly dynamic value is more difficult to support because we
3160   // don't know if the size value is uniform or not. If the size isn't uniform,
3161   // we would need to do a wave reduction to get the maximum size to know how
3162   // much to increment the uniform stack pointer.
3163   SDValue Size = Op.getOperand(1);
3164   if (isa<ConstantSDNode>(Size))
3165       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3166 
3167   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3168 }
3169 
3170 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3171                                              const MachineFunction &MF) const {
3172   Register Reg = StringSwitch<Register>(RegName)
3173     .Case("m0", AMDGPU::M0)
3174     .Case("exec", AMDGPU::EXEC)
3175     .Case("exec_lo", AMDGPU::EXEC_LO)
3176     .Case("exec_hi", AMDGPU::EXEC_HI)
3177     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3178     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3179     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3180     .Default(Register());
3181 
3182   if (Reg == AMDGPU::NoRegister) {
3183     report_fatal_error(Twine("invalid register name \""
3184                              + StringRef(RegName)  + "\"."));
3185 
3186   }
3187 
3188   if (!Subtarget->hasFlatScrRegister() &&
3189        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3190     report_fatal_error(Twine("invalid register \""
3191                              + StringRef(RegName)  + "\" for subtarget."));
3192   }
3193 
3194   switch (Reg) {
3195   case AMDGPU::M0:
3196   case AMDGPU::EXEC_LO:
3197   case AMDGPU::EXEC_HI:
3198   case AMDGPU::FLAT_SCR_LO:
3199   case AMDGPU::FLAT_SCR_HI:
3200     if (VT.getSizeInBits() == 32)
3201       return Reg;
3202     break;
3203   case AMDGPU::EXEC:
3204   case AMDGPU::FLAT_SCR:
3205     if (VT.getSizeInBits() == 64)
3206       return Reg;
3207     break;
3208   default:
3209     llvm_unreachable("missing register type checking");
3210   }
3211 
3212   report_fatal_error(Twine("invalid type for register \""
3213                            + StringRef(RegName) + "\"."));
3214 }
3215 
3216 // If kill is not the last instruction, split the block so kill is always a
3217 // proper terminator.
3218 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3219                                                     MachineBasicBlock *BB) const {
3220   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3221 
3222   MachineBasicBlock::iterator SplitPoint(&MI);
3223   ++SplitPoint;
3224 
3225   if (SplitPoint == BB->end()) {
3226     // Don't bother with a new block.
3227     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3228     return BB;
3229   }
3230 
3231   MachineFunction *MF = BB->getParent();
3232   MachineBasicBlock *SplitBB
3233     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3234 
3235   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3236   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3237 
3238   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3239   BB->addSuccessor(SplitBB);
3240 
3241   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3242   return SplitBB;
3243 }
3244 
3245 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3246 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3247 // be the first instruction in the remainder block.
3248 //
3249 /// \returns { LoopBody, Remainder }
3250 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3251 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3252   MachineFunction *MF = MBB.getParent();
3253   MachineBasicBlock::iterator I(&MI);
3254 
3255   // To insert the loop we need to split the block. Move everything after this
3256   // point to a new block, and insert a new empty block between the two.
3257   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3258   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3259   MachineFunction::iterator MBBI(MBB);
3260   ++MBBI;
3261 
3262   MF->insert(MBBI, LoopBB);
3263   MF->insert(MBBI, RemainderBB);
3264 
3265   LoopBB->addSuccessor(LoopBB);
3266   LoopBB->addSuccessor(RemainderBB);
3267 
3268   // Move the rest of the block into a new block.
3269   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3270 
3271   if (InstInLoop) {
3272     auto Next = std::next(I);
3273 
3274     // Move instruction to loop body.
3275     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3276 
3277     // Move the rest of the block.
3278     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3279   } else {
3280     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3281   }
3282 
3283   MBB.addSuccessor(LoopBB);
3284 
3285   return std::make_pair(LoopBB, RemainderBB);
3286 }
3287 
3288 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3289 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3290   MachineBasicBlock *MBB = MI.getParent();
3291   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3292   auto I = MI.getIterator();
3293   auto E = std::next(I);
3294 
3295   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3296     .addImm(0);
3297 
3298   MIBundleBuilder Bundler(*MBB, I, E);
3299   finalizeBundle(*MBB, Bundler.begin());
3300 }
3301 
3302 MachineBasicBlock *
3303 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3304                                          MachineBasicBlock *BB) const {
3305   const DebugLoc &DL = MI.getDebugLoc();
3306 
3307   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3308 
3309   MachineBasicBlock *LoopBB;
3310   MachineBasicBlock *RemainderBB;
3311   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3312 
3313   // Apparently kill flags are only valid if the def is in the same block?
3314   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3315     Src->setIsKill(false);
3316 
3317   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3318 
3319   MachineBasicBlock::iterator I = LoopBB->end();
3320 
3321   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3322     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3323 
3324   // Clear TRAP_STS.MEM_VIOL
3325   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3326     .addImm(0)
3327     .addImm(EncodedReg);
3328 
3329   bundleInstWithWaitcnt(MI);
3330 
3331   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3332 
3333   // Load and check TRAP_STS.MEM_VIOL
3334   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3335     .addImm(EncodedReg);
3336 
3337   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3338   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3339     .addReg(Reg, RegState::Kill)
3340     .addImm(0);
3341   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3342     .addMBB(LoopBB);
3343 
3344   return RemainderBB;
3345 }
3346 
3347 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3348 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3349 // will only do one iteration. In the worst case, this will loop 64 times.
3350 //
3351 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3352 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3353   const SIInstrInfo *TII,
3354   MachineRegisterInfo &MRI,
3355   MachineBasicBlock &OrigBB,
3356   MachineBasicBlock &LoopBB,
3357   const DebugLoc &DL,
3358   const MachineOperand &IdxReg,
3359   unsigned InitReg,
3360   unsigned ResultReg,
3361   unsigned PhiReg,
3362   unsigned InitSaveExecReg,
3363   int Offset,
3364   bool UseGPRIdxMode,
3365   bool IsIndirectSrc) {
3366   MachineFunction *MF = OrigBB.getParent();
3367   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3368   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3369   MachineBasicBlock::iterator I = LoopBB.begin();
3370 
3371   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3372   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3373   Register NewExec = MRI.createVirtualRegister(BoolRC);
3374   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3375   Register CondReg = MRI.createVirtualRegister(BoolRC);
3376 
3377   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3378     .addReg(InitReg)
3379     .addMBB(&OrigBB)
3380     .addReg(ResultReg)
3381     .addMBB(&LoopBB);
3382 
3383   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3384     .addReg(InitSaveExecReg)
3385     .addMBB(&OrigBB)
3386     .addReg(NewExec)
3387     .addMBB(&LoopBB);
3388 
3389   // Read the next variant <- also loop target.
3390   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3391     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3392 
3393   // Compare the just read M0 value to all possible Idx values.
3394   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3395     .addReg(CurrentIdxReg)
3396     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3397 
3398   // Update EXEC, save the original EXEC value to VCC.
3399   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3400                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3401           NewExec)
3402     .addReg(CondReg, RegState::Kill);
3403 
3404   MRI.setSimpleHint(NewExec, CondReg);
3405 
3406   if (UseGPRIdxMode) {
3407     unsigned IdxReg;
3408     if (Offset == 0) {
3409       IdxReg = CurrentIdxReg;
3410     } else {
3411       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3412       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3413         .addReg(CurrentIdxReg, RegState::Kill)
3414         .addImm(Offset);
3415     }
3416     unsigned IdxMode = IsIndirectSrc ?
3417       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3418     MachineInstr *SetOn =
3419       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3420       .addReg(IdxReg, RegState::Kill)
3421       .addImm(IdxMode);
3422     SetOn->getOperand(3).setIsUndef();
3423   } else {
3424     // Move index from VCC into M0
3425     if (Offset == 0) {
3426       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3427         .addReg(CurrentIdxReg, RegState::Kill);
3428     } else {
3429       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3430         .addReg(CurrentIdxReg, RegState::Kill)
3431         .addImm(Offset);
3432     }
3433   }
3434 
3435   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3436   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3437   MachineInstr *InsertPt =
3438     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3439                                                   : AMDGPU::S_XOR_B64_term), Exec)
3440       .addReg(Exec)
3441       .addReg(NewExec);
3442 
3443   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3444   // s_cbranch_scc0?
3445 
3446   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3447   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3448     .addMBB(&LoopBB);
3449 
3450   return InsertPt->getIterator();
3451 }
3452 
3453 // This has slightly sub-optimal regalloc when the source vector is killed by
3454 // the read. The register allocator does not understand that the kill is
3455 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3456 // subregister from it, using 1 more VGPR than necessary. This was saved when
3457 // this was expanded after register allocation.
3458 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3459                                                   MachineBasicBlock &MBB,
3460                                                   MachineInstr &MI,
3461                                                   unsigned InitResultReg,
3462                                                   unsigned PhiReg,
3463                                                   int Offset,
3464                                                   bool UseGPRIdxMode,
3465                                                   bool IsIndirectSrc) {
3466   MachineFunction *MF = MBB.getParent();
3467   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3468   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3469   MachineRegisterInfo &MRI = MF->getRegInfo();
3470   const DebugLoc &DL = MI.getDebugLoc();
3471   MachineBasicBlock::iterator I(&MI);
3472 
3473   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3474   Register DstReg = MI.getOperand(0).getReg();
3475   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3476   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3477   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3478   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3479 
3480   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3481 
3482   // Save the EXEC mask
3483   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3484     .addReg(Exec);
3485 
3486   MachineBasicBlock *LoopBB;
3487   MachineBasicBlock *RemainderBB;
3488   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3489 
3490   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3491 
3492   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3493                                       InitResultReg, DstReg, PhiReg, TmpExec,
3494                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3495   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3496   MachineFunction::iterator MBBI(LoopBB);
3497   ++MBBI;
3498   MF->insert(MBBI, LandingPad);
3499   LoopBB->removeSuccessor(RemainderBB);
3500   LandingPad->addSuccessor(RemainderBB);
3501   LoopBB->addSuccessor(LandingPad);
3502   MachineBasicBlock::iterator First = LandingPad->begin();
3503   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3504     .addReg(SaveExec);
3505 
3506   return InsPt;
3507 }
3508 
3509 // Returns subreg index, offset
3510 static std::pair<unsigned, int>
3511 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3512                             const TargetRegisterClass *SuperRC,
3513                             unsigned VecReg,
3514                             int Offset) {
3515   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3516 
3517   // Skip out of bounds offsets, or else we would end up using an undefined
3518   // register.
3519   if (Offset >= NumElts || Offset < 0)
3520     return std::make_pair(AMDGPU::sub0, Offset);
3521 
3522   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3523 }
3524 
3525 // Return true if the index is an SGPR and was set.
3526 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3527                                  MachineRegisterInfo &MRI,
3528                                  MachineInstr &MI,
3529                                  int Offset,
3530                                  bool UseGPRIdxMode,
3531                                  bool IsIndirectSrc) {
3532   MachineBasicBlock *MBB = MI.getParent();
3533   const DebugLoc &DL = MI.getDebugLoc();
3534   MachineBasicBlock::iterator I(&MI);
3535 
3536   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3537   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3538 
3539   assert(Idx->getReg() != AMDGPU::NoRegister);
3540 
3541   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3542     return false;
3543 
3544   if (UseGPRIdxMode) {
3545     unsigned IdxMode = IsIndirectSrc ?
3546       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3547     if (Offset == 0) {
3548       MachineInstr *SetOn =
3549           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3550               .add(*Idx)
3551               .addImm(IdxMode);
3552 
3553       SetOn->getOperand(3).setIsUndef();
3554     } else {
3555       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3556       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3557           .add(*Idx)
3558           .addImm(Offset);
3559       MachineInstr *SetOn =
3560         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3561         .addReg(Tmp, RegState::Kill)
3562         .addImm(IdxMode);
3563 
3564       SetOn->getOperand(3).setIsUndef();
3565     }
3566 
3567     return true;
3568   }
3569 
3570   if (Offset == 0) {
3571     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3572       .add(*Idx);
3573   } else {
3574     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3575       .add(*Idx)
3576       .addImm(Offset);
3577   }
3578 
3579   return true;
3580 }
3581 
3582 // Control flow needs to be inserted if indexing with a VGPR.
3583 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3584                                           MachineBasicBlock &MBB,
3585                                           const GCNSubtarget &ST) {
3586   const SIInstrInfo *TII = ST.getInstrInfo();
3587   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3588   MachineFunction *MF = MBB.getParent();
3589   MachineRegisterInfo &MRI = MF->getRegInfo();
3590 
3591   Register Dst = MI.getOperand(0).getReg();
3592   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3593   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3594 
3595   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3596 
3597   unsigned SubReg;
3598   std::tie(SubReg, Offset)
3599     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3600 
3601   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3602 
3603   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3604     MachineBasicBlock::iterator I(&MI);
3605     const DebugLoc &DL = MI.getDebugLoc();
3606 
3607     if (UseGPRIdxMode) {
3608       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3609       // to avoid interfering with other uses, so probably requires a new
3610       // optimization pass.
3611       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3612         .addReg(SrcReg, RegState::Undef, SubReg)
3613         .addReg(SrcReg, RegState::Implicit)
3614         .addReg(AMDGPU::M0, RegState::Implicit);
3615       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3616     } else {
3617       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3618         .addReg(SrcReg, RegState::Undef, SubReg)
3619         .addReg(SrcReg, RegState::Implicit);
3620     }
3621 
3622     MI.eraseFromParent();
3623 
3624     return &MBB;
3625   }
3626 
3627   const DebugLoc &DL = MI.getDebugLoc();
3628   MachineBasicBlock::iterator I(&MI);
3629 
3630   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3631   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3632 
3633   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3634 
3635   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3636                               Offset, UseGPRIdxMode, true);
3637   MachineBasicBlock *LoopBB = InsPt->getParent();
3638 
3639   if (UseGPRIdxMode) {
3640     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3641       .addReg(SrcReg, RegState::Undef, SubReg)
3642       .addReg(SrcReg, RegState::Implicit)
3643       .addReg(AMDGPU::M0, RegState::Implicit);
3644     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3645   } else {
3646     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3647       .addReg(SrcReg, RegState::Undef, SubReg)
3648       .addReg(SrcReg, RegState::Implicit);
3649   }
3650 
3651   MI.eraseFromParent();
3652 
3653   return LoopBB;
3654 }
3655 
3656 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3657                                           MachineBasicBlock &MBB,
3658                                           const GCNSubtarget &ST) {
3659   const SIInstrInfo *TII = ST.getInstrInfo();
3660   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3661   MachineFunction *MF = MBB.getParent();
3662   MachineRegisterInfo &MRI = MF->getRegInfo();
3663 
3664   Register Dst = MI.getOperand(0).getReg();
3665   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3666   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3667   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3668   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3669   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3670 
3671   // This can be an immediate, but will be folded later.
3672   assert(Val->getReg());
3673 
3674   unsigned SubReg;
3675   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3676                                                          SrcVec->getReg(),
3677                                                          Offset);
3678   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3679 
3680   if (Idx->getReg() == AMDGPU::NoRegister) {
3681     MachineBasicBlock::iterator I(&MI);
3682     const DebugLoc &DL = MI.getDebugLoc();
3683 
3684     assert(Offset == 0);
3685 
3686     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3687         .add(*SrcVec)
3688         .add(*Val)
3689         .addImm(SubReg);
3690 
3691     MI.eraseFromParent();
3692     return &MBB;
3693   }
3694 
3695   const MCInstrDesc &MovRelDesc
3696     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3697 
3698   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3699     MachineBasicBlock::iterator I(&MI);
3700     const DebugLoc &DL = MI.getDebugLoc();
3701     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3702       .addReg(SrcVec->getReg())
3703       .add(*Val)
3704       .addImm(SubReg);
3705     if (UseGPRIdxMode)
3706       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3707 
3708     MI.eraseFromParent();
3709     return &MBB;
3710   }
3711 
3712   if (Val->isReg())
3713     MRI.clearKillFlags(Val->getReg());
3714 
3715   const DebugLoc &DL = MI.getDebugLoc();
3716 
3717   Register PhiReg = MRI.createVirtualRegister(VecRC);
3718 
3719   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3720                               Offset, UseGPRIdxMode, false);
3721   MachineBasicBlock *LoopBB = InsPt->getParent();
3722 
3723   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3724     .addReg(PhiReg)
3725     .add(*Val)
3726     .addImm(AMDGPU::sub0);
3727   if (UseGPRIdxMode)
3728     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3729 
3730   MI.eraseFromParent();
3731   return LoopBB;
3732 }
3733 
3734 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3735   MachineInstr &MI, MachineBasicBlock *BB) const {
3736 
3737   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3738   MachineFunction *MF = BB->getParent();
3739   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3740 
3741   switch (MI.getOpcode()) {
3742   case AMDGPU::S_UADDO_PSEUDO:
3743   case AMDGPU::S_USUBO_PSEUDO: {
3744     const DebugLoc &DL = MI.getDebugLoc();
3745     MachineOperand &Dest0 = MI.getOperand(0);
3746     MachineOperand &Dest1 = MI.getOperand(1);
3747     MachineOperand &Src0 = MI.getOperand(2);
3748     MachineOperand &Src1 = MI.getOperand(3);
3749 
3750     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3751                        ? AMDGPU::S_ADD_I32
3752                        : AMDGPU::S_SUB_I32;
3753     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3754 
3755     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3756         .addImm(1)
3757         .addImm(0);
3758 
3759     MI.eraseFromParent();
3760     return BB;
3761   }
3762   case AMDGPU::S_ADD_U64_PSEUDO:
3763   case AMDGPU::S_SUB_U64_PSEUDO: {
3764     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3765     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3766     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3767     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3768     const DebugLoc &DL = MI.getDebugLoc();
3769 
3770     MachineOperand &Dest = MI.getOperand(0);
3771     MachineOperand &Src0 = MI.getOperand(1);
3772     MachineOperand &Src1 = MI.getOperand(2);
3773 
3774     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3775     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3776 
3777     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3778         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3779     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3780         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3781 
3782     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3783         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3784     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3785         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3786 
3787     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3788 
3789     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3790     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3791     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3792     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3793     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3794         .addReg(DestSub0)
3795         .addImm(AMDGPU::sub0)
3796         .addReg(DestSub1)
3797         .addImm(AMDGPU::sub1);
3798     MI.eraseFromParent();
3799     return BB;
3800   }
3801   case AMDGPU::V_ADD_U64_PSEUDO:
3802   case AMDGPU::V_SUB_U64_PSEUDO: {
3803     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3804     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3805     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3806     const DebugLoc &DL = MI.getDebugLoc();
3807 
3808     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3809 
3810     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3811 
3812     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3813     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3814 
3815     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3816     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3817 
3818     MachineOperand &Dest = MI.getOperand(0);
3819     MachineOperand &Src0 = MI.getOperand(1);
3820     MachineOperand &Src1 = MI.getOperand(2);
3821 
3822     const TargetRegisterClass *Src0RC = Src0.isReg()
3823                                             ? MRI.getRegClass(Src0.getReg())
3824                                             : &AMDGPU::VReg_64RegClass;
3825     const TargetRegisterClass *Src1RC = Src1.isReg()
3826                                             ? MRI.getRegClass(Src1.getReg())
3827                                             : &AMDGPU::VReg_64RegClass;
3828 
3829     const TargetRegisterClass *Src0SubRC =
3830         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3831     const TargetRegisterClass *Src1SubRC =
3832         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3833 
3834     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3835         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3836     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3837         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3838 
3839     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3840         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3841     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3842         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3843 
3844     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
3845     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3846                                .addReg(CarryReg, RegState::Define)
3847                                .add(SrcReg0Sub0)
3848                                .add(SrcReg1Sub0)
3849                                .addImm(0); // clamp bit
3850 
3851     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3852     MachineInstr *HiHalf =
3853         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3854             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3855             .add(SrcReg0Sub1)
3856             .add(SrcReg1Sub1)
3857             .addReg(CarryReg, RegState::Kill)
3858             .addImm(0); // clamp bit
3859 
3860     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3861         .addReg(DestSub0)
3862         .addImm(AMDGPU::sub0)
3863         .addReg(DestSub1)
3864         .addImm(AMDGPU::sub1);
3865     TII->legalizeOperands(*LoHalf);
3866     TII->legalizeOperands(*HiHalf);
3867     MI.eraseFromParent();
3868     return BB;
3869   }
3870   case AMDGPU::S_ADD_CO_PSEUDO:
3871   case AMDGPU::S_SUB_CO_PSEUDO: {
3872     // This pseudo has a chance to be selected
3873     // only from uniform add/subcarry node. All the VGPR operands
3874     // therefore assumed to be splat vectors.
3875     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3876     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3877     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3878     MachineBasicBlock::iterator MII = MI;
3879     const DebugLoc &DL = MI.getDebugLoc();
3880     MachineOperand &Dest = MI.getOperand(0);
3881     MachineOperand &Src0 = MI.getOperand(2);
3882     MachineOperand &Src1 = MI.getOperand(3);
3883     MachineOperand &Src2 = MI.getOperand(4);
3884     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3885                        ? AMDGPU::S_ADDC_U32
3886                        : AMDGPU::S_SUBB_U32;
3887     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3888       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3889       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3890           .addReg(Src0.getReg());
3891       Src0.setReg(RegOp0);
3892     }
3893     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3894       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3895       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3896           .addReg(Src1.getReg());
3897       Src1.setReg(RegOp1);
3898     }
3899     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3900     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3901       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3902           .addReg(Src2.getReg());
3903       Src2.setReg(RegOp2);
3904     }
3905 
3906     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
3907       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3908           .addReg(Src2.getReg())
3909           .addImm(0);
3910     } else {
3911       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
3912           .addReg(Src2.getReg())
3913           .addImm(0);
3914     }
3915 
3916     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
3917     MI.eraseFromParent();
3918     return BB;
3919   }
3920   case AMDGPU::SI_INIT_M0: {
3921     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3922             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3923         .add(MI.getOperand(0));
3924     MI.eraseFromParent();
3925     return BB;
3926   }
3927   case AMDGPU::SI_INIT_EXEC:
3928     // This should be before all vector instructions.
3929     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3930             AMDGPU::EXEC)
3931         .addImm(MI.getOperand(0).getImm());
3932     MI.eraseFromParent();
3933     return BB;
3934 
3935   case AMDGPU::SI_INIT_EXEC_LO:
3936     // This should be before all vector instructions.
3937     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3938             AMDGPU::EXEC_LO)
3939         .addImm(MI.getOperand(0).getImm());
3940     MI.eraseFromParent();
3941     return BB;
3942 
3943   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3944     // Extract the thread count from an SGPR input and set EXEC accordingly.
3945     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3946     //
3947     // S_BFE_U32 count, input, {shift, 7}
3948     // S_BFM_B64 exec, count, 0
3949     // S_CMP_EQ_U32 count, 64
3950     // S_CMOV_B64 exec, -1
3951     MachineInstr *FirstMI = &*BB->begin();
3952     MachineRegisterInfo &MRI = MF->getRegInfo();
3953     Register InputReg = MI.getOperand(0).getReg();
3954     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3955     bool Found = false;
3956 
3957     // Move the COPY of the input reg to the beginning, so that we can use it.
3958     for (auto I = BB->begin(); I != &MI; I++) {
3959       if (I->getOpcode() != TargetOpcode::COPY ||
3960           I->getOperand(0).getReg() != InputReg)
3961         continue;
3962 
3963       if (I == FirstMI) {
3964         FirstMI = &*++BB->begin();
3965       } else {
3966         I->removeFromParent();
3967         BB->insert(FirstMI, &*I);
3968       }
3969       Found = true;
3970       break;
3971     }
3972     assert(Found);
3973     (void)Found;
3974 
3975     // This should be before all vector instructions.
3976     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3977     bool isWave32 = getSubtarget()->isWave32();
3978     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3979     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3980         .addReg(InputReg)
3981         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3982     BuildMI(*BB, FirstMI, DebugLoc(),
3983             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3984             Exec)
3985         .addReg(CountReg)
3986         .addImm(0);
3987     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3988         .addReg(CountReg, RegState::Kill)
3989         .addImm(getSubtarget()->getWavefrontSize());
3990     BuildMI(*BB, FirstMI, DebugLoc(),
3991             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3992             Exec)
3993         .addImm(-1);
3994     MI.eraseFromParent();
3995     return BB;
3996   }
3997 
3998   case AMDGPU::GET_GROUPSTATICSIZE: {
3999     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4000            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4001     DebugLoc DL = MI.getDebugLoc();
4002     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4003         .add(MI.getOperand(0))
4004         .addImm(MFI->getLDSSize());
4005     MI.eraseFromParent();
4006     return BB;
4007   }
4008   case AMDGPU::SI_INDIRECT_SRC_V1:
4009   case AMDGPU::SI_INDIRECT_SRC_V2:
4010   case AMDGPU::SI_INDIRECT_SRC_V4:
4011   case AMDGPU::SI_INDIRECT_SRC_V8:
4012   case AMDGPU::SI_INDIRECT_SRC_V16:
4013   case AMDGPU::SI_INDIRECT_SRC_V32:
4014     return emitIndirectSrc(MI, *BB, *getSubtarget());
4015   case AMDGPU::SI_INDIRECT_DST_V1:
4016   case AMDGPU::SI_INDIRECT_DST_V2:
4017   case AMDGPU::SI_INDIRECT_DST_V4:
4018   case AMDGPU::SI_INDIRECT_DST_V8:
4019   case AMDGPU::SI_INDIRECT_DST_V16:
4020   case AMDGPU::SI_INDIRECT_DST_V32:
4021     return emitIndirectDst(MI, *BB, *getSubtarget());
4022   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4023   case AMDGPU::SI_KILL_I1_PSEUDO:
4024     return splitKillBlock(MI, BB);
4025   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4026     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4027     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4028     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4029 
4030     Register Dst = MI.getOperand(0).getReg();
4031     Register Src0 = MI.getOperand(1).getReg();
4032     Register Src1 = MI.getOperand(2).getReg();
4033     const DebugLoc &DL = MI.getDebugLoc();
4034     Register SrcCond = MI.getOperand(3).getReg();
4035 
4036     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4037     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4038     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4039     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4040 
4041     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4042       .addReg(SrcCond);
4043     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4044       .addImm(0)
4045       .addReg(Src0, 0, AMDGPU::sub0)
4046       .addImm(0)
4047       .addReg(Src1, 0, AMDGPU::sub0)
4048       .addReg(SrcCondCopy);
4049     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4050       .addImm(0)
4051       .addReg(Src0, 0, AMDGPU::sub1)
4052       .addImm(0)
4053       .addReg(Src1, 0, AMDGPU::sub1)
4054       .addReg(SrcCondCopy);
4055 
4056     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4057       .addReg(DstLo)
4058       .addImm(AMDGPU::sub0)
4059       .addReg(DstHi)
4060       .addImm(AMDGPU::sub1);
4061     MI.eraseFromParent();
4062     return BB;
4063   }
4064   case AMDGPU::SI_BR_UNDEF: {
4065     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4066     const DebugLoc &DL = MI.getDebugLoc();
4067     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4068                            .add(MI.getOperand(0));
4069     Br->getOperand(1).setIsUndef(true); // read undef SCC
4070     MI.eraseFromParent();
4071     return BB;
4072   }
4073   case AMDGPU::ADJCALLSTACKUP:
4074   case AMDGPU::ADJCALLSTACKDOWN: {
4075     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4076     MachineInstrBuilder MIB(*MF, &MI);
4077 
4078     // Add an implicit use of the frame offset reg to prevent the restore copy
4079     // inserted after the call from being reorderd after stack operations in the
4080     // the caller's frame.
4081     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4082         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
4083         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
4084     return BB;
4085   }
4086   case AMDGPU::SI_CALL_ISEL: {
4087     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4088     const DebugLoc &DL = MI.getDebugLoc();
4089 
4090     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4091 
4092     MachineInstrBuilder MIB;
4093     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4094 
4095     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4096       MIB.add(MI.getOperand(I));
4097 
4098     MIB.cloneMemRefs(MI);
4099     MI.eraseFromParent();
4100     return BB;
4101   }
4102   case AMDGPU::V_ADD_I32_e32:
4103   case AMDGPU::V_SUB_I32_e32:
4104   case AMDGPU::V_SUBREV_I32_e32: {
4105     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4106     const DebugLoc &DL = MI.getDebugLoc();
4107     unsigned Opc = MI.getOpcode();
4108 
4109     bool NeedClampOperand = false;
4110     if (TII->pseudoToMCOpcode(Opc) == -1) {
4111       Opc = AMDGPU::getVOPe64(Opc);
4112       NeedClampOperand = true;
4113     }
4114 
4115     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4116     if (TII->isVOP3(*I)) {
4117       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4118       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4119       I.addReg(TRI->getVCC(), RegState::Define);
4120     }
4121     I.add(MI.getOperand(1))
4122      .add(MI.getOperand(2));
4123     if (NeedClampOperand)
4124       I.addImm(0); // clamp bit for e64 encoding
4125 
4126     TII->legalizeOperands(*I);
4127 
4128     MI.eraseFromParent();
4129     return BB;
4130   }
4131   case AMDGPU::DS_GWS_INIT:
4132   case AMDGPU::DS_GWS_SEMA_V:
4133   case AMDGPU::DS_GWS_SEMA_BR:
4134   case AMDGPU::DS_GWS_SEMA_P:
4135   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4136   case AMDGPU::DS_GWS_BARRIER:
4137     // A s_waitcnt 0 is required to be the instruction immediately following.
4138     if (getSubtarget()->hasGWSAutoReplay()) {
4139       bundleInstWithWaitcnt(MI);
4140       return BB;
4141     }
4142 
4143     return emitGWSMemViolTestLoop(MI, BB);
4144   case AMDGPU::S_SETREG_B32: {
4145     if (!getSubtarget()->hasDenormModeInst())
4146       return BB;
4147 
4148     // Try to optimize cases that only set the denormal mode or rounding mode.
4149     //
4150     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4151     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4152     // instead.
4153     //
4154     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4155     // allow you to have a no side effect instruction in the output of a
4156     // sideeffecting pattern.
4157 
4158     // TODO: Should also emit a no side effects pseudo if only FP bits are
4159     // touched, even if not all of them or to a variable.
4160     unsigned ID, Offset, Width;
4161     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4162     if (ID != AMDGPU::Hwreg::ID_MODE)
4163       return BB;
4164 
4165     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4166     const unsigned SetMask = WidthMask << Offset;
4167     unsigned SetDenormOp = 0;
4168     unsigned SetRoundOp = 0;
4169 
4170     // The dedicated instructions can only set the whole denorm or round mode at
4171     // once, not a subset of bits in either.
4172     if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4173                                   AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) {
4174       // If this fully sets both the round and denorm mode, emit the two
4175       // dedicated instructions for these.
4176       assert(Offset == 0);
4177       SetRoundOp = AMDGPU::S_ROUND_MODE;
4178       SetDenormOp = AMDGPU::S_DENORM_MODE;
4179     } else if (Width == 4) {
4180       if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) {
4181         SetRoundOp = AMDGPU::S_ROUND_MODE;
4182         assert(Offset == 0);
4183       } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) {
4184         SetDenormOp = AMDGPU::S_DENORM_MODE;
4185         assert(Offset == 4);
4186       }
4187     }
4188 
4189     if (SetRoundOp || SetDenormOp) {
4190       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4191       MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4192       if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4193         unsigned ImmVal = Def->getOperand(1).getImm();
4194         if (SetRoundOp) {
4195           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4196             .addImm(ImmVal & 0xf);
4197 
4198           // If we also have the denorm mode, get just the denorm mode bits.
4199           ImmVal >>= 4;
4200         }
4201 
4202         if (SetDenormOp) {
4203           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4204             .addImm(ImmVal & 0xf);
4205         }
4206 
4207         MI.eraseFromParent();
4208       }
4209     }
4210 
4211     return BB;
4212   }
4213   default:
4214     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4215   }
4216 }
4217 
4218 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4219   return isTypeLegal(VT.getScalarType());
4220 }
4221 
4222 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4223   // This currently forces unfolding various combinations of fsub into fma with
4224   // free fneg'd operands. As long as we have fast FMA (controlled by
4225   // isFMAFasterThanFMulAndFAdd), we should perform these.
4226 
4227   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4228   // most of these combines appear to be cycle neutral but save on instruction
4229   // count / code size.
4230   return true;
4231 }
4232 
4233 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4234                                          EVT VT) const {
4235   if (!VT.isVector()) {
4236     return MVT::i1;
4237   }
4238   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4239 }
4240 
4241 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4242   // TODO: Should i16 be used always if legal? For now it would force VALU
4243   // shifts.
4244   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4245 }
4246 
4247 // Answering this is somewhat tricky and depends on the specific device which
4248 // have different rates for fma or all f64 operations.
4249 //
4250 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4251 // regardless of which device (although the number of cycles differs between
4252 // devices), so it is always profitable for f64.
4253 //
4254 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4255 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4256 // which we can always do even without fused FP ops since it returns the same
4257 // result as the separate operations and since it is always full
4258 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4259 // however does not support denormals, so we do report fma as faster if we have
4260 // a fast fma device and require denormals.
4261 //
4262 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4263                                                   EVT VT) const {
4264   VT = VT.getScalarType();
4265 
4266   switch (VT.getSimpleVT().SimpleTy) {
4267   case MVT::f32: {
4268     // This is as fast on some subtargets. However, we always have full rate f32
4269     // mad available which returns the same result as the separate operations
4270     // which we should prefer over fma. We can't use this if we want to support
4271     // denormals, so only report this in these cases.
4272     if (hasFP32Denormals(MF))
4273       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4274 
4275     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4276     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4277   }
4278   case MVT::f64:
4279     return true;
4280   case MVT::f16:
4281     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4282   default:
4283     break;
4284   }
4285 
4286   return false;
4287 }
4288 
4289 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4290                                    const SDNode *N) const {
4291   // TODO: Check future ftz flag
4292   // v_mad_f32/v_mac_f32 do not support denormals.
4293   EVT VT = N->getValueType(0);
4294   if (VT == MVT::f32)
4295     return Subtarget->hasMadMacF32Insts() &&
4296            !hasFP32Denormals(DAG.getMachineFunction());
4297   if (VT == MVT::f16) {
4298     return Subtarget->hasMadF16() &&
4299            !hasFP64FP16Denormals(DAG.getMachineFunction());
4300   }
4301 
4302   return false;
4303 }
4304 
4305 //===----------------------------------------------------------------------===//
4306 // Custom DAG Lowering Operations
4307 //===----------------------------------------------------------------------===//
4308 
4309 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4310 // wider vector type is legal.
4311 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4312                                              SelectionDAG &DAG) const {
4313   unsigned Opc = Op.getOpcode();
4314   EVT VT = Op.getValueType();
4315   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4316 
4317   SDValue Lo, Hi;
4318   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4319 
4320   SDLoc SL(Op);
4321   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4322                              Op->getFlags());
4323   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4324                              Op->getFlags());
4325 
4326   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4327 }
4328 
4329 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4330 // wider vector type is legal.
4331 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4332                                               SelectionDAG &DAG) const {
4333   unsigned Opc = Op.getOpcode();
4334   EVT VT = Op.getValueType();
4335   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4336 
4337   SDValue Lo0, Hi0;
4338   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4339   SDValue Lo1, Hi1;
4340   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4341 
4342   SDLoc SL(Op);
4343 
4344   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4345                              Op->getFlags());
4346   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4347                              Op->getFlags());
4348 
4349   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4350 }
4351 
4352 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4353                                               SelectionDAG &DAG) const {
4354   unsigned Opc = Op.getOpcode();
4355   EVT VT = Op.getValueType();
4356   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4357 
4358   SDValue Lo0, Hi0;
4359   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4360   SDValue Lo1, Hi1;
4361   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4362   SDValue Lo2, Hi2;
4363   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4364 
4365   SDLoc SL(Op);
4366 
4367   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4368                              Op->getFlags());
4369   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4370                              Op->getFlags());
4371 
4372   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4373 }
4374 
4375 
4376 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4377   switch (Op.getOpcode()) {
4378   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4379   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4380   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4381   case ISD::LOAD: {
4382     SDValue Result = LowerLOAD(Op, DAG);
4383     assert((!Result.getNode() ||
4384             Result.getNode()->getNumValues() == 2) &&
4385            "Load should return a value and a chain");
4386     return Result;
4387   }
4388 
4389   case ISD::FSIN:
4390   case ISD::FCOS:
4391     return LowerTrig(Op, DAG);
4392   case ISD::SELECT: return LowerSELECT(Op, DAG);
4393   case ISD::FDIV: return LowerFDIV(Op, DAG);
4394   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4395   case ISD::STORE: return LowerSTORE(Op, DAG);
4396   case ISD::GlobalAddress: {
4397     MachineFunction &MF = DAG.getMachineFunction();
4398     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4399     return LowerGlobalAddress(MFI, Op, DAG);
4400   }
4401   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4402   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4403   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4404   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4405   case ISD::INSERT_SUBVECTOR:
4406     return lowerINSERT_SUBVECTOR(Op, DAG);
4407   case ISD::INSERT_VECTOR_ELT:
4408     return lowerINSERT_VECTOR_ELT(Op, DAG);
4409   case ISD::EXTRACT_VECTOR_ELT:
4410     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4411   case ISD::VECTOR_SHUFFLE:
4412     return lowerVECTOR_SHUFFLE(Op, DAG);
4413   case ISD::BUILD_VECTOR:
4414     return lowerBUILD_VECTOR(Op, DAG);
4415   case ISD::FP_ROUND:
4416     return lowerFP_ROUND(Op, DAG);
4417   case ISD::TRAP:
4418     return lowerTRAP(Op, DAG);
4419   case ISD::DEBUGTRAP:
4420     return lowerDEBUGTRAP(Op, DAG);
4421   case ISD::FABS:
4422   case ISD::FNEG:
4423   case ISD::FCANONICALIZE:
4424   case ISD::BSWAP:
4425     return splitUnaryVectorOp(Op, DAG);
4426   case ISD::FMINNUM:
4427   case ISD::FMAXNUM:
4428     return lowerFMINNUM_FMAXNUM(Op, DAG);
4429   case ISD::FMA:
4430     return splitTernaryVectorOp(Op, DAG);
4431   case ISD::SHL:
4432   case ISD::SRA:
4433   case ISD::SRL:
4434   case ISD::ADD:
4435   case ISD::SUB:
4436   case ISD::MUL:
4437   case ISD::SMIN:
4438   case ISD::SMAX:
4439   case ISD::UMIN:
4440   case ISD::UMAX:
4441   case ISD::FADD:
4442   case ISD::FMUL:
4443   case ISD::FMINNUM_IEEE:
4444   case ISD::FMAXNUM_IEEE:
4445     return splitBinaryVectorOp(Op, DAG);
4446   case ISD::SMULO:
4447   case ISD::UMULO:
4448     return lowerXMULO(Op, DAG);
4449   case ISD::DYNAMIC_STACKALLOC:
4450     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4451   }
4452   return SDValue();
4453 }
4454 
4455 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4456                                        const SDLoc &DL,
4457                                        SelectionDAG &DAG, bool Unpacked) {
4458   if (!LoadVT.isVector())
4459     return Result;
4460 
4461   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4462     // Truncate to v2i16/v4i16.
4463     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4464 
4465     // Workaround legalizer not scalarizing truncate after vector op
4466     // legalization byt not creating intermediate vector trunc.
4467     SmallVector<SDValue, 4> Elts;
4468     DAG.ExtractVectorElements(Result, Elts);
4469     for (SDValue &Elt : Elts)
4470       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4471 
4472     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4473 
4474     // Bitcast to original type (v2f16/v4f16).
4475     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4476   }
4477 
4478   // Cast back to the original packed type.
4479   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4480 }
4481 
4482 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4483                                               MemSDNode *M,
4484                                               SelectionDAG &DAG,
4485                                               ArrayRef<SDValue> Ops,
4486                                               bool IsIntrinsic) const {
4487   SDLoc DL(M);
4488 
4489   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4490   EVT LoadVT = M->getValueType(0);
4491 
4492   EVT EquivLoadVT = LoadVT;
4493   if (Unpacked && LoadVT.isVector()) {
4494     EquivLoadVT = LoadVT.isVector() ?
4495       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4496                        LoadVT.getVectorNumElements()) : LoadVT;
4497   }
4498 
4499   // Change from v4f16/v2f16 to EquivLoadVT.
4500   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4501 
4502   SDValue Load
4503     = DAG.getMemIntrinsicNode(
4504       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4505       VTList, Ops, M->getMemoryVT(),
4506       M->getMemOperand());
4507   if (!Unpacked) // Just adjusted the opcode.
4508     return Load;
4509 
4510   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4511 
4512   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4513 }
4514 
4515 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4516                                              SelectionDAG &DAG,
4517                                              ArrayRef<SDValue> Ops) const {
4518   SDLoc DL(M);
4519   EVT LoadVT = M->getValueType(0);
4520   EVT EltType = LoadVT.getScalarType();
4521   EVT IntVT = LoadVT.changeTypeToInteger();
4522 
4523   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4524 
4525   unsigned Opc =
4526       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4527 
4528   if (IsD16) {
4529     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4530   }
4531 
4532   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4533   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4534     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4535 
4536   if (isTypeLegal(LoadVT)) {
4537     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4538                                M->getMemOperand(), DAG);
4539   }
4540 
4541   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4542   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4543   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4544                                         M->getMemOperand(), DAG);
4545   return DAG.getMergeValues(
4546       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4547       DL);
4548 }
4549 
4550 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4551                                   SDNode *N, SelectionDAG &DAG) {
4552   EVT VT = N->getValueType(0);
4553   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4554   int CondCode = CD->getSExtValue();
4555   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4556       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4557     return DAG.getUNDEF(VT);
4558 
4559   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4560 
4561   SDValue LHS = N->getOperand(1);
4562   SDValue RHS = N->getOperand(2);
4563 
4564   SDLoc DL(N);
4565 
4566   EVT CmpVT = LHS.getValueType();
4567   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4568     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4569       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4570     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4571     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4572   }
4573 
4574   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4575 
4576   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4577   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4578 
4579   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4580                               DAG.getCondCode(CCOpcode));
4581   if (VT.bitsEq(CCVT))
4582     return SetCC;
4583   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4584 }
4585 
4586 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4587                                   SDNode *N, SelectionDAG &DAG) {
4588   EVT VT = N->getValueType(0);
4589   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4590 
4591   int CondCode = CD->getSExtValue();
4592   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4593       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4594     return DAG.getUNDEF(VT);
4595   }
4596 
4597   SDValue Src0 = N->getOperand(1);
4598   SDValue Src1 = N->getOperand(2);
4599   EVT CmpVT = Src0.getValueType();
4600   SDLoc SL(N);
4601 
4602   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4603     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4604     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4605   }
4606 
4607   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4608   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4609   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4610   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4611   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4612                               Src1, DAG.getCondCode(CCOpcode));
4613   if (VT.bitsEq(CCVT))
4614     return SetCC;
4615   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4616 }
4617 
4618 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4619                                     SelectionDAG &DAG) {
4620   EVT VT = N->getValueType(0);
4621   SDValue Src = N->getOperand(1);
4622   SDLoc SL(N);
4623 
4624   if (Src.getOpcode() == ISD::SETCC) {
4625     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4626     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4627                        Src.getOperand(1), Src.getOperand(2));
4628   }
4629   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4630     // (ballot 0) -> 0
4631     if (Arg->isNullValue())
4632       return DAG.getConstant(0, SL, VT);
4633 
4634     // (ballot 1) -> EXEC/EXEC_LO
4635     if (Arg->isOne()) {
4636       Register Exec;
4637       if (VT.getScalarSizeInBits() == 32)
4638         Exec = AMDGPU::EXEC_LO;
4639       else if (VT.getScalarSizeInBits() == 64)
4640         Exec = AMDGPU::EXEC;
4641       else
4642         return SDValue();
4643 
4644       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4645     }
4646   }
4647 
4648   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4649   // ISD::SETNE)
4650   return DAG.getNode(
4651       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4652       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4653 }
4654 
4655 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4656                                           SmallVectorImpl<SDValue> &Results,
4657                                           SelectionDAG &DAG) const {
4658   switch (N->getOpcode()) {
4659   case ISD::INSERT_VECTOR_ELT: {
4660     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4661       Results.push_back(Res);
4662     return;
4663   }
4664   case ISD::EXTRACT_VECTOR_ELT: {
4665     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4666       Results.push_back(Res);
4667     return;
4668   }
4669   case ISD::INTRINSIC_WO_CHAIN: {
4670     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4671     switch (IID) {
4672     case Intrinsic::amdgcn_cvt_pkrtz: {
4673       SDValue Src0 = N->getOperand(1);
4674       SDValue Src1 = N->getOperand(2);
4675       SDLoc SL(N);
4676       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4677                                 Src0, Src1);
4678       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4679       return;
4680     }
4681     case Intrinsic::amdgcn_cvt_pknorm_i16:
4682     case Intrinsic::amdgcn_cvt_pknorm_u16:
4683     case Intrinsic::amdgcn_cvt_pk_i16:
4684     case Intrinsic::amdgcn_cvt_pk_u16: {
4685       SDValue Src0 = N->getOperand(1);
4686       SDValue Src1 = N->getOperand(2);
4687       SDLoc SL(N);
4688       unsigned Opcode;
4689 
4690       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4691         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4692       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4693         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4694       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4695         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4696       else
4697         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4698 
4699       EVT VT = N->getValueType(0);
4700       if (isTypeLegal(VT))
4701         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4702       else {
4703         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4704         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4705       }
4706       return;
4707     }
4708     }
4709     break;
4710   }
4711   case ISD::INTRINSIC_W_CHAIN: {
4712     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4713       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4714         // FIXME: Hacky
4715         Results.push_back(Res.getOperand(0));
4716         Results.push_back(Res.getOperand(1));
4717       } else {
4718         Results.push_back(Res);
4719         Results.push_back(Res.getValue(1));
4720       }
4721       return;
4722     }
4723 
4724     break;
4725   }
4726   case ISD::SELECT: {
4727     SDLoc SL(N);
4728     EVT VT = N->getValueType(0);
4729     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4730     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4731     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4732 
4733     EVT SelectVT = NewVT;
4734     if (NewVT.bitsLT(MVT::i32)) {
4735       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4736       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4737       SelectVT = MVT::i32;
4738     }
4739 
4740     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4741                                     N->getOperand(0), LHS, RHS);
4742 
4743     if (NewVT != SelectVT)
4744       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4745     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4746     return;
4747   }
4748   case ISD::FNEG: {
4749     if (N->getValueType(0) != MVT::v2f16)
4750       break;
4751 
4752     SDLoc SL(N);
4753     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4754 
4755     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4756                              BC,
4757                              DAG.getConstant(0x80008000, SL, MVT::i32));
4758     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4759     return;
4760   }
4761   case ISD::FABS: {
4762     if (N->getValueType(0) != MVT::v2f16)
4763       break;
4764 
4765     SDLoc SL(N);
4766     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4767 
4768     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4769                              BC,
4770                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4771     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4772     return;
4773   }
4774   default:
4775     break;
4776   }
4777 }
4778 
4779 /// Helper function for LowerBRCOND
4780 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4781 
4782   SDNode *Parent = Value.getNode();
4783   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4784        I != E; ++I) {
4785 
4786     if (I.getUse().get() != Value)
4787       continue;
4788 
4789     if (I->getOpcode() == Opcode)
4790       return *I;
4791   }
4792   return nullptr;
4793 }
4794 
4795 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4796   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4797     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4798     case Intrinsic::amdgcn_if:
4799       return AMDGPUISD::IF;
4800     case Intrinsic::amdgcn_else:
4801       return AMDGPUISD::ELSE;
4802     case Intrinsic::amdgcn_loop:
4803       return AMDGPUISD::LOOP;
4804     case Intrinsic::amdgcn_end_cf:
4805       llvm_unreachable("should not occur");
4806     default:
4807       return 0;
4808     }
4809   }
4810 
4811   // break, if_break, else_break are all only used as inputs to loop, not
4812   // directly as branch conditions.
4813   return 0;
4814 }
4815 
4816 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4817   const Triple &TT = getTargetMachine().getTargetTriple();
4818   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4819           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4820          AMDGPU::shouldEmitConstantsToTextSection(TT);
4821 }
4822 
4823 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4824   // FIXME: Either avoid relying on address space here or change the default
4825   // address space for functions to avoid the explicit check.
4826   return (GV->getValueType()->isFunctionTy() ||
4827           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4828          !shouldEmitFixup(GV) &&
4829          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4830 }
4831 
4832 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4833   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4834 }
4835 
4836 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4837   if (!GV->hasExternalLinkage())
4838     return true;
4839 
4840   const auto OS = getTargetMachine().getTargetTriple().getOS();
4841   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4842 }
4843 
4844 /// This transforms the control flow intrinsics to get the branch destination as
4845 /// last parameter, also switches branch target with BR if the need arise
4846 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4847                                       SelectionDAG &DAG) const {
4848   SDLoc DL(BRCOND);
4849 
4850   SDNode *Intr = BRCOND.getOperand(1).getNode();
4851   SDValue Target = BRCOND.getOperand(2);
4852   SDNode *BR = nullptr;
4853   SDNode *SetCC = nullptr;
4854 
4855   if (Intr->getOpcode() == ISD::SETCC) {
4856     // As long as we negate the condition everything is fine
4857     SetCC = Intr;
4858     Intr = SetCC->getOperand(0).getNode();
4859 
4860   } else {
4861     // Get the target from BR if we don't negate the condition
4862     BR = findUser(BRCOND, ISD::BR);
4863     assert(BR && "brcond missing unconditional branch user");
4864     Target = BR->getOperand(1);
4865   }
4866 
4867   unsigned CFNode = isCFIntrinsic(Intr);
4868   if (CFNode == 0) {
4869     // This is a uniform branch so we don't need to legalize.
4870     return BRCOND;
4871   }
4872 
4873   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4874                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4875 
4876   assert(!SetCC ||
4877         (SetCC->getConstantOperandVal(1) == 1 &&
4878          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4879                                                              ISD::SETNE));
4880 
4881   // operands of the new intrinsic call
4882   SmallVector<SDValue, 4> Ops;
4883   if (HaveChain)
4884     Ops.push_back(BRCOND.getOperand(0));
4885 
4886   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4887   Ops.push_back(Target);
4888 
4889   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4890 
4891   // build the new intrinsic call
4892   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4893 
4894   if (!HaveChain) {
4895     SDValue Ops[] =  {
4896       SDValue(Result, 0),
4897       BRCOND.getOperand(0)
4898     };
4899 
4900     Result = DAG.getMergeValues(Ops, DL).getNode();
4901   }
4902 
4903   if (BR) {
4904     // Give the branch instruction our target
4905     SDValue Ops[] = {
4906       BR->getOperand(0),
4907       BRCOND.getOperand(2)
4908     };
4909     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4910     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4911   }
4912 
4913   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4914 
4915   // Copy the intrinsic results to registers
4916   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4917     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4918     if (!CopyToReg)
4919       continue;
4920 
4921     Chain = DAG.getCopyToReg(
4922       Chain, DL,
4923       CopyToReg->getOperand(1),
4924       SDValue(Result, i - 1),
4925       SDValue());
4926 
4927     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4928   }
4929 
4930   // Remove the old intrinsic from the chain
4931   DAG.ReplaceAllUsesOfValueWith(
4932     SDValue(Intr, Intr->getNumValues() - 1),
4933     Intr->getOperand(0));
4934 
4935   return Chain;
4936 }
4937 
4938 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4939                                           SelectionDAG &DAG) const {
4940   MVT VT = Op.getSimpleValueType();
4941   SDLoc DL(Op);
4942   // Checking the depth
4943   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4944     return DAG.getConstant(0, DL, VT);
4945 
4946   MachineFunction &MF = DAG.getMachineFunction();
4947   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4948   // Check for kernel and shader functions
4949   if (Info->isEntryFunction())
4950     return DAG.getConstant(0, DL, VT);
4951 
4952   MachineFrameInfo &MFI = MF.getFrameInfo();
4953   // There is a call to @llvm.returnaddress in this function
4954   MFI.setReturnAddressIsTaken(true);
4955 
4956   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4957   // Get the return address reg and mark it as an implicit live-in
4958   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4959 
4960   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4961 }
4962 
4963 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4964                                             SDValue Op,
4965                                             const SDLoc &DL,
4966                                             EVT VT) const {
4967   return Op.getValueType().bitsLE(VT) ?
4968       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4969     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4970                 DAG.getTargetConstant(0, DL, MVT::i32));
4971 }
4972 
4973 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4974   assert(Op.getValueType() == MVT::f16 &&
4975          "Do not know how to custom lower FP_ROUND for non-f16 type");
4976 
4977   SDValue Src = Op.getOperand(0);
4978   EVT SrcVT = Src.getValueType();
4979   if (SrcVT != MVT::f64)
4980     return Op;
4981 
4982   SDLoc DL(Op);
4983 
4984   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4985   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4986   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4987 }
4988 
4989 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4990                                                SelectionDAG &DAG) const {
4991   EVT VT = Op.getValueType();
4992   const MachineFunction &MF = DAG.getMachineFunction();
4993   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4994   bool IsIEEEMode = Info->getMode().IEEE;
4995 
4996   // FIXME: Assert during selection that this is only selected for
4997   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4998   // mode functions, but this happens to be OK since it's only done in cases
4999   // where there is known no sNaN.
5000   if (IsIEEEMode)
5001     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5002 
5003   if (VT == MVT::v4f16)
5004     return splitBinaryVectorOp(Op, DAG);
5005   return Op;
5006 }
5007 
5008 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5009   EVT VT = Op.getValueType();
5010   SDLoc SL(Op);
5011   SDValue LHS = Op.getOperand(0);
5012   SDValue RHS = Op.getOperand(1);
5013   bool isSigned = Op.getOpcode() == ISD::SMULO;
5014 
5015   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5016     const APInt &C = RHSC->getAPIntValue();
5017     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5018     if (C.isPowerOf2()) {
5019       // smulo(x, signed_min) is same as umulo(x, signed_min).
5020       bool UseArithShift = isSigned && !C.isMinSignedValue();
5021       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5022       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5023       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5024           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5025                       SL, VT, Result, ShiftAmt),
5026           LHS, ISD::SETNE);
5027       return DAG.getMergeValues({ Result, Overflow }, SL);
5028     }
5029   }
5030 
5031   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5032   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5033                             SL, VT, LHS, RHS);
5034 
5035   SDValue Sign = isSigned
5036     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5037                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5038     : DAG.getConstant(0, SL, VT);
5039   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5040 
5041   return DAG.getMergeValues({ Result, Overflow }, SL);
5042 }
5043 
5044 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5045   SDLoc SL(Op);
5046   SDValue Chain = Op.getOperand(0);
5047 
5048   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5049       !Subtarget->isTrapHandlerEnabled())
5050     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5051 
5052   MachineFunction &MF = DAG.getMachineFunction();
5053   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5054   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
5055   assert(UserSGPR != AMDGPU::NoRegister);
5056   SDValue QueuePtr = CreateLiveInRegister(
5057     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5058   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5059   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5060                                    QueuePtr, SDValue());
5061   SDValue Ops[] = {
5062     ToReg,
5063     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5064     SGPR01,
5065     ToReg.getValue(1)
5066   };
5067   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5068 }
5069 
5070 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5071   SDLoc SL(Op);
5072   SDValue Chain = Op.getOperand(0);
5073   MachineFunction &MF = DAG.getMachineFunction();
5074 
5075   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5076       !Subtarget->isTrapHandlerEnabled()) {
5077     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5078                                      "debugtrap handler not supported",
5079                                      Op.getDebugLoc(),
5080                                      DS_Warning);
5081     LLVMContext &Ctx = MF.getFunction().getContext();
5082     Ctx.diagnose(NoTrap);
5083     return Chain;
5084   }
5085 
5086   SDValue Ops[] = {
5087     Chain,
5088     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5089   };
5090   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5091 }
5092 
5093 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5094                                              SelectionDAG &DAG) const {
5095   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5096   if (Subtarget->hasApertureRegs()) {
5097     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5098         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5099         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5100     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5101         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5102         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5103     unsigned Encoding =
5104         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5105         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5106         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5107 
5108     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5109     SDValue ApertureReg = SDValue(
5110         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5111     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5112     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5113   }
5114 
5115   MachineFunction &MF = DAG.getMachineFunction();
5116   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5117   Register UserSGPR = Info->getQueuePtrUserSGPR();
5118   assert(UserSGPR != AMDGPU::NoRegister);
5119 
5120   SDValue QueuePtr = CreateLiveInRegister(
5121     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5122 
5123   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5124   // private_segment_aperture_base_hi.
5125   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5126 
5127   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
5128 
5129   // TODO: Use custom target PseudoSourceValue.
5130   // TODO: We should use the value from the IR intrinsic call, but it might not
5131   // be available and how do we get it?
5132   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5133   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5134                      MinAlign(64, StructOffset),
5135                      MachineMemOperand::MODereferenceable |
5136                          MachineMemOperand::MOInvariant);
5137 }
5138 
5139 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5140                                              SelectionDAG &DAG) const {
5141   SDLoc SL(Op);
5142   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5143 
5144   SDValue Src = ASC->getOperand(0);
5145   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5146 
5147   const AMDGPUTargetMachine &TM =
5148     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5149 
5150   // flat -> local/private
5151   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5152     unsigned DestAS = ASC->getDestAddressSpace();
5153 
5154     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5155         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5156       unsigned NullVal = TM.getNullPointerValue(DestAS);
5157       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5158       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5159       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5160 
5161       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5162                          NonNull, Ptr, SegmentNullPtr);
5163     }
5164   }
5165 
5166   // local/private -> flat
5167   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5168     unsigned SrcAS = ASC->getSrcAddressSpace();
5169 
5170     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5171         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5172       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5173       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5174 
5175       SDValue NonNull
5176         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5177 
5178       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5179       SDValue CvtPtr
5180         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5181 
5182       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5183                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5184                          FlatNullPtr);
5185     }
5186   }
5187 
5188   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5189       Src.getValueType() == MVT::i64)
5190     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5191 
5192   // global <-> flat are no-ops and never emitted.
5193 
5194   const MachineFunction &MF = DAG.getMachineFunction();
5195   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5196     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5197   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5198 
5199   return DAG.getUNDEF(ASC->getValueType(0));
5200 }
5201 
5202 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5203 // the small vector and inserting them into the big vector. That is better than
5204 // the default expansion of doing it via a stack slot. Even though the use of
5205 // the stack slot would be optimized away afterwards, the stack slot itself
5206 // remains.
5207 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5208                                                 SelectionDAG &DAG) const {
5209   SDValue Vec = Op.getOperand(0);
5210   SDValue Ins = Op.getOperand(1);
5211   SDValue Idx = Op.getOperand(2);
5212   EVT VecVT = Vec.getValueType();
5213   EVT InsVT = Ins.getValueType();
5214   EVT EltVT = VecVT.getVectorElementType();
5215   unsigned InsNumElts = InsVT.getVectorNumElements();
5216   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5217   SDLoc SL(Op);
5218 
5219   for (unsigned I = 0; I != InsNumElts; ++I) {
5220     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5221                               DAG.getConstant(I, SL, MVT::i32));
5222     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5223                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5224   }
5225   return Vec;
5226 }
5227 
5228 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5229                                                  SelectionDAG &DAG) const {
5230   SDValue Vec = Op.getOperand(0);
5231   SDValue InsVal = Op.getOperand(1);
5232   SDValue Idx = Op.getOperand(2);
5233   EVT VecVT = Vec.getValueType();
5234   EVT EltVT = VecVT.getVectorElementType();
5235   unsigned VecSize = VecVT.getSizeInBits();
5236   unsigned EltSize = EltVT.getSizeInBits();
5237 
5238 
5239   assert(VecSize <= 64);
5240 
5241   unsigned NumElts = VecVT.getVectorNumElements();
5242   SDLoc SL(Op);
5243   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5244 
5245   if (NumElts == 4 && EltSize == 16 && KIdx) {
5246     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5247 
5248     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5249                                  DAG.getConstant(0, SL, MVT::i32));
5250     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5251                                  DAG.getConstant(1, SL, MVT::i32));
5252 
5253     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5254     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5255 
5256     unsigned Idx = KIdx->getZExtValue();
5257     bool InsertLo = Idx < 2;
5258     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5259       InsertLo ? LoVec : HiVec,
5260       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5261       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5262 
5263     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5264 
5265     SDValue Concat = InsertLo ?
5266       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5267       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5268 
5269     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5270   }
5271 
5272   if (isa<ConstantSDNode>(Idx))
5273     return SDValue();
5274 
5275   MVT IntVT = MVT::getIntegerVT(VecSize);
5276 
5277   // Avoid stack access for dynamic indexing.
5278   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5279 
5280   // Create a congruent vector with the target value in each element so that
5281   // the required element can be masked and ORed into the target vector.
5282   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5283                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5284 
5285   assert(isPowerOf2_32(EltSize));
5286   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5287 
5288   // Convert vector index to bit-index.
5289   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5290 
5291   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5292   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5293                             DAG.getConstant(0xffff, SL, IntVT),
5294                             ScaledIdx);
5295 
5296   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5297   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5298                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5299 
5300   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5301   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5302 }
5303 
5304 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5305                                                   SelectionDAG &DAG) const {
5306   SDLoc SL(Op);
5307 
5308   EVT ResultVT = Op.getValueType();
5309   SDValue Vec = Op.getOperand(0);
5310   SDValue Idx = Op.getOperand(1);
5311   EVT VecVT = Vec.getValueType();
5312   unsigned VecSize = VecVT.getSizeInBits();
5313   EVT EltVT = VecVT.getVectorElementType();
5314   assert(VecSize <= 64);
5315 
5316   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5317 
5318   // Make sure we do any optimizations that will make it easier to fold
5319   // source modifiers before obscuring it with bit operations.
5320 
5321   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5322   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5323     return Combined;
5324 
5325   unsigned EltSize = EltVT.getSizeInBits();
5326   assert(isPowerOf2_32(EltSize));
5327 
5328   MVT IntVT = MVT::getIntegerVT(VecSize);
5329   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5330 
5331   // Convert vector index to bit-index (* EltSize)
5332   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5333 
5334   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5335   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5336 
5337   if (ResultVT == MVT::f16) {
5338     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5339     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5340   }
5341 
5342   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5343 }
5344 
5345 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5346   assert(Elt % 2 == 0);
5347   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5348 }
5349 
5350 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5351                                               SelectionDAG &DAG) const {
5352   SDLoc SL(Op);
5353   EVT ResultVT = Op.getValueType();
5354   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5355 
5356   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5357   EVT EltVT = PackVT.getVectorElementType();
5358   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5359 
5360   // vector_shuffle <0,1,6,7> lhs, rhs
5361   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5362   //
5363   // vector_shuffle <6,7,2,3> lhs, rhs
5364   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5365   //
5366   // vector_shuffle <6,7,0,1> lhs, rhs
5367   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5368 
5369   // Avoid scalarizing when both halves are reading from consecutive elements.
5370   SmallVector<SDValue, 4> Pieces;
5371   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5372     if (elementPairIsContiguous(SVN->getMask(), I)) {
5373       const int Idx = SVN->getMaskElt(I);
5374       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5375       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5376       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5377                                     PackVT, SVN->getOperand(VecIdx),
5378                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5379       Pieces.push_back(SubVec);
5380     } else {
5381       const int Idx0 = SVN->getMaskElt(I);
5382       const int Idx1 = SVN->getMaskElt(I + 1);
5383       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5384       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5385       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5386       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5387 
5388       SDValue Vec0 = SVN->getOperand(VecIdx0);
5389       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5390                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5391 
5392       SDValue Vec1 = SVN->getOperand(VecIdx1);
5393       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5394                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5395       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5396     }
5397   }
5398 
5399   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5400 }
5401 
5402 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5403                                             SelectionDAG &DAG) const {
5404   SDLoc SL(Op);
5405   EVT VT = Op.getValueType();
5406 
5407   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5408     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5409 
5410     // Turn into pair of packed build_vectors.
5411     // TODO: Special case for constants that can be materialized with s_mov_b64.
5412     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5413                                     { Op.getOperand(0), Op.getOperand(1) });
5414     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5415                                     { Op.getOperand(2), Op.getOperand(3) });
5416 
5417     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5418     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5419 
5420     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5421     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5422   }
5423 
5424   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5425   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5426 
5427   SDValue Lo = Op.getOperand(0);
5428   SDValue Hi = Op.getOperand(1);
5429 
5430   // Avoid adding defined bits with the zero_extend.
5431   if (Hi.isUndef()) {
5432     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5433     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5434     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5435   }
5436 
5437   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5438   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5439 
5440   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5441                               DAG.getConstant(16, SL, MVT::i32));
5442   if (Lo.isUndef())
5443     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5444 
5445   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5446   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5447 
5448   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5449   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5450 }
5451 
5452 bool
5453 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5454   // We can fold offsets for anything that doesn't require a GOT relocation.
5455   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5456           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5457           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5458          !shouldEmitGOTReloc(GA->getGlobal());
5459 }
5460 
5461 static SDValue
5462 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5463                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5464                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5465   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5466   // lowered to the following code sequence:
5467   //
5468   // For constant address space:
5469   //   s_getpc_b64 s[0:1]
5470   //   s_add_u32 s0, s0, $symbol
5471   //   s_addc_u32 s1, s1, 0
5472   //
5473   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5474   //   a fixup or relocation is emitted to replace $symbol with a literal
5475   //   constant, which is a pc-relative offset from the encoding of the $symbol
5476   //   operand to the global variable.
5477   //
5478   // For global address space:
5479   //   s_getpc_b64 s[0:1]
5480   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5481   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5482   //
5483   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5484   //   fixups or relocations are emitted to replace $symbol@*@lo and
5485   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5486   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5487   //   operand to the global variable.
5488   //
5489   // What we want here is an offset from the value returned by s_getpc
5490   // (which is the address of the s_add_u32 instruction) to the global
5491   // variable, but since the encoding of $symbol starts 4 bytes after the start
5492   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5493   // small. This requires us to add 4 to the global variable offset in order to
5494   // compute the correct address.
5495   SDValue PtrLo =
5496       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5497   SDValue PtrHi;
5498   if (GAFlags == SIInstrInfo::MO_NONE) {
5499     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5500   } else {
5501     PtrHi =
5502         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5503   }
5504   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5505 }
5506 
5507 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5508                                              SDValue Op,
5509                                              SelectionDAG &DAG) const {
5510   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5511   const GlobalValue *GV = GSD->getGlobal();
5512   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5513        shouldUseLDSConstAddress(GV)) ||
5514       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5515       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5516     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5517 
5518   SDLoc DL(GSD);
5519   EVT PtrVT = Op.getValueType();
5520 
5521   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5522     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5523                                             SIInstrInfo::MO_ABS32_LO);
5524     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5525   }
5526 
5527   if (shouldEmitFixup(GV))
5528     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5529   else if (shouldEmitPCReloc(GV))
5530     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5531                                    SIInstrInfo::MO_REL32);
5532 
5533   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5534                                             SIInstrInfo::MO_GOTPCREL32);
5535 
5536   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5537   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5538   const DataLayout &DataLayout = DAG.getDataLayout();
5539   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5540   MachinePointerInfo PtrInfo
5541     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5542 
5543   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5544                      MachineMemOperand::MODereferenceable |
5545                          MachineMemOperand::MOInvariant);
5546 }
5547 
5548 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5549                                    const SDLoc &DL, SDValue V) const {
5550   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5551   // the destination register.
5552   //
5553   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5554   // so we will end up with redundant moves to m0.
5555   //
5556   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5557 
5558   // A Null SDValue creates a glue result.
5559   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5560                                   V, Chain);
5561   return SDValue(M0, 0);
5562 }
5563 
5564 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5565                                                  SDValue Op,
5566                                                  MVT VT,
5567                                                  unsigned Offset) const {
5568   SDLoc SL(Op);
5569   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5570                                            DAG.getEntryNode(), Offset, 4, false);
5571   // The local size values will have the hi 16-bits as zero.
5572   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5573                      DAG.getValueType(VT));
5574 }
5575 
5576 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5577                                         EVT VT) {
5578   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5579                                       "non-hsa intrinsic with hsa target",
5580                                       DL.getDebugLoc());
5581   DAG.getContext()->diagnose(BadIntrin);
5582   return DAG.getUNDEF(VT);
5583 }
5584 
5585 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5586                                          EVT VT) {
5587   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5588                                       "intrinsic not supported on subtarget",
5589                                       DL.getDebugLoc());
5590   DAG.getContext()->diagnose(BadIntrin);
5591   return DAG.getUNDEF(VT);
5592 }
5593 
5594 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5595                                     ArrayRef<SDValue> Elts) {
5596   assert(!Elts.empty());
5597   MVT Type;
5598   unsigned NumElts;
5599 
5600   if (Elts.size() == 1) {
5601     Type = MVT::f32;
5602     NumElts = 1;
5603   } else if (Elts.size() == 2) {
5604     Type = MVT::v2f32;
5605     NumElts = 2;
5606   } else if (Elts.size() == 3) {
5607     Type = MVT::v3f32;
5608     NumElts = 3;
5609   } else if (Elts.size() <= 4) {
5610     Type = MVT::v4f32;
5611     NumElts = 4;
5612   } else if (Elts.size() <= 8) {
5613     Type = MVT::v8f32;
5614     NumElts = 8;
5615   } else {
5616     assert(Elts.size() <= 16);
5617     Type = MVT::v16f32;
5618     NumElts = 16;
5619   }
5620 
5621   SmallVector<SDValue, 16> VecElts(NumElts);
5622   for (unsigned i = 0; i < Elts.size(); ++i) {
5623     SDValue Elt = Elts[i];
5624     if (Elt.getValueType() != MVT::f32)
5625       Elt = DAG.getBitcast(MVT::f32, Elt);
5626     VecElts[i] = Elt;
5627   }
5628   for (unsigned i = Elts.size(); i < NumElts; ++i)
5629     VecElts[i] = DAG.getUNDEF(MVT::f32);
5630 
5631   if (NumElts == 1)
5632     return VecElts[0];
5633   return DAG.getBuildVector(Type, DL, VecElts);
5634 }
5635 
5636 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5637                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5638   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5639 
5640   uint64_t Value = CachePolicyConst->getZExtValue();
5641   SDLoc DL(CachePolicy);
5642   if (GLC) {
5643     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5644     Value &= ~(uint64_t)0x1;
5645   }
5646   if (SLC) {
5647     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5648     Value &= ~(uint64_t)0x2;
5649   }
5650   if (DLC) {
5651     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5652     Value &= ~(uint64_t)0x4;
5653   }
5654 
5655   return Value == 0;
5656 }
5657 
5658 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5659                               SDValue Src, int ExtraElts) {
5660   EVT SrcVT = Src.getValueType();
5661 
5662   SmallVector<SDValue, 8> Elts;
5663 
5664   if (SrcVT.isVector())
5665     DAG.ExtractVectorElements(Src, Elts);
5666   else
5667     Elts.push_back(Src);
5668 
5669   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5670   while (ExtraElts--)
5671     Elts.push_back(Undef);
5672 
5673   return DAG.getBuildVector(CastVT, DL, Elts);
5674 }
5675 
5676 // Re-construct the required return value for a image load intrinsic.
5677 // This is more complicated due to the optional use TexFailCtrl which means the required
5678 // return type is an aggregate
5679 static SDValue constructRetValue(SelectionDAG &DAG,
5680                                  MachineSDNode *Result,
5681                                  ArrayRef<EVT> ResultTypes,
5682                                  bool IsTexFail, bool Unpacked, bool IsD16,
5683                                  int DMaskPop, int NumVDataDwords,
5684                                  const SDLoc &DL, LLVMContext &Context) {
5685   // Determine the required return type. This is the same regardless of IsTexFail flag
5686   EVT ReqRetVT = ResultTypes[0];
5687   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5688   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5689     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5690 
5691   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5692     DMaskPop : (DMaskPop + 1) / 2;
5693 
5694   MVT DataDwordVT = NumDataDwords == 1 ?
5695     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5696 
5697   MVT MaskPopVT = MaskPopDwords == 1 ?
5698     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5699 
5700   SDValue Data(Result, 0);
5701   SDValue TexFail;
5702 
5703   if (IsTexFail) {
5704     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5705     if (MaskPopVT.isVector()) {
5706       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5707                          SDValue(Result, 0), ZeroIdx);
5708     } else {
5709       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5710                          SDValue(Result, 0), ZeroIdx);
5711     }
5712 
5713     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5714                           SDValue(Result, 0),
5715                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5716   }
5717 
5718   if (DataDwordVT.isVector())
5719     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5720                           NumDataDwords - MaskPopDwords);
5721 
5722   if (IsD16)
5723     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5724 
5725   if (!ReqRetVT.isVector())
5726     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5727 
5728   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5729 
5730   if (TexFail)
5731     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5732 
5733   if (Result->getNumValues() == 1)
5734     return Data;
5735 
5736   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5737 }
5738 
5739 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5740                          SDValue *LWE, bool &IsTexFail) {
5741   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5742 
5743   uint64_t Value = TexFailCtrlConst->getZExtValue();
5744   if (Value) {
5745     IsTexFail = true;
5746   }
5747 
5748   SDLoc DL(TexFailCtrlConst);
5749   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5750   Value &= ~(uint64_t)0x1;
5751   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5752   Value &= ~(uint64_t)0x2;
5753 
5754   return Value == 0;
5755 }
5756 
5757 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5758                                         MVT PackVectorVT,
5759                                         SmallVectorImpl<SDValue> &PackedAddrs,
5760                                         unsigned DimIdx, unsigned EndIdx,
5761                                         unsigned NumGradients) {
5762   SDLoc DL(Op);
5763   for (unsigned I = DimIdx; I < EndIdx; I++) {
5764     SDValue Addr = Op.getOperand(I);
5765 
5766     // Gradients are packed with undef for each coordinate.
5767     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5768     // 1D: undef,dx/dh; undef,dx/dv
5769     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5770     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5771     if (((I + 1) >= EndIdx) ||
5772         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5773                                          I == DimIdx + NumGradients - 1))) {
5774       if (Addr.getValueType() != MVT::i16)
5775         Addr = DAG.getBitcast(MVT::i16, Addr);
5776       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5777     } else {
5778       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5779       I++;
5780     }
5781     Addr = DAG.getBitcast(MVT::f32, Addr);
5782     PackedAddrs.push_back(Addr);
5783   }
5784 }
5785 
5786 SDValue SITargetLowering::lowerImage(SDValue Op,
5787                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5788                                      SelectionDAG &DAG) const {
5789   SDLoc DL(Op);
5790   MachineFunction &MF = DAG.getMachineFunction();
5791   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5792   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5793       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5794   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5795   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5796       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5797   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5798       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5799   unsigned IntrOpcode = Intr->BaseOpcode;
5800   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5801 
5802   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5803   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5804   bool IsD16 = false;
5805   bool IsG16 = false;
5806   bool IsA16 = false;
5807   SDValue VData;
5808   int NumVDataDwords;
5809   bool AdjustRetType = false;
5810 
5811   unsigned AddrIdx; // Index of first address argument
5812   unsigned DMask;
5813   unsigned DMaskLanes = 0;
5814 
5815   if (BaseOpcode->Atomic) {
5816     VData = Op.getOperand(2);
5817 
5818     bool Is64Bit = VData.getValueType() == MVT::i64;
5819     if (BaseOpcode->AtomicX2) {
5820       SDValue VData2 = Op.getOperand(3);
5821       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5822                                  {VData, VData2});
5823       if (Is64Bit)
5824         VData = DAG.getBitcast(MVT::v4i32, VData);
5825 
5826       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5827       DMask = Is64Bit ? 0xf : 0x3;
5828       NumVDataDwords = Is64Bit ? 4 : 2;
5829       AddrIdx = 4;
5830     } else {
5831       DMask = Is64Bit ? 0x3 : 0x1;
5832       NumVDataDwords = Is64Bit ? 2 : 1;
5833       AddrIdx = 3;
5834     }
5835   } else {
5836     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5837     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5838     DMask = DMaskConst->getZExtValue();
5839     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5840 
5841     if (BaseOpcode->Store) {
5842       VData = Op.getOperand(2);
5843 
5844       MVT StoreVT = VData.getSimpleValueType();
5845       if (StoreVT.getScalarType() == MVT::f16) {
5846         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5847           return Op; // D16 is unsupported for this instruction
5848 
5849         IsD16 = true;
5850         VData = handleD16VData(VData, DAG);
5851       }
5852 
5853       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5854     } else {
5855       // Work out the num dwords based on the dmask popcount and underlying type
5856       // and whether packing is supported.
5857       MVT LoadVT = ResultTypes[0].getSimpleVT();
5858       if (LoadVT.getScalarType() == MVT::f16) {
5859         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5860           return Op; // D16 is unsupported for this instruction
5861 
5862         IsD16 = true;
5863       }
5864 
5865       // Confirm that the return type is large enough for the dmask specified
5866       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5867           (!LoadVT.isVector() && DMaskLanes > 1))
5868           return Op;
5869 
5870       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5871         NumVDataDwords = (DMaskLanes + 1) / 2;
5872       else
5873         NumVDataDwords = DMaskLanes;
5874 
5875       AdjustRetType = true;
5876     }
5877 
5878     AddrIdx = DMaskIdx + 1;
5879   }
5880 
5881   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5882   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5883   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5884   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5885                        NumCoords + NumLCM;
5886   unsigned NumMIVAddrs = NumVAddrs;
5887 
5888   SmallVector<SDValue, 4> VAddrs;
5889 
5890   // Optimize _L to _LZ when _L is zero
5891   if (LZMappingInfo) {
5892     if (auto ConstantLod =
5893          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5894       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5895         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5896         NumMIVAddrs--;               // remove 'lod'
5897       }
5898     }
5899   }
5900 
5901   // Optimize _mip away, when 'lod' is zero
5902   if (MIPMappingInfo) {
5903     if (auto ConstantLod =
5904          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5905       if (ConstantLod->isNullValue()) {
5906         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5907         NumMIVAddrs--;               // remove 'lod'
5908       }
5909     }
5910   }
5911 
5912   // Push back extra arguments.
5913   for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++)
5914     VAddrs.push_back(Op.getOperand(AddrIdx + I));
5915 
5916   // Check for 16 bit addresses or derivatives and pack if true.
5917   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5918   unsigned CoordIdx = DimIdx + NumGradients;
5919   unsigned CoordsEnd = AddrIdx + NumMIVAddrs;
5920 
5921   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5922   MVT VAddrScalarVT = VAddrVT.getScalarType();
5923   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5924   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
5925 
5926   VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType();
5927   VAddrScalarVT = VAddrVT.getScalarType();
5928   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
5929   if (IsA16 || IsG16) {
5930     if (IsA16) {
5931       if (!ST->hasA16()) {
5932         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
5933                              "support 16 bit addresses\n");
5934         return Op;
5935       }
5936       if (!IsG16) {
5937         LLVM_DEBUG(
5938             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
5939                       "need 16 bit derivatives but got 32 bit derivatives\n");
5940         return Op;
5941       }
5942     } else if (!ST->hasG16()) {
5943       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
5944                            "support 16 bit derivatives\n");
5945       return Op;
5946     }
5947 
5948     if (BaseOpcode->Gradients && !IsA16) {
5949       if (!ST->hasG16()) {
5950         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
5951                              "support 16 bit derivatives\n");
5952         return Op;
5953       }
5954       // Activate g16
5955       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
5956           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
5957       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
5958     }
5959 
5960     // Don't compress addresses for G16
5961     const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx;
5962     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx,
5963                                 PackEndIdx, NumGradients);
5964 
5965     if (!IsA16) {
5966       // Add uncompressed address
5967       for (unsigned I = CoordIdx; I < CoordsEnd; I++)
5968         VAddrs.push_back(Op.getOperand(I));
5969     }
5970   } else {
5971     for (unsigned I = DimIdx; I < CoordsEnd; I++)
5972       VAddrs.push_back(Op.getOperand(I));
5973   }
5974 
5975   // If the register allocator cannot place the address registers contiguously
5976   // without introducing moves, then using the non-sequential address encoding
5977   // is always preferable, since it saves VALU instructions and is usually a
5978   // wash in terms of code size or even better.
5979   //
5980   // However, we currently have no way of hinting to the register allocator that
5981   // MIMG addresses should be placed contiguously when it is possible to do so,
5982   // so force non-NSA for the common 2-address case as a heuristic.
5983   //
5984   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5985   // allocation when possible.
5986   bool UseNSA =
5987       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5988   SDValue VAddr;
5989   if (!UseNSA)
5990     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5991 
5992   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5993   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5994   unsigned CtrlIdx; // Index of texfailctrl argument
5995   SDValue Unorm;
5996   if (!BaseOpcode->Sampler) {
5997     Unorm = True;
5998     CtrlIdx = AddrIdx + NumVAddrs + 1;
5999   } else {
6000     auto UnormConst =
6001         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
6002 
6003     Unorm = UnormConst->getZExtValue() ? True : False;
6004     CtrlIdx = AddrIdx + NumVAddrs + 3;
6005   }
6006 
6007   SDValue TFE;
6008   SDValue LWE;
6009   SDValue TexFail = Op.getOperand(CtrlIdx);
6010   bool IsTexFail = false;
6011   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6012     return Op;
6013 
6014   if (IsTexFail) {
6015     if (!DMaskLanes) {
6016       // Expecting to get an error flag since TFC is on - and dmask is 0
6017       // Force dmask to be at least 1 otherwise the instruction will fail
6018       DMask = 0x1;
6019       DMaskLanes = 1;
6020       NumVDataDwords = 1;
6021     }
6022     NumVDataDwords += 1;
6023     AdjustRetType = true;
6024   }
6025 
6026   // Has something earlier tagged that the return type needs adjusting
6027   // This happens if the instruction is a load or has set TexFailCtrl flags
6028   if (AdjustRetType) {
6029     // NumVDataDwords reflects the true number of dwords required in the return type
6030     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6031       // This is a no-op load. This can be eliminated
6032       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6033       if (isa<MemSDNode>(Op))
6034         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6035       return Undef;
6036     }
6037 
6038     EVT NewVT = NumVDataDwords > 1 ?
6039                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6040                 : MVT::i32;
6041 
6042     ResultTypes[0] = NewVT;
6043     if (ResultTypes.size() == 3) {
6044       // Original result was aggregate type used for TexFailCtrl results
6045       // The actual instruction returns as a vector type which has now been
6046       // created. Remove the aggregate result.
6047       ResultTypes.erase(&ResultTypes[1]);
6048     }
6049   }
6050 
6051   SDValue GLC;
6052   SDValue SLC;
6053   SDValue DLC;
6054   if (BaseOpcode->Atomic) {
6055     GLC = True; // TODO no-return optimization
6056     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
6057                           IsGFX10 ? &DLC : nullptr))
6058       return Op;
6059   } else {
6060     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
6061                           IsGFX10 ? &DLC : nullptr))
6062       return Op;
6063   }
6064 
6065   SmallVector<SDValue, 26> Ops;
6066   if (BaseOpcode->Store || BaseOpcode->Atomic)
6067     Ops.push_back(VData); // vdata
6068   if (UseNSA) {
6069     for (const SDValue &Addr : VAddrs)
6070       Ops.push_back(Addr);
6071   } else {
6072     Ops.push_back(VAddr);
6073   }
6074   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
6075   if (BaseOpcode->Sampler)
6076     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
6077   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6078   if (IsGFX10)
6079     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6080   Ops.push_back(Unorm);
6081   if (IsGFX10)
6082     Ops.push_back(DLC);
6083   Ops.push_back(GLC);
6084   Ops.push_back(SLC);
6085   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6086                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6087   if (IsGFX10)
6088     Ops.push_back(IsA16 ? True : False);
6089   Ops.push_back(TFE);
6090   Ops.push_back(LWE);
6091   if (!IsGFX10)
6092     Ops.push_back(DimInfo->DA ? True : False);
6093   if (BaseOpcode->HasD16)
6094     Ops.push_back(IsD16 ? True : False);
6095   if (isa<MemSDNode>(Op))
6096     Ops.push_back(Op.getOperand(0)); // chain
6097 
6098   int NumVAddrDwords =
6099       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6100   int Opcode = -1;
6101 
6102   if (IsGFX10) {
6103     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6104                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6105                                           : AMDGPU::MIMGEncGfx10Default,
6106                                    NumVDataDwords, NumVAddrDwords);
6107   } else {
6108     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6109       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6110                                      NumVDataDwords, NumVAddrDwords);
6111     if (Opcode == -1)
6112       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6113                                      NumVDataDwords, NumVAddrDwords);
6114   }
6115   assert(Opcode != -1);
6116 
6117   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6118   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6119     MachineMemOperand *MemRef = MemOp->getMemOperand();
6120     DAG.setNodeMemRefs(NewNode, {MemRef});
6121   }
6122 
6123   if (BaseOpcode->AtomicX2) {
6124     SmallVector<SDValue, 1> Elt;
6125     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6126     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6127   } else if (!BaseOpcode->Store) {
6128     return constructRetValue(DAG, NewNode,
6129                              OrigResultTypes, IsTexFail,
6130                              Subtarget->hasUnpackedD16VMem(), IsD16,
6131                              DMaskLanes, NumVDataDwords, DL,
6132                              *DAG.getContext());
6133   }
6134 
6135   return SDValue(NewNode, 0);
6136 }
6137 
6138 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6139                                        SDValue Offset, SDValue CachePolicy,
6140                                        SelectionDAG &DAG) const {
6141   MachineFunction &MF = DAG.getMachineFunction();
6142 
6143   const DataLayout &DataLayout = DAG.getDataLayout();
6144   Align Alignment =
6145       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6146 
6147   MachineMemOperand *MMO = MF.getMachineMemOperand(
6148       MachinePointerInfo(),
6149       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6150           MachineMemOperand::MOInvariant,
6151       VT.getStoreSize(), Alignment);
6152 
6153   if (!Offset->isDivergent()) {
6154     SDValue Ops[] = {
6155         Rsrc,
6156         Offset, // Offset
6157         CachePolicy
6158     };
6159 
6160     // Widen vec3 load to vec4.
6161     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6162       EVT WidenedVT =
6163           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6164       auto WidenedOp = DAG.getMemIntrinsicNode(
6165           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6166           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6167       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6168                                    DAG.getVectorIdxConstant(0, DL));
6169       return Subvector;
6170     }
6171 
6172     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6173                                    DAG.getVTList(VT), Ops, VT, MMO);
6174   }
6175 
6176   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6177   // assume that the buffer is unswizzled.
6178   SmallVector<SDValue, 4> Loads;
6179   unsigned NumLoads = 1;
6180   MVT LoadVT = VT.getSimpleVT();
6181   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6182   assert((LoadVT.getScalarType() == MVT::i32 ||
6183           LoadVT.getScalarType() == MVT::f32));
6184 
6185   if (NumElts == 8 || NumElts == 16) {
6186     NumLoads = NumElts / 4;
6187     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6188   }
6189 
6190   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6191   SDValue Ops[] = {
6192       DAG.getEntryNode(),                               // Chain
6193       Rsrc,                                             // rsrc
6194       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6195       {},                                               // voffset
6196       {},                                               // soffset
6197       {},                                               // offset
6198       CachePolicy,                                      // cachepolicy
6199       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6200   };
6201 
6202   // Use the alignment to ensure that the required offsets will fit into the
6203   // immediate offsets.
6204   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
6205 
6206   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6207   for (unsigned i = 0; i < NumLoads; ++i) {
6208     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6209     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6210                                         LoadVT, MMO, DAG));
6211   }
6212 
6213   if (NumElts == 8 || NumElts == 16)
6214     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6215 
6216   return Loads[0];
6217 }
6218 
6219 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6220                                                   SelectionDAG &DAG) const {
6221   MachineFunction &MF = DAG.getMachineFunction();
6222   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6223 
6224   EVT VT = Op.getValueType();
6225   SDLoc DL(Op);
6226   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6227 
6228   // TODO: Should this propagate fast-math-flags?
6229 
6230   switch (IntrinsicID) {
6231   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6232     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6233       return emitNonHSAIntrinsicError(DAG, DL, VT);
6234     return getPreloadedValue(DAG, *MFI, VT,
6235                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6236   }
6237   case Intrinsic::amdgcn_dispatch_ptr:
6238   case Intrinsic::amdgcn_queue_ptr: {
6239     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6240       DiagnosticInfoUnsupported BadIntrin(
6241           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6242           DL.getDebugLoc());
6243       DAG.getContext()->diagnose(BadIntrin);
6244       return DAG.getUNDEF(VT);
6245     }
6246 
6247     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6248       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6249     return getPreloadedValue(DAG, *MFI, VT, RegID);
6250   }
6251   case Intrinsic::amdgcn_implicitarg_ptr: {
6252     if (MFI->isEntryFunction())
6253       return getImplicitArgPtr(DAG, DL);
6254     return getPreloadedValue(DAG, *MFI, VT,
6255                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6256   }
6257   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6258     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6259       // This only makes sense to call in a kernel, so just lower to null.
6260       return DAG.getConstant(0, DL, VT);
6261     }
6262 
6263     return getPreloadedValue(DAG, *MFI, VT,
6264                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6265   }
6266   case Intrinsic::amdgcn_dispatch_id: {
6267     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6268   }
6269   case Intrinsic::amdgcn_rcp:
6270     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6271   case Intrinsic::amdgcn_rsq:
6272     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6273   case Intrinsic::amdgcn_rsq_legacy:
6274     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6275       return emitRemovedIntrinsicError(DAG, DL, VT);
6276     return SDValue();
6277   case Intrinsic::amdgcn_rcp_legacy:
6278     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6279       return emitRemovedIntrinsicError(DAG, DL, VT);
6280     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6281   case Intrinsic::amdgcn_rsq_clamp: {
6282     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6283       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6284 
6285     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6286     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6287     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6288 
6289     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6290     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6291                               DAG.getConstantFP(Max, DL, VT));
6292     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6293                        DAG.getConstantFP(Min, DL, VT));
6294   }
6295   case Intrinsic::r600_read_ngroups_x:
6296     if (Subtarget->isAmdHsaOS())
6297       return emitNonHSAIntrinsicError(DAG, DL, VT);
6298 
6299     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6300                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
6301   case Intrinsic::r600_read_ngroups_y:
6302     if (Subtarget->isAmdHsaOS())
6303       return emitNonHSAIntrinsicError(DAG, DL, VT);
6304 
6305     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6306                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
6307   case Intrinsic::r600_read_ngroups_z:
6308     if (Subtarget->isAmdHsaOS())
6309       return emitNonHSAIntrinsicError(DAG, DL, VT);
6310 
6311     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6312                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
6313   case Intrinsic::r600_read_global_size_x:
6314     if (Subtarget->isAmdHsaOS())
6315       return emitNonHSAIntrinsicError(DAG, DL, VT);
6316 
6317     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6318                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
6319   case Intrinsic::r600_read_global_size_y:
6320     if (Subtarget->isAmdHsaOS())
6321       return emitNonHSAIntrinsicError(DAG, DL, VT);
6322 
6323     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6324                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
6325   case Intrinsic::r600_read_global_size_z:
6326     if (Subtarget->isAmdHsaOS())
6327       return emitNonHSAIntrinsicError(DAG, DL, VT);
6328 
6329     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6330                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
6331   case Intrinsic::r600_read_local_size_x:
6332     if (Subtarget->isAmdHsaOS())
6333       return emitNonHSAIntrinsicError(DAG, DL, VT);
6334 
6335     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6336                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6337   case Intrinsic::r600_read_local_size_y:
6338     if (Subtarget->isAmdHsaOS())
6339       return emitNonHSAIntrinsicError(DAG, DL, VT);
6340 
6341     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6342                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6343   case Intrinsic::r600_read_local_size_z:
6344     if (Subtarget->isAmdHsaOS())
6345       return emitNonHSAIntrinsicError(DAG, DL, VT);
6346 
6347     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6348                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6349   case Intrinsic::amdgcn_workgroup_id_x:
6350     return getPreloadedValue(DAG, *MFI, VT,
6351                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6352   case Intrinsic::amdgcn_workgroup_id_y:
6353     return getPreloadedValue(DAG, *MFI, VT,
6354                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6355   case Intrinsic::amdgcn_workgroup_id_z:
6356     return getPreloadedValue(DAG, *MFI, VT,
6357                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6358   case Intrinsic::amdgcn_workitem_id_x:
6359     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6360                           SDLoc(DAG.getEntryNode()),
6361                           MFI->getArgInfo().WorkItemIDX);
6362   case Intrinsic::amdgcn_workitem_id_y:
6363     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6364                           SDLoc(DAG.getEntryNode()),
6365                           MFI->getArgInfo().WorkItemIDY);
6366   case Intrinsic::amdgcn_workitem_id_z:
6367     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6368                           SDLoc(DAG.getEntryNode()),
6369                           MFI->getArgInfo().WorkItemIDZ);
6370   case Intrinsic::amdgcn_wavefrontsize:
6371     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6372                            SDLoc(Op), MVT::i32);
6373   case Intrinsic::amdgcn_s_buffer_load: {
6374     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6375     SDValue GLC;
6376     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6377     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6378                           IsGFX10 ? &DLC : nullptr))
6379       return Op;
6380     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6381                         DAG);
6382   }
6383   case Intrinsic::amdgcn_fdiv_fast:
6384     return lowerFDIV_FAST(Op, DAG);
6385   case Intrinsic::amdgcn_sin:
6386     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6387 
6388   case Intrinsic::amdgcn_cos:
6389     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6390 
6391   case Intrinsic::amdgcn_mul_u24:
6392     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6393   case Intrinsic::amdgcn_mul_i24:
6394     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6395 
6396   case Intrinsic::amdgcn_log_clamp: {
6397     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6398       return SDValue();
6399 
6400     DiagnosticInfoUnsupported BadIntrin(
6401       MF.getFunction(), "intrinsic not supported on subtarget",
6402       DL.getDebugLoc());
6403       DAG.getContext()->diagnose(BadIntrin);
6404       return DAG.getUNDEF(VT);
6405   }
6406   case Intrinsic::amdgcn_ldexp:
6407     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6408                        Op.getOperand(1), Op.getOperand(2));
6409 
6410   case Intrinsic::amdgcn_fract:
6411     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6412 
6413   case Intrinsic::amdgcn_class:
6414     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6415                        Op.getOperand(1), Op.getOperand(2));
6416   case Intrinsic::amdgcn_div_fmas:
6417     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6418                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6419                        Op.getOperand(4));
6420 
6421   case Intrinsic::amdgcn_div_fixup:
6422     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6423                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6424 
6425   case Intrinsic::amdgcn_trig_preop:
6426     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
6427                        Op.getOperand(1), Op.getOperand(2));
6428   case Intrinsic::amdgcn_div_scale: {
6429     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6430 
6431     // Translate to the operands expected by the machine instruction. The
6432     // first parameter must be the same as the first instruction.
6433     SDValue Numerator = Op.getOperand(1);
6434     SDValue Denominator = Op.getOperand(2);
6435 
6436     // Note this order is opposite of the machine instruction's operations,
6437     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6438     // intrinsic has the numerator as the first operand to match a normal
6439     // division operation.
6440 
6441     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6442 
6443     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6444                        Denominator, Numerator);
6445   }
6446   case Intrinsic::amdgcn_icmp: {
6447     // There is a Pat that handles this variant, so return it as-is.
6448     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6449         Op.getConstantOperandVal(2) == 0 &&
6450         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6451       return Op;
6452     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6453   }
6454   case Intrinsic::amdgcn_fcmp: {
6455     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6456   }
6457   case Intrinsic::amdgcn_ballot:
6458     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6459   case Intrinsic::amdgcn_fmed3:
6460     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6461                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6462   case Intrinsic::amdgcn_fdot2:
6463     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6464                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6465                        Op.getOperand(4));
6466   case Intrinsic::amdgcn_fmul_legacy:
6467     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6468                        Op.getOperand(1), Op.getOperand(2));
6469   case Intrinsic::amdgcn_sffbh:
6470     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6471   case Intrinsic::amdgcn_sbfe:
6472     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6473                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6474   case Intrinsic::amdgcn_ubfe:
6475     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6476                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6477   case Intrinsic::amdgcn_cvt_pkrtz:
6478   case Intrinsic::amdgcn_cvt_pknorm_i16:
6479   case Intrinsic::amdgcn_cvt_pknorm_u16:
6480   case Intrinsic::amdgcn_cvt_pk_i16:
6481   case Intrinsic::amdgcn_cvt_pk_u16: {
6482     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6483     EVT VT = Op.getValueType();
6484     unsigned Opcode;
6485 
6486     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6487       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6488     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6489       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6490     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6491       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6492     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6493       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6494     else
6495       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6496 
6497     if (isTypeLegal(VT))
6498       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6499 
6500     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6501                                Op.getOperand(1), Op.getOperand(2));
6502     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6503   }
6504   case Intrinsic::amdgcn_fmad_ftz:
6505     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6506                        Op.getOperand(2), Op.getOperand(3));
6507 
6508   case Intrinsic::amdgcn_if_break:
6509     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6510                                       Op->getOperand(1), Op->getOperand(2)), 0);
6511 
6512   case Intrinsic::amdgcn_groupstaticsize: {
6513     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6514     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6515       return Op;
6516 
6517     const Module *M = MF.getFunction().getParent();
6518     const GlobalValue *GV =
6519         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6520     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6521                                             SIInstrInfo::MO_ABS32_LO);
6522     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6523   }
6524   case Intrinsic::amdgcn_is_shared:
6525   case Intrinsic::amdgcn_is_private: {
6526     SDLoc SL(Op);
6527     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6528       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6529     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6530     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6531                                  Op.getOperand(1));
6532 
6533     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6534                                 DAG.getConstant(1, SL, MVT::i32));
6535     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6536   }
6537   case Intrinsic::amdgcn_alignbit:
6538     return DAG.getNode(ISD::FSHR, DL, VT,
6539                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6540   case Intrinsic::amdgcn_reloc_constant: {
6541     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6542     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6543     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6544     auto RelocSymbol = cast<GlobalVariable>(
6545         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6546     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6547                                             SIInstrInfo::MO_ABS32_LO);
6548     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6549   }
6550   default:
6551     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6552             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6553       return lowerImage(Op, ImageDimIntr, DAG);
6554 
6555     return Op;
6556   }
6557 }
6558 
6559 // This function computes an appropriate offset to pass to
6560 // MachineMemOperand::setOffset() based on the offset inputs to
6561 // an intrinsic.  If any of the offsets are non-contstant or
6562 // if VIndex is non-zero then this function returns 0.  Otherwise,
6563 // it returns the sum of VOffset, SOffset, and Offset.
6564 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6565                                       SDValue SOffset,
6566                                       SDValue Offset,
6567                                       SDValue VIndex = SDValue()) {
6568 
6569   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6570       !isa<ConstantSDNode>(Offset))
6571     return 0;
6572 
6573   if (VIndex) {
6574     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6575       return 0;
6576   }
6577 
6578   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6579          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6580          cast<ConstantSDNode>(Offset)->getSExtValue();
6581 }
6582 
6583 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6584   switch (MF.getFunction().getCallingConv()) {
6585   case CallingConv::AMDGPU_PS:
6586     return 1;
6587   case CallingConv::AMDGPU_VS:
6588     return 2;
6589   case CallingConv::AMDGPU_GS:
6590     return 3;
6591   case CallingConv::AMDGPU_HS:
6592   case CallingConv::AMDGPU_LS:
6593   case CallingConv::AMDGPU_ES:
6594     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6595   case CallingConv::AMDGPU_CS:
6596   case CallingConv::AMDGPU_KERNEL:
6597   case CallingConv::C:
6598   case CallingConv::Fast:
6599   default:
6600     // Assume other calling conventions are various compute callable functions
6601     return 0;
6602   }
6603 }
6604 
6605 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6606                                                  SelectionDAG &DAG) const {
6607   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6608   SDLoc DL(Op);
6609 
6610   switch (IntrID) {
6611   case Intrinsic::amdgcn_ds_ordered_add:
6612   case Intrinsic::amdgcn_ds_ordered_swap: {
6613     MemSDNode *M = cast<MemSDNode>(Op);
6614     SDValue Chain = M->getOperand(0);
6615     SDValue M0 = M->getOperand(2);
6616     SDValue Value = M->getOperand(3);
6617     unsigned IndexOperand = M->getConstantOperandVal(7);
6618     unsigned WaveRelease = M->getConstantOperandVal(8);
6619     unsigned WaveDone = M->getConstantOperandVal(9);
6620 
6621     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6622     IndexOperand &= ~0x3f;
6623     unsigned CountDw = 0;
6624 
6625     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6626       CountDw = (IndexOperand >> 24) & 0xf;
6627       IndexOperand &= ~(0xf << 24);
6628 
6629       if (CountDw < 1 || CountDw > 4) {
6630         report_fatal_error(
6631             "ds_ordered_count: dword count must be between 1 and 4");
6632       }
6633     }
6634 
6635     if (IndexOperand)
6636       report_fatal_error("ds_ordered_count: bad index operand");
6637 
6638     if (WaveDone && !WaveRelease)
6639       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6640 
6641     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6642     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6643     unsigned Offset0 = OrderedCountIndex << 2;
6644     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6645                        (Instruction << 4);
6646 
6647     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6648       Offset1 |= (CountDw - 1) << 6;
6649 
6650     unsigned Offset = Offset0 | (Offset1 << 8);
6651 
6652     SDValue Ops[] = {
6653       Chain,
6654       Value,
6655       DAG.getTargetConstant(Offset, DL, MVT::i16),
6656       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6657     };
6658     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6659                                    M->getVTList(), Ops, M->getMemoryVT(),
6660                                    M->getMemOperand());
6661   }
6662   case Intrinsic::amdgcn_ds_fadd: {
6663     MemSDNode *M = cast<MemSDNode>(Op);
6664     unsigned Opc;
6665     switch (IntrID) {
6666     case Intrinsic::amdgcn_ds_fadd:
6667       Opc = ISD::ATOMIC_LOAD_FADD;
6668       break;
6669     }
6670 
6671     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6672                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6673                          M->getMemOperand());
6674   }
6675   case Intrinsic::amdgcn_atomic_inc:
6676   case Intrinsic::amdgcn_atomic_dec:
6677   case Intrinsic::amdgcn_ds_fmin:
6678   case Intrinsic::amdgcn_ds_fmax: {
6679     MemSDNode *M = cast<MemSDNode>(Op);
6680     unsigned Opc;
6681     switch (IntrID) {
6682     case Intrinsic::amdgcn_atomic_inc:
6683       Opc = AMDGPUISD::ATOMIC_INC;
6684       break;
6685     case Intrinsic::amdgcn_atomic_dec:
6686       Opc = AMDGPUISD::ATOMIC_DEC;
6687       break;
6688     case Intrinsic::amdgcn_ds_fmin:
6689       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6690       break;
6691     case Intrinsic::amdgcn_ds_fmax:
6692       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6693       break;
6694     default:
6695       llvm_unreachable("Unknown intrinsic!");
6696     }
6697     SDValue Ops[] = {
6698       M->getOperand(0), // Chain
6699       M->getOperand(2), // Ptr
6700       M->getOperand(3)  // Value
6701     };
6702 
6703     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6704                                    M->getMemoryVT(), M->getMemOperand());
6705   }
6706   case Intrinsic::amdgcn_buffer_load:
6707   case Intrinsic::amdgcn_buffer_load_format: {
6708     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6709     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6710     unsigned IdxEn = 1;
6711     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6712       IdxEn = Idx->getZExtValue() != 0;
6713     SDValue Ops[] = {
6714       Op.getOperand(0), // Chain
6715       Op.getOperand(2), // rsrc
6716       Op.getOperand(3), // vindex
6717       SDValue(),        // voffset -- will be set by setBufferOffsets
6718       SDValue(),        // soffset -- will be set by setBufferOffsets
6719       SDValue(),        // offset -- will be set by setBufferOffsets
6720       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6721       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6722     };
6723 
6724     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6725     // We don't know the offset if vindex is non-zero, so clear it.
6726     if (IdxEn)
6727       Offset = 0;
6728 
6729     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6730         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6731 
6732     EVT VT = Op.getValueType();
6733     EVT IntVT = VT.changeTypeToInteger();
6734     auto *M = cast<MemSDNode>(Op);
6735     M->getMemOperand()->setOffset(Offset);
6736     EVT LoadVT = Op.getValueType();
6737 
6738     if (LoadVT.getScalarType() == MVT::f16)
6739       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6740                                  M, DAG, Ops);
6741 
6742     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6743     if (LoadVT.getScalarType() == MVT::i8 ||
6744         LoadVT.getScalarType() == MVT::i16)
6745       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6746 
6747     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6748                                M->getMemOperand(), DAG);
6749   }
6750   case Intrinsic::amdgcn_raw_buffer_load:
6751   case Intrinsic::amdgcn_raw_buffer_load_format: {
6752     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6753 
6754     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6755     SDValue Ops[] = {
6756       Op.getOperand(0), // Chain
6757       Op.getOperand(2), // rsrc
6758       DAG.getConstant(0, DL, MVT::i32), // vindex
6759       Offsets.first,    // voffset
6760       Op.getOperand(4), // soffset
6761       Offsets.second,   // offset
6762       Op.getOperand(5), // cachepolicy, swizzled buffer
6763       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6764     };
6765 
6766     auto *M = cast<MemSDNode>(Op);
6767     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6768     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6769   }
6770   case Intrinsic::amdgcn_struct_buffer_load:
6771   case Intrinsic::amdgcn_struct_buffer_load_format: {
6772     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6773 
6774     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6775     SDValue Ops[] = {
6776       Op.getOperand(0), // Chain
6777       Op.getOperand(2), // rsrc
6778       Op.getOperand(3), // vindex
6779       Offsets.first,    // voffset
6780       Op.getOperand(5), // soffset
6781       Offsets.second,   // offset
6782       Op.getOperand(6), // cachepolicy, swizzled buffer
6783       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6784     };
6785 
6786     auto *M = cast<MemSDNode>(Op);
6787     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6788                                                         Ops[2]));
6789     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6790   }
6791   case Intrinsic::amdgcn_tbuffer_load: {
6792     MemSDNode *M = cast<MemSDNode>(Op);
6793     EVT LoadVT = Op.getValueType();
6794 
6795     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6796     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6797     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6798     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6799     unsigned IdxEn = 1;
6800     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6801       IdxEn = Idx->getZExtValue() != 0;
6802     SDValue Ops[] = {
6803       Op.getOperand(0),  // Chain
6804       Op.getOperand(2),  // rsrc
6805       Op.getOperand(3),  // vindex
6806       Op.getOperand(4),  // voffset
6807       Op.getOperand(5),  // soffset
6808       Op.getOperand(6),  // offset
6809       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6810       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6811       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6812     };
6813 
6814     if (LoadVT.getScalarType() == MVT::f16)
6815       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6816                                  M, DAG, Ops);
6817     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6818                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6819                                DAG);
6820   }
6821   case Intrinsic::amdgcn_raw_tbuffer_load: {
6822     MemSDNode *M = cast<MemSDNode>(Op);
6823     EVT LoadVT = Op.getValueType();
6824     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6825 
6826     SDValue Ops[] = {
6827       Op.getOperand(0),  // Chain
6828       Op.getOperand(2),  // rsrc
6829       DAG.getConstant(0, DL, MVT::i32), // vindex
6830       Offsets.first,     // voffset
6831       Op.getOperand(4),  // soffset
6832       Offsets.second,    // offset
6833       Op.getOperand(5),  // format
6834       Op.getOperand(6),  // cachepolicy, swizzled buffer
6835       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6836     };
6837 
6838     if (LoadVT.getScalarType() == MVT::f16)
6839       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6840                                  M, DAG, Ops);
6841     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6842                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6843                                DAG);
6844   }
6845   case Intrinsic::amdgcn_struct_tbuffer_load: {
6846     MemSDNode *M = cast<MemSDNode>(Op);
6847     EVT LoadVT = Op.getValueType();
6848     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6849 
6850     SDValue Ops[] = {
6851       Op.getOperand(0),  // Chain
6852       Op.getOperand(2),  // rsrc
6853       Op.getOperand(3),  // vindex
6854       Offsets.first,     // voffset
6855       Op.getOperand(5),  // soffset
6856       Offsets.second,    // offset
6857       Op.getOperand(6),  // format
6858       Op.getOperand(7),  // cachepolicy, swizzled buffer
6859       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6860     };
6861 
6862     if (LoadVT.getScalarType() == MVT::f16)
6863       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6864                                  M, DAG, Ops);
6865     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6866                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6867                                DAG);
6868   }
6869   case Intrinsic::amdgcn_buffer_atomic_swap:
6870   case Intrinsic::amdgcn_buffer_atomic_add:
6871   case Intrinsic::amdgcn_buffer_atomic_sub:
6872   case Intrinsic::amdgcn_buffer_atomic_csub:
6873   case Intrinsic::amdgcn_buffer_atomic_smin:
6874   case Intrinsic::amdgcn_buffer_atomic_umin:
6875   case Intrinsic::amdgcn_buffer_atomic_smax:
6876   case Intrinsic::amdgcn_buffer_atomic_umax:
6877   case Intrinsic::amdgcn_buffer_atomic_and:
6878   case Intrinsic::amdgcn_buffer_atomic_or:
6879   case Intrinsic::amdgcn_buffer_atomic_xor: {
6880     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6881     unsigned IdxEn = 1;
6882     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6883       IdxEn = Idx->getZExtValue() != 0;
6884     SDValue Ops[] = {
6885       Op.getOperand(0), // Chain
6886       Op.getOperand(2), // vdata
6887       Op.getOperand(3), // rsrc
6888       Op.getOperand(4), // vindex
6889       SDValue(),        // voffset -- will be set by setBufferOffsets
6890       SDValue(),        // soffset -- will be set by setBufferOffsets
6891       SDValue(),        // offset -- will be set by setBufferOffsets
6892       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6893       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6894     };
6895     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6896     // We don't know the offset if vindex is non-zero, so clear it.
6897     if (IdxEn)
6898       Offset = 0;
6899     EVT VT = Op.getValueType();
6900 
6901     auto *M = cast<MemSDNode>(Op);
6902     M->getMemOperand()->setOffset(Offset);
6903     unsigned Opcode = 0;
6904 
6905     switch (IntrID) {
6906     case Intrinsic::amdgcn_buffer_atomic_swap:
6907       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6908       break;
6909     case Intrinsic::amdgcn_buffer_atomic_add:
6910       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6911       break;
6912     case Intrinsic::amdgcn_buffer_atomic_sub:
6913       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6914       break;
6915     case Intrinsic::amdgcn_buffer_atomic_csub:
6916       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
6917       break;
6918     case Intrinsic::amdgcn_buffer_atomic_smin:
6919       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6920       break;
6921     case Intrinsic::amdgcn_buffer_atomic_umin:
6922       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6923       break;
6924     case Intrinsic::amdgcn_buffer_atomic_smax:
6925       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6926       break;
6927     case Intrinsic::amdgcn_buffer_atomic_umax:
6928       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6929       break;
6930     case Intrinsic::amdgcn_buffer_atomic_and:
6931       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6932       break;
6933     case Intrinsic::amdgcn_buffer_atomic_or:
6934       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6935       break;
6936     case Intrinsic::amdgcn_buffer_atomic_xor:
6937       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6938       break;
6939     default:
6940       llvm_unreachable("unhandled atomic opcode");
6941     }
6942 
6943     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6944                                    M->getMemOperand());
6945   }
6946   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6947   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6948   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6949   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6950   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6951   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6952   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6953   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6954   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6955   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6956   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6957   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6958     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6959     SDValue Ops[] = {
6960       Op.getOperand(0), // Chain
6961       Op.getOperand(2), // vdata
6962       Op.getOperand(3), // rsrc
6963       DAG.getConstant(0, DL, MVT::i32), // vindex
6964       Offsets.first,    // voffset
6965       Op.getOperand(5), // soffset
6966       Offsets.second,   // offset
6967       Op.getOperand(6), // cachepolicy
6968       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6969     };
6970     EVT VT = Op.getValueType();
6971 
6972     auto *M = cast<MemSDNode>(Op);
6973     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6974     unsigned Opcode = 0;
6975 
6976     switch (IntrID) {
6977     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6978       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6979       break;
6980     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6981       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6982       break;
6983     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6984       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6985       break;
6986     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6987       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6988       break;
6989     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6990       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6991       break;
6992     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6993       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6994       break;
6995     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6996       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6997       break;
6998     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6999       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7000       break;
7001     case Intrinsic::amdgcn_raw_buffer_atomic_or:
7002       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7003       break;
7004     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7005       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7006       break;
7007     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7008       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
7009       break;
7010     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7011       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
7012       break;
7013     default:
7014       llvm_unreachable("unhandled atomic opcode");
7015     }
7016 
7017     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7018                                    M->getMemOperand());
7019   }
7020   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7021   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7022   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7023   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7024   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7025   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7026   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7027   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7028   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7029   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7030   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7031   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
7032     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7033     SDValue Ops[] = {
7034       Op.getOperand(0), // Chain
7035       Op.getOperand(2), // vdata
7036       Op.getOperand(3), // rsrc
7037       Op.getOperand(4), // vindex
7038       Offsets.first,    // voffset
7039       Op.getOperand(6), // soffset
7040       Offsets.second,   // offset
7041       Op.getOperand(7), // cachepolicy
7042       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7043     };
7044     EVT VT = Op.getValueType();
7045 
7046     auto *M = cast<MemSDNode>(Op);
7047     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7048                                                         Ops[3]));
7049     unsigned Opcode = 0;
7050 
7051     switch (IntrID) {
7052     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7053       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7054       break;
7055     case Intrinsic::amdgcn_struct_buffer_atomic_add:
7056       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7057       break;
7058     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7059       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7060       break;
7061     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7062       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7063       break;
7064     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7065       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7066       break;
7067     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7068       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7069       break;
7070     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7071       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7072       break;
7073     case Intrinsic::amdgcn_struct_buffer_atomic_and:
7074       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7075       break;
7076     case Intrinsic::amdgcn_struct_buffer_atomic_or:
7077       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7078       break;
7079     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7080       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7081       break;
7082     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7083       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
7084       break;
7085     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7086       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
7087       break;
7088     default:
7089       llvm_unreachable("unhandled atomic opcode");
7090     }
7091 
7092     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7093                                    M->getMemOperand());
7094   }
7095   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7096     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7097     unsigned IdxEn = 1;
7098     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7099       IdxEn = Idx->getZExtValue() != 0;
7100     SDValue Ops[] = {
7101       Op.getOperand(0), // Chain
7102       Op.getOperand(2), // src
7103       Op.getOperand(3), // cmp
7104       Op.getOperand(4), // rsrc
7105       Op.getOperand(5), // vindex
7106       SDValue(),        // voffset -- will be set by setBufferOffsets
7107       SDValue(),        // soffset -- will be set by setBufferOffsets
7108       SDValue(),        // offset -- will be set by setBufferOffsets
7109       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7110       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7111     };
7112     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7113     // We don't know the offset if vindex is non-zero, so clear it.
7114     if (IdxEn)
7115       Offset = 0;
7116     EVT VT = Op.getValueType();
7117     auto *M = cast<MemSDNode>(Op);
7118     M->getMemOperand()->setOffset(Offset);
7119 
7120     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7121                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7122   }
7123   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7124     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7125     SDValue Ops[] = {
7126       Op.getOperand(0), // Chain
7127       Op.getOperand(2), // src
7128       Op.getOperand(3), // cmp
7129       Op.getOperand(4), // rsrc
7130       DAG.getConstant(0, DL, MVT::i32), // vindex
7131       Offsets.first,    // voffset
7132       Op.getOperand(6), // soffset
7133       Offsets.second,   // offset
7134       Op.getOperand(7), // cachepolicy
7135       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7136     };
7137     EVT VT = Op.getValueType();
7138     auto *M = cast<MemSDNode>(Op);
7139     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7140 
7141     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7142                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7143   }
7144   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7145     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7146     SDValue Ops[] = {
7147       Op.getOperand(0), // Chain
7148       Op.getOperand(2), // src
7149       Op.getOperand(3), // cmp
7150       Op.getOperand(4), // rsrc
7151       Op.getOperand(5), // vindex
7152       Offsets.first,    // voffset
7153       Op.getOperand(7), // soffset
7154       Offsets.second,   // offset
7155       Op.getOperand(8), // cachepolicy
7156       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7157     };
7158     EVT VT = Op.getValueType();
7159     auto *M = cast<MemSDNode>(Op);
7160     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7161                                                         Ops[4]));
7162 
7163     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7164                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7165   }
7166   case Intrinsic::amdgcn_global_atomic_csub: {
7167     MemSDNode *M = cast<MemSDNode>(Op);
7168     SDValue Ops[] = {
7169       M->getOperand(0), // Chain
7170       M->getOperand(2), // Ptr
7171       M->getOperand(3)  // Value
7172     };
7173 
7174     return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_LOAD_CSUB, SDLoc(Op),
7175                                    M->getVTList(), Ops, M->getMemoryVT(),
7176                                    M->getMemOperand());
7177   }
7178 
7179   default:
7180     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7181             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7182       return lowerImage(Op, ImageDimIntr, DAG);
7183 
7184     return SDValue();
7185   }
7186 }
7187 
7188 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7189 // dwordx4 if on SI.
7190 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7191                                               SDVTList VTList,
7192                                               ArrayRef<SDValue> Ops, EVT MemVT,
7193                                               MachineMemOperand *MMO,
7194                                               SelectionDAG &DAG) const {
7195   EVT VT = VTList.VTs[0];
7196   EVT WidenedVT = VT;
7197   EVT WidenedMemVT = MemVT;
7198   if (!Subtarget->hasDwordx3LoadStores() &&
7199       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7200     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7201                                  WidenedVT.getVectorElementType(), 4);
7202     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7203                                     WidenedMemVT.getVectorElementType(), 4);
7204     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7205   }
7206 
7207   assert(VTList.NumVTs == 2);
7208   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7209 
7210   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7211                                        WidenedMemVT, MMO);
7212   if (WidenedVT != VT) {
7213     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7214                                DAG.getVectorIdxConstant(0, DL));
7215     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7216   }
7217   return NewOp;
7218 }
7219 
7220 SDValue SITargetLowering::handleD16VData(SDValue VData,
7221                                          SelectionDAG &DAG) const {
7222   EVT StoreVT = VData.getValueType();
7223 
7224   // No change for f16 and legal vector D16 types.
7225   if (!StoreVT.isVector())
7226     return VData;
7227 
7228   SDLoc DL(VData);
7229   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
7230 
7231   if (Subtarget->hasUnpackedD16VMem()) {
7232     // We need to unpack the packed data to store.
7233     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7234     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7235 
7236     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
7237                                         StoreVT.getVectorNumElements());
7238     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7239     return DAG.UnrollVectorOp(ZExt.getNode());
7240   }
7241 
7242   assert(isTypeLegal(StoreVT));
7243   return VData;
7244 }
7245 
7246 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7247                                               SelectionDAG &DAG) const {
7248   SDLoc DL(Op);
7249   SDValue Chain = Op.getOperand(0);
7250   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7251   MachineFunction &MF = DAG.getMachineFunction();
7252 
7253   switch (IntrinsicID) {
7254   case Intrinsic::amdgcn_exp_compr: {
7255     SDValue Src0 = Op.getOperand(4);
7256     SDValue Src1 = Op.getOperand(5);
7257     // Hack around illegal type on SI by directly selecting it.
7258     if (isTypeLegal(Src0.getValueType()))
7259       return SDValue();
7260 
7261     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7262     SDValue Undef = DAG.getUNDEF(MVT::f32);
7263     const SDValue Ops[] = {
7264       Op.getOperand(2), // tgt
7265       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7266       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7267       Undef, // src2
7268       Undef, // src3
7269       Op.getOperand(7), // vm
7270       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7271       Op.getOperand(3), // en
7272       Op.getOperand(0) // Chain
7273     };
7274 
7275     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7276     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7277   }
7278   case Intrinsic::amdgcn_s_barrier: {
7279     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7280       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7281       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7282       if (WGSize <= ST.getWavefrontSize())
7283         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7284                                           Op.getOperand(0)), 0);
7285     }
7286     return SDValue();
7287   };
7288   case Intrinsic::amdgcn_tbuffer_store: {
7289     SDValue VData = Op.getOperand(2);
7290     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7291     if (IsD16)
7292       VData = handleD16VData(VData, DAG);
7293     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7294     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7295     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7296     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7297     unsigned IdxEn = 1;
7298     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7299       IdxEn = Idx->getZExtValue() != 0;
7300     SDValue Ops[] = {
7301       Chain,
7302       VData,             // vdata
7303       Op.getOperand(3),  // rsrc
7304       Op.getOperand(4),  // vindex
7305       Op.getOperand(5),  // voffset
7306       Op.getOperand(6),  // soffset
7307       Op.getOperand(7),  // offset
7308       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7309       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7310       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7311     };
7312     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7313                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7314     MemSDNode *M = cast<MemSDNode>(Op);
7315     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7316                                    M->getMemoryVT(), M->getMemOperand());
7317   }
7318 
7319   case Intrinsic::amdgcn_struct_tbuffer_store: {
7320     SDValue VData = Op.getOperand(2);
7321     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7322     if (IsD16)
7323       VData = handleD16VData(VData, DAG);
7324     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7325     SDValue Ops[] = {
7326       Chain,
7327       VData,             // vdata
7328       Op.getOperand(3),  // rsrc
7329       Op.getOperand(4),  // vindex
7330       Offsets.first,     // voffset
7331       Op.getOperand(6),  // soffset
7332       Offsets.second,    // offset
7333       Op.getOperand(7),  // format
7334       Op.getOperand(8),  // cachepolicy, swizzled buffer
7335       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7336     };
7337     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7338                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7339     MemSDNode *M = cast<MemSDNode>(Op);
7340     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7341                                    M->getMemoryVT(), M->getMemOperand());
7342   }
7343 
7344   case Intrinsic::amdgcn_raw_tbuffer_store: {
7345     SDValue VData = Op.getOperand(2);
7346     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7347     if (IsD16)
7348       VData = handleD16VData(VData, DAG);
7349     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7350     SDValue Ops[] = {
7351       Chain,
7352       VData,             // vdata
7353       Op.getOperand(3),  // rsrc
7354       DAG.getConstant(0, DL, MVT::i32), // vindex
7355       Offsets.first,     // voffset
7356       Op.getOperand(5),  // soffset
7357       Offsets.second,    // offset
7358       Op.getOperand(6),  // format
7359       Op.getOperand(7),  // cachepolicy, swizzled buffer
7360       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7361     };
7362     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7363                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7364     MemSDNode *M = cast<MemSDNode>(Op);
7365     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7366                                    M->getMemoryVT(), M->getMemOperand());
7367   }
7368 
7369   case Intrinsic::amdgcn_buffer_store:
7370   case Intrinsic::amdgcn_buffer_store_format: {
7371     SDValue VData = Op.getOperand(2);
7372     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7373     if (IsD16)
7374       VData = handleD16VData(VData, DAG);
7375     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7376     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7377     unsigned IdxEn = 1;
7378     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7379       IdxEn = Idx->getZExtValue() != 0;
7380     SDValue Ops[] = {
7381       Chain,
7382       VData,
7383       Op.getOperand(3), // rsrc
7384       Op.getOperand(4), // vindex
7385       SDValue(), // voffset -- will be set by setBufferOffsets
7386       SDValue(), // soffset -- will be set by setBufferOffsets
7387       SDValue(), // offset -- will be set by setBufferOffsets
7388       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7389       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7390     };
7391     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7392     // We don't know the offset if vindex is non-zero, so clear it.
7393     if (IdxEn)
7394       Offset = 0;
7395     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7396                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7397     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7398     MemSDNode *M = cast<MemSDNode>(Op);
7399     M->getMemOperand()->setOffset(Offset);
7400 
7401     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7402     EVT VDataType = VData.getValueType().getScalarType();
7403     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7404       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7405 
7406     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7407                                    M->getMemoryVT(), M->getMemOperand());
7408   }
7409 
7410   case Intrinsic::amdgcn_raw_buffer_store:
7411   case Intrinsic::amdgcn_raw_buffer_store_format: {
7412     const bool IsFormat =
7413         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7414 
7415     SDValue VData = Op.getOperand(2);
7416     EVT VDataVT = VData.getValueType();
7417     EVT EltType = VDataVT.getScalarType();
7418     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7419     if (IsD16)
7420       VData = handleD16VData(VData, DAG);
7421 
7422     if (!isTypeLegal(VDataVT)) {
7423       VData =
7424           DAG.getNode(ISD::BITCAST, DL,
7425                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7426     }
7427 
7428     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7429     SDValue Ops[] = {
7430       Chain,
7431       VData,
7432       Op.getOperand(3), // rsrc
7433       DAG.getConstant(0, DL, MVT::i32), // vindex
7434       Offsets.first,    // voffset
7435       Op.getOperand(5), // soffset
7436       Offsets.second,   // offset
7437       Op.getOperand(6), // cachepolicy, swizzled buffer
7438       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7439     };
7440     unsigned Opc =
7441         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7442     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7443     MemSDNode *M = cast<MemSDNode>(Op);
7444     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7445 
7446     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7447     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7448       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7449 
7450     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7451                                    M->getMemoryVT(), M->getMemOperand());
7452   }
7453 
7454   case Intrinsic::amdgcn_struct_buffer_store:
7455   case Intrinsic::amdgcn_struct_buffer_store_format: {
7456     const bool IsFormat =
7457         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7458 
7459     SDValue VData = Op.getOperand(2);
7460     EVT VDataVT = VData.getValueType();
7461     EVT EltType = VDataVT.getScalarType();
7462     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7463 
7464     if (IsD16)
7465       VData = handleD16VData(VData, DAG);
7466 
7467     if (!isTypeLegal(VDataVT)) {
7468       VData =
7469           DAG.getNode(ISD::BITCAST, DL,
7470                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7471     }
7472 
7473     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7474     SDValue Ops[] = {
7475       Chain,
7476       VData,
7477       Op.getOperand(3), // rsrc
7478       Op.getOperand(4), // vindex
7479       Offsets.first,    // voffset
7480       Op.getOperand(6), // soffset
7481       Offsets.second,   // offset
7482       Op.getOperand(7), // cachepolicy, swizzled buffer
7483       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7484     };
7485     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7486                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7487     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7488     MemSDNode *M = cast<MemSDNode>(Op);
7489     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7490                                                         Ops[3]));
7491 
7492     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7493     EVT VDataType = VData.getValueType().getScalarType();
7494     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7495       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7496 
7497     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7498                                    M->getMemoryVT(), M->getMemOperand());
7499   }
7500 
7501   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7502     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7503     unsigned IdxEn = 1;
7504     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7505       IdxEn = Idx->getZExtValue() != 0;
7506     SDValue Ops[] = {
7507       Chain,
7508       Op.getOperand(2), // vdata
7509       Op.getOperand(3), // rsrc
7510       Op.getOperand(4), // vindex
7511       SDValue(),        // voffset -- will be set by setBufferOffsets
7512       SDValue(),        // soffset -- will be set by setBufferOffsets
7513       SDValue(),        // offset -- will be set by setBufferOffsets
7514       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7515       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7516     };
7517     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7518     // We don't know the offset if vindex is non-zero, so clear it.
7519     if (IdxEn)
7520       Offset = 0;
7521     EVT VT = Op.getOperand(2).getValueType();
7522 
7523     auto *M = cast<MemSDNode>(Op);
7524     M->getMemOperand()->setOffset(Offset);
7525     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7526                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7527 
7528     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7529                                    M->getMemOperand());
7530   }
7531 
7532   case Intrinsic::amdgcn_global_atomic_fadd: {
7533     SDValue Ops[] = {
7534       Chain,
7535       Op.getOperand(2), // ptr
7536       Op.getOperand(3)  // vdata
7537     };
7538     EVT VT = Op.getOperand(3).getValueType();
7539 
7540     auto *M = cast<MemSDNode>(Op);
7541     if (VT.isVector()) {
7542       return DAG.getMemIntrinsicNode(
7543         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7544         M->getMemOperand());
7545     }
7546 
7547     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7548                          DAG.getVTList(VT, MVT::Other), Ops,
7549                          M->getMemOperand()).getValue(1);
7550   }
7551   case Intrinsic::amdgcn_end_cf:
7552     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7553                                       Op->getOperand(2), Chain), 0);
7554 
7555   default: {
7556     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7557             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7558       return lowerImage(Op, ImageDimIntr, DAG);
7559 
7560     return Op;
7561   }
7562   }
7563 }
7564 
7565 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7566 // offset (the offset that is included in bounds checking and swizzling, to be
7567 // split between the instruction's voffset and immoffset fields) and soffset
7568 // (the offset that is excluded from bounds checking and swizzling, to go in
7569 // the instruction's soffset field).  This function takes the first kind of
7570 // offset and figures out how to split it between voffset and immoffset.
7571 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7572     SDValue Offset, SelectionDAG &DAG) const {
7573   SDLoc DL(Offset);
7574   const unsigned MaxImm = 4095;
7575   SDValue N0 = Offset;
7576   ConstantSDNode *C1 = nullptr;
7577 
7578   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7579     N0 = SDValue();
7580   else if (DAG.isBaseWithConstantOffset(N0)) {
7581     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7582     N0 = N0.getOperand(0);
7583   }
7584 
7585   if (C1) {
7586     unsigned ImmOffset = C1->getZExtValue();
7587     // If the immediate value is too big for the immoffset field, put the value
7588     // and -4096 into the immoffset field so that the value that is copied/added
7589     // for the voffset field is a multiple of 4096, and it stands more chance
7590     // of being CSEd with the copy/add for another similar load/store.
7591     // However, do not do that rounding down to a multiple of 4096 if that is a
7592     // negative number, as it appears to be illegal to have a negative offset
7593     // in the vgpr, even if adding the immediate offset makes it positive.
7594     unsigned Overflow = ImmOffset & ~MaxImm;
7595     ImmOffset -= Overflow;
7596     if ((int32_t)Overflow < 0) {
7597       Overflow += ImmOffset;
7598       ImmOffset = 0;
7599     }
7600     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7601     if (Overflow) {
7602       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7603       if (!N0)
7604         N0 = OverflowVal;
7605       else {
7606         SDValue Ops[] = { N0, OverflowVal };
7607         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7608       }
7609     }
7610   }
7611   if (!N0)
7612     N0 = DAG.getConstant(0, DL, MVT::i32);
7613   if (!C1)
7614     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7615   return {N0, SDValue(C1, 0)};
7616 }
7617 
7618 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7619 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7620 // pointed to by Offsets.
7621 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7622                                         SelectionDAG &DAG, SDValue *Offsets,
7623                                         unsigned Align) const {
7624   SDLoc DL(CombinedOffset);
7625   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7626     uint32_t Imm = C->getZExtValue();
7627     uint32_t SOffset, ImmOffset;
7628     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7629       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7630       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7631       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7632       return SOffset + ImmOffset;
7633     }
7634   }
7635   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7636     SDValue N0 = CombinedOffset.getOperand(0);
7637     SDValue N1 = CombinedOffset.getOperand(1);
7638     uint32_t SOffset, ImmOffset;
7639     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7640     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7641                                                 Subtarget, Align)) {
7642       Offsets[0] = N0;
7643       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7644       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7645       return 0;
7646     }
7647   }
7648   Offsets[0] = CombinedOffset;
7649   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7650   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7651   return 0;
7652 }
7653 
7654 // Handle 8 bit and 16 bit buffer loads
7655 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7656                                                      EVT LoadVT, SDLoc DL,
7657                                                      ArrayRef<SDValue> Ops,
7658                                                      MemSDNode *M) const {
7659   EVT IntVT = LoadVT.changeTypeToInteger();
7660   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7661          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7662 
7663   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7664   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7665                                                Ops, IntVT,
7666                                                M->getMemOperand());
7667   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7668   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7669 
7670   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7671 }
7672 
7673 // Handle 8 bit and 16 bit buffer stores
7674 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7675                                                       EVT VDataType, SDLoc DL,
7676                                                       SDValue Ops[],
7677                                                       MemSDNode *M) const {
7678   if (VDataType == MVT::f16)
7679     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7680 
7681   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7682   Ops[1] = BufferStoreExt;
7683   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7684                                  AMDGPUISD::BUFFER_STORE_SHORT;
7685   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7686   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7687                                      M->getMemOperand());
7688 }
7689 
7690 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7691                                  ISD::LoadExtType ExtType, SDValue Op,
7692                                  const SDLoc &SL, EVT VT) {
7693   if (VT.bitsLT(Op.getValueType()))
7694     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7695 
7696   switch (ExtType) {
7697   case ISD::SEXTLOAD:
7698     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7699   case ISD::ZEXTLOAD:
7700     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7701   case ISD::EXTLOAD:
7702     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7703   case ISD::NON_EXTLOAD:
7704     return Op;
7705   }
7706 
7707   llvm_unreachable("invalid ext type");
7708 }
7709 
7710 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7711   SelectionDAG &DAG = DCI.DAG;
7712   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7713     return SDValue();
7714 
7715   // FIXME: Constant loads should all be marked invariant.
7716   unsigned AS = Ld->getAddressSpace();
7717   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7718       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7719       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7720     return SDValue();
7721 
7722   // Don't do this early, since it may interfere with adjacent load merging for
7723   // illegal types. We can avoid losing alignment information for exotic types
7724   // pre-legalize.
7725   EVT MemVT = Ld->getMemoryVT();
7726   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7727       MemVT.getSizeInBits() >= 32)
7728     return SDValue();
7729 
7730   SDLoc SL(Ld);
7731 
7732   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7733          "unexpected vector extload");
7734 
7735   // TODO: Drop only high part of range.
7736   SDValue Ptr = Ld->getBasePtr();
7737   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7738                                 MVT::i32, SL, Ld->getChain(), Ptr,
7739                                 Ld->getOffset(),
7740                                 Ld->getPointerInfo(), MVT::i32,
7741                                 Ld->getAlignment(),
7742                                 Ld->getMemOperand()->getFlags(),
7743                                 Ld->getAAInfo(),
7744                                 nullptr); // Drop ranges
7745 
7746   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7747   if (MemVT.isFloatingPoint()) {
7748     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7749            "unexpected fp extload");
7750     TruncVT = MemVT.changeTypeToInteger();
7751   }
7752 
7753   SDValue Cvt = NewLoad;
7754   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7755     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7756                       DAG.getValueType(TruncVT));
7757   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7758              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7759     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7760   } else {
7761     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7762   }
7763 
7764   EVT VT = Ld->getValueType(0);
7765   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7766 
7767   DCI.AddToWorklist(Cvt.getNode());
7768 
7769   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7770   // the appropriate extension from the 32-bit load.
7771   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7772   DCI.AddToWorklist(Cvt.getNode());
7773 
7774   // Handle conversion back to floating point if necessary.
7775   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7776 
7777   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7778 }
7779 
7780 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7781   SDLoc DL(Op);
7782   LoadSDNode *Load = cast<LoadSDNode>(Op);
7783   ISD::LoadExtType ExtType = Load->getExtensionType();
7784   EVT MemVT = Load->getMemoryVT();
7785 
7786   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7787     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7788       return SDValue();
7789 
7790     // FIXME: Copied from PPC
7791     // First, load into 32 bits, then truncate to 1 bit.
7792 
7793     SDValue Chain = Load->getChain();
7794     SDValue BasePtr = Load->getBasePtr();
7795     MachineMemOperand *MMO = Load->getMemOperand();
7796 
7797     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7798 
7799     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7800                                    BasePtr, RealMemVT, MMO);
7801 
7802     if (!MemVT.isVector()) {
7803       SDValue Ops[] = {
7804         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7805         NewLD.getValue(1)
7806       };
7807 
7808       return DAG.getMergeValues(Ops, DL);
7809     }
7810 
7811     SmallVector<SDValue, 3> Elts;
7812     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7813       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7814                                 DAG.getConstant(I, DL, MVT::i32));
7815 
7816       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7817     }
7818 
7819     SDValue Ops[] = {
7820       DAG.getBuildVector(MemVT, DL, Elts),
7821       NewLD.getValue(1)
7822     };
7823 
7824     return DAG.getMergeValues(Ops, DL);
7825   }
7826 
7827   if (!MemVT.isVector())
7828     return SDValue();
7829 
7830   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7831          "Custom lowering for non-i32 vectors hasn't been implemented.");
7832 
7833   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7834                                       MemVT, *Load->getMemOperand())) {
7835     SDValue Ops[2];
7836     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7837     return DAG.getMergeValues(Ops, DL);
7838   }
7839 
7840   unsigned Alignment = Load->getAlignment();
7841   unsigned AS = Load->getAddressSpace();
7842   if (Subtarget->hasLDSMisalignedBug() &&
7843       AS == AMDGPUAS::FLAT_ADDRESS &&
7844       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7845     return SplitVectorLoad(Op, DAG);
7846   }
7847 
7848   MachineFunction &MF = DAG.getMachineFunction();
7849   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7850   // If there is a possibilty that flat instruction access scratch memory
7851   // then we need to use the same legalization rules we use for private.
7852   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7853       !Subtarget->hasMultiDwordFlatScratchAddressing())
7854     AS = MFI->hasFlatScratchInit() ?
7855          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7856 
7857   unsigned NumElements = MemVT.getVectorNumElements();
7858 
7859   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7860       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7861     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7862       if (MemVT.isPow2VectorType())
7863         return SDValue();
7864       if (NumElements == 3)
7865         return WidenVectorLoad(Op, DAG);
7866       return SplitVectorLoad(Op, DAG);
7867     }
7868     // Non-uniform loads will be selected to MUBUF instructions, so they
7869     // have the same legalization requirements as global and private
7870     // loads.
7871     //
7872   }
7873 
7874   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7875       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7876       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7877     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7878         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
7879         Alignment >= 4 && NumElements < 32) {
7880       if (MemVT.isPow2VectorType())
7881         return SDValue();
7882       if (NumElements == 3)
7883         return WidenVectorLoad(Op, DAG);
7884       return SplitVectorLoad(Op, DAG);
7885     }
7886     // Non-uniform loads will be selected to MUBUF instructions, so they
7887     // have the same legalization requirements as global and private
7888     // loads.
7889     //
7890   }
7891   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7892       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7893       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7894       AS == AMDGPUAS::FLAT_ADDRESS) {
7895     if (NumElements > 4)
7896       return SplitVectorLoad(Op, DAG);
7897     // v3 loads not supported on SI.
7898     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7899       return WidenVectorLoad(Op, DAG);
7900     // v3 and v4 loads are supported for private and global memory.
7901     return SDValue();
7902   }
7903   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7904     // Depending on the setting of the private_element_size field in the
7905     // resource descriptor, we can only make private accesses up to a certain
7906     // size.
7907     switch (Subtarget->getMaxPrivateElementSize()) {
7908     case 4: {
7909       SDValue Ops[2];
7910       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7911       return DAG.getMergeValues(Ops, DL);
7912     }
7913     case 8:
7914       if (NumElements > 2)
7915         return SplitVectorLoad(Op, DAG);
7916       return SDValue();
7917     case 16:
7918       // Same as global/flat
7919       if (NumElements > 4)
7920         return SplitVectorLoad(Op, DAG);
7921       // v3 loads not supported on SI.
7922       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7923         return WidenVectorLoad(Op, DAG);
7924       return SDValue();
7925     default:
7926       llvm_unreachable("unsupported private_element_size");
7927     }
7928   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7929     // Use ds_read_b128 if possible.
7930     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7931         MemVT.getStoreSize() == 16)
7932       return SDValue();
7933 
7934     if (NumElements > 2)
7935       return SplitVectorLoad(Op, DAG);
7936 
7937     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7938     // address is negative, then the instruction is incorrectly treated as
7939     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7940     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7941     // load later in the SILoadStoreOptimizer.
7942     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7943         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7944         Load->getAlignment() < 8) {
7945       return SplitVectorLoad(Op, DAG);
7946     }
7947   }
7948   return SDValue();
7949 }
7950 
7951 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7952   EVT VT = Op.getValueType();
7953   assert(VT.getSizeInBits() == 64);
7954 
7955   SDLoc DL(Op);
7956   SDValue Cond = Op.getOperand(0);
7957 
7958   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7959   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7960 
7961   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7962   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7963 
7964   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7965   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7966 
7967   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7968 
7969   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7970   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7971 
7972   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7973 
7974   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7975   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7976 }
7977 
7978 // Catch division cases where we can use shortcuts with rcp and rsq
7979 // instructions.
7980 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7981                                               SelectionDAG &DAG) const {
7982   SDLoc SL(Op);
7983   SDValue LHS = Op.getOperand(0);
7984   SDValue RHS = Op.getOperand(1);
7985   EVT VT = Op.getValueType();
7986   const SDNodeFlags Flags = Op->getFlags();
7987 
7988   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7989                             Flags.hasApproximateFuncs();
7990 
7991   // Without !fpmath accuracy information, we can't do more because we don't
7992   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7993   if (!AllowInaccurateRcp)
7994     return SDValue();
7995 
7996   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7997     if (CLHS->isExactlyValue(1.0)) {
7998       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7999       // the CI documentation has a worst case error of 1 ulp.
8000       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8001       // use it as long as we aren't trying to use denormals.
8002       //
8003       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8004 
8005       // 1.0 / sqrt(x) -> rsq(x)
8006 
8007       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8008       // error seems really high at 2^29 ULP.
8009       if (RHS.getOpcode() == ISD::FSQRT)
8010         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8011 
8012       // 1.0 / x -> rcp(x)
8013       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8014     }
8015 
8016     // Same as for 1.0, but expand the sign out of the constant.
8017     if (CLHS->isExactlyValue(-1.0)) {
8018       // -1.0 / x -> rcp (fneg x)
8019       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8020       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8021     }
8022   }
8023 
8024   // Turn into multiply by the reciprocal.
8025   // x / y -> x * (1.0 / y)
8026   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8027   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8028 }
8029 
8030 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8031                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8032                           SDNodeFlags Flags) {
8033   if (GlueChain->getNumValues() <= 1) {
8034     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8035   }
8036 
8037   assert(GlueChain->getNumValues() == 3);
8038 
8039   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8040   switch (Opcode) {
8041   default: llvm_unreachable("no chain equivalent for opcode");
8042   case ISD::FMUL:
8043     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8044     break;
8045   }
8046 
8047   return DAG.getNode(Opcode, SL, VTList,
8048                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8049                      Flags);
8050 }
8051 
8052 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8053                            EVT VT, SDValue A, SDValue B, SDValue C,
8054                            SDValue GlueChain, SDNodeFlags Flags) {
8055   if (GlueChain->getNumValues() <= 1) {
8056     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8057   }
8058 
8059   assert(GlueChain->getNumValues() == 3);
8060 
8061   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8062   switch (Opcode) {
8063   default: llvm_unreachable("no chain equivalent for opcode");
8064   case ISD::FMA:
8065     Opcode = AMDGPUISD::FMA_W_CHAIN;
8066     break;
8067   }
8068 
8069   return DAG.getNode(Opcode, SL, VTList,
8070                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8071                      Flags);
8072 }
8073 
8074 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8075   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8076     return FastLowered;
8077 
8078   SDLoc SL(Op);
8079   SDValue Src0 = Op.getOperand(0);
8080   SDValue Src1 = Op.getOperand(1);
8081 
8082   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8083   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8084 
8085   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8086   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8087 
8088   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8089   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8090 
8091   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8092 }
8093 
8094 // Faster 2.5 ULP division that does not support denormals.
8095 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8096   SDLoc SL(Op);
8097   SDValue LHS = Op.getOperand(1);
8098   SDValue RHS = Op.getOperand(2);
8099 
8100   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8101 
8102   const APFloat K0Val(BitsToFloat(0x6f800000));
8103   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8104 
8105   const APFloat K1Val(BitsToFloat(0x2f800000));
8106   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8107 
8108   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8109 
8110   EVT SetCCVT =
8111     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8112 
8113   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8114 
8115   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8116 
8117   // TODO: Should this propagate fast-math-flags?
8118   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8119 
8120   // rcp does not support denormals.
8121   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8122 
8123   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8124 
8125   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8126 }
8127 
8128 // Returns immediate value for setting the F32 denorm mode when using the
8129 // S_DENORM_MODE instruction.
8130 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8131                                           const SDLoc &SL, const GCNSubtarget *ST) {
8132   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8133   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8134                                 ? FP_DENORM_FLUSH_NONE
8135                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8136 
8137   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8138   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8139 }
8140 
8141 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8142   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8143     return FastLowered;
8144 
8145   // The selection matcher assumes anything with a chain selecting to a
8146   // mayRaiseFPException machine instruction. Since we're introducing a chain
8147   // here, we need to explicitly report nofpexcept for the regular fdiv
8148   // lowering.
8149   SDNodeFlags Flags = Op->getFlags();
8150   Flags.setNoFPExcept(true);
8151 
8152   SDLoc SL(Op);
8153   SDValue LHS = Op.getOperand(0);
8154   SDValue RHS = Op.getOperand(1);
8155 
8156   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8157 
8158   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8159 
8160   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8161                                           {RHS, RHS, LHS}, Flags);
8162   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8163                                         {LHS, RHS, LHS}, Flags);
8164 
8165   // Denominator is scaled to not be denormal, so using rcp is ok.
8166   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8167                                   DenominatorScaled, Flags);
8168   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8169                                      DenominatorScaled, Flags);
8170 
8171   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8172                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8173                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8174   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8175 
8176   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8177 
8178   if (!HasFP32Denormals) {
8179     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8180     // lowering. The chain dependence is insufficient, and we need glue. We do
8181     // not need the glue variants in a strictfp function.
8182 
8183     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8184 
8185     SDNode *EnableDenorm;
8186     if (Subtarget->hasDenormModeInst()) {
8187       const SDValue EnableDenormValue =
8188           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8189 
8190       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8191                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8192     } else {
8193       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8194                                                         SL, MVT::i32);
8195       EnableDenorm =
8196           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8197                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8198     }
8199 
8200     SDValue Ops[3] = {
8201       NegDivScale0,
8202       SDValue(EnableDenorm, 0),
8203       SDValue(EnableDenorm, 1)
8204     };
8205 
8206     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8207   }
8208 
8209   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8210                              ApproxRcp, One, NegDivScale0, Flags);
8211 
8212   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8213                              ApproxRcp, Fma0, Flags);
8214 
8215   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8216                            Fma1, Fma1, Flags);
8217 
8218   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8219                              NumeratorScaled, Mul, Flags);
8220 
8221   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8222                              Fma2, Fma1, Mul, Fma2, Flags);
8223 
8224   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8225                              NumeratorScaled, Fma3, Flags);
8226 
8227   if (!HasFP32Denormals) {
8228     SDNode *DisableDenorm;
8229     if (Subtarget->hasDenormModeInst()) {
8230       const SDValue DisableDenormValue =
8231           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8232 
8233       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8234                                   Fma4.getValue(1), DisableDenormValue,
8235                                   Fma4.getValue(2)).getNode();
8236     } else {
8237       const SDValue DisableDenormValue =
8238           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8239 
8240       DisableDenorm = DAG.getMachineNode(
8241           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8242           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8243     }
8244 
8245     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8246                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8247     DAG.setRoot(OutputChain);
8248   }
8249 
8250   SDValue Scale = NumeratorScaled.getValue(1);
8251   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8252                              {Fma4, Fma1, Fma3, Scale}, Flags);
8253 
8254   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8255 }
8256 
8257 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8258   if (DAG.getTarget().Options.UnsafeFPMath)
8259     return lowerFastUnsafeFDIV(Op, DAG);
8260 
8261   SDLoc SL(Op);
8262   SDValue X = Op.getOperand(0);
8263   SDValue Y = Op.getOperand(1);
8264 
8265   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8266 
8267   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8268 
8269   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8270 
8271   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8272 
8273   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8274 
8275   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8276 
8277   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8278 
8279   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8280 
8281   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8282 
8283   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8284   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8285 
8286   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8287                              NegDivScale0, Mul, DivScale1);
8288 
8289   SDValue Scale;
8290 
8291   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8292     // Workaround a hardware bug on SI where the condition output from div_scale
8293     // is not usable.
8294 
8295     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8296 
8297     // Figure out if the scale to use for div_fmas.
8298     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8299     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8300     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8301     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8302 
8303     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8304     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8305 
8306     SDValue Scale0Hi
8307       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8308     SDValue Scale1Hi
8309       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8310 
8311     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8312     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8313     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8314   } else {
8315     Scale = DivScale1.getValue(1);
8316   }
8317 
8318   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8319                              Fma4, Fma3, Mul, Scale);
8320 
8321   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8322 }
8323 
8324 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8325   EVT VT = Op.getValueType();
8326 
8327   if (VT == MVT::f32)
8328     return LowerFDIV32(Op, DAG);
8329 
8330   if (VT == MVT::f64)
8331     return LowerFDIV64(Op, DAG);
8332 
8333   if (VT == MVT::f16)
8334     return LowerFDIV16(Op, DAG);
8335 
8336   llvm_unreachable("Unexpected type for fdiv");
8337 }
8338 
8339 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8340   SDLoc DL(Op);
8341   StoreSDNode *Store = cast<StoreSDNode>(Op);
8342   EVT VT = Store->getMemoryVT();
8343 
8344   if (VT == MVT::i1) {
8345     return DAG.getTruncStore(Store->getChain(), DL,
8346        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8347        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8348   }
8349 
8350   assert(VT.isVector() &&
8351          Store->getValue().getValueType().getScalarType() == MVT::i32);
8352 
8353   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8354                                       VT, *Store->getMemOperand())) {
8355     return expandUnalignedStore(Store, DAG);
8356   }
8357 
8358   unsigned AS = Store->getAddressSpace();
8359   if (Subtarget->hasLDSMisalignedBug() &&
8360       AS == AMDGPUAS::FLAT_ADDRESS &&
8361       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8362     return SplitVectorStore(Op, DAG);
8363   }
8364 
8365   MachineFunction &MF = DAG.getMachineFunction();
8366   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8367   // If there is a possibilty that flat instruction access scratch memory
8368   // then we need to use the same legalization rules we use for private.
8369   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8370       !Subtarget->hasMultiDwordFlatScratchAddressing())
8371     AS = MFI->hasFlatScratchInit() ?
8372          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8373 
8374   unsigned NumElements = VT.getVectorNumElements();
8375   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8376       AS == AMDGPUAS::FLAT_ADDRESS) {
8377     if (NumElements > 4)
8378       return SplitVectorStore(Op, DAG);
8379     // v3 stores not supported on SI.
8380     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8381       return SplitVectorStore(Op, DAG);
8382     return SDValue();
8383   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8384     switch (Subtarget->getMaxPrivateElementSize()) {
8385     case 4:
8386       return scalarizeVectorStore(Store, DAG);
8387     case 8:
8388       if (NumElements > 2)
8389         return SplitVectorStore(Op, DAG);
8390       return SDValue();
8391     case 16:
8392       if (NumElements > 4 || NumElements == 3)
8393         return SplitVectorStore(Op, DAG);
8394       return SDValue();
8395     default:
8396       llvm_unreachable("unsupported private_element_size");
8397     }
8398   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8399     // Use ds_write_b128 if possible.
8400     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8401         VT.getStoreSize() == 16 && NumElements != 3)
8402       return SDValue();
8403 
8404     if (NumElements > 2)
8405       return SplitVectorStore(Op, DAG);
8406 
8407     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8408     // address is negative, then the instruction is incorrectly treated as
8409     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8410     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8411     // store later in the SILoadStoreOptimizer.
8412     if (!Subtarget->hasUsableDSOffset() &&
8413         NumElements == 2 && VT.getStoreSize() == 8 &&
8414         Store->getAlignment() < 8) {
8415       return SplitVectorStore(Op, DAG);
8416     }
8417 
8418     return SDValue();
8419   } else {
8420     llvm_unreachable("unhandled address space");
8421   }
8422 }
8423 
8424 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8425   SDLoc DL(Op);
8426   EVT VT = Op.getValueType();
8427   SDValue Arg = Op.getOperand(0);
8428   SDValue TrigVal;
8429 
8430   // Propagate fast-math flags so that the multiply we introduce can be folded
8431   // if Arg is already the result of a multiply by constant.
8432   auto Flags = Op->getFlags();
8433 
8434   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8435 
8436   if (Subtarget->hasTrigReducedRange()) {
8437     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8438     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8439   } else {
8440     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8441   }
8442 
8443   switch (Op.getOpcode()) {
8444   case ISD::FCOS:
8445     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8446   case ISD::FSIN:
8447     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8448   default:
8449     llvm_unreachable("Wrong trig opcode");
8450   }
8451 }
8452 
8453 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8454   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8455   assert(AtomicNode->isCompareAndSwap());
8456   unsigned AS = AtomicNode->getAddressSpace();
8457 
8458   // No custom lowering required for local address space
8459   if (!isFlatGlobalAddrSpace(AS))
8460     return Op;
8461 
8462   // Non-local address space requires custom lowering for atomic compare
8463   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8464   SDLoc DL(Op);
8465   SDValue ChainIn = Op.getOperand(0);
8466   SDValue Addr = Op.getOperand(1);
8467   SDValue Old = Op.getOperand(2);
8468   SDValue New = Op.getOperand(3);
8469   EVT VT = Op.getValueType();
8470   MVT SimpleVT = VT.getSimpleVT();
8471   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8472 
8473   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8474   SDValue Ops[] = { ChainIn, Addr, NewOld };
8475 
8476   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8477                                  Ops, VT, AtomicNode->getMemOperand());
8478 }
8479 
8480 //===----------------------------------------------------------------------===//
8481 // Custom DAG optimizations
8482 //===----------------------------------------------------------------------===//
8483 
8484 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8485                                                      DAGCombinerInfo &DCI) const {
8486   EVT VT = N->getValueType(0);
8487   EVT ScalarVT = VT.getScalarType();
8488   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8489     return SDValue();
8490 
8491   SelectionDAG &DAG = DCI.DAG;
8492   SDLoc DL(N);
8493 
8494   SDValue Src = N->getOperand(0);
8495   EVT SrcVT = Src.getValueType();
8496 
8497   // TODO: We could try to match extracting the higher bytes, which would be
8498   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8499   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8500   // about in practice.
8501   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8502     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8503       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8504       DCI.AddToWorklist(Cvt.getNode());
8505 
8506       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8507       if (ScalarVT != MVT::f32) {
8508         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8509                           DAG.getTargetConstant(0, DL, MVT::i32));
8510       }
8511       return Cvt;
8512     }
8513   }
8514 
8515   return SDValue();
8516 }
8517 
8518 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8519 
8520 // This is a variant of
8521 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8522 //
8523 // The normal DAG combiner will do this, but only if the add has one use since
8524 // that would increase the number of instructions.
8525 //
8526 // This prevents us from seeing a constant offset that can be folded into a
8527 // memory instruction's addressing mode. If we know the resulting add offset of
8528 // a pointer can be folded into an addressing offset, we can replace the pointer
8529 // operand with the add of new constant offset. This eliminates one of the uses,
8530 // and may allow the remaining use to also be simplified.
8531 //
8532 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8533                                                unsigned AddrSpace,
8534                                                EVT MemVT,
8535                                                DAGCombinerInfo &DCI) const {
8536   SDValue N0 = N->getOperand(0);
8537   SDValue N1 = N->getOperand(1);
8538 
8539   // We only do this to handle cases where it's profitable when there are
8540   // multiple uses of the add, so defer to the standard combine.
8541   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8542       N0->hasOneUse())
8543     return SDValue();
8544 
8545   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8546   if (!CN1)
8547     return SDValue();
8548 
8549   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8550   if (!CAdd)
8551     return SDValue();
8552 
8553   // If the resulting offset is too large, we can't fold it into the addressing
8554   // mode offset.
8555   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8556   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8557 
8558   AddrMode AM;
8559   AM.HasBaseReg = true;
8560   AM.BaseOffs = Offset.getSExtValue();
8561   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8562     return SDValue();
8563 
8564   SelectionDAG &DAG = DCI.DAG;
8565   SDLoc SL(N);
8566   EVT VT = N->getValueType(0);
8567 
8568   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8569   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8570 
8571   SDNodeFlags Flags;
8572   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8573                           (N0.getOpcode() == ISD::OR ||
8574                            N0->getFlags().hasNoUnsignedWrap()));
8575 
8576   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8577 }
8578 
8579 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8580                                                   DAGCombinerInfo &DCI) const {
8581   SDValue Ptr = N->getBasePtr();
8582   SelectionDAG &DAG = DCI.DAG;
8583   SDLoc SL(N);
8584 
8585   // TODO: We could also do this for multiplies.
8586   if (Ptr.getOpcode() == ISD::SHL) {
8587     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8588                                           N->getMemoryVT(), DCI);
8589     if (NewPtr) {
8590       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8591 
8592       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8593       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8594     }
8595   }
8596 
8597   return SDValue();
8598 }
8599 
8600 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8601   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8602          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8603          (Opc == ISD::XOR && Val == 0);
8604 }
8605 
8606 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8607 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8608 // integer combine opportunities since most 64-bit operations are decomposed
8609 // this way.  TODO: We won't want this for SALU especially if it is an inline
8610 // immediate.
8611 SDValue SITargetLowering::splitBinaryBitConstantOp(
8612   DAGCombinerInfo &DCI,
8613   const SDLoc &SL,
8614   unsigned Opc, SDValue LHS,
8615   const ConstantSDNode *CRHS) const {
8616   uint64_t Val = CRHS->getZExtValue();
8617   uint32_t ValLo = Lo_32(Val);
8618   uint32_t ValHi = Hi_32(Val);
8619   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8620 
8621     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8622          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8623         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8624     // If we need to materialize a 64-bit immediate, it will be split up later
8625     // anyway. Avoid creating the harder to understand 64-bit immediate
8626     // materialization.
8627     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8628   }
8629 
8630   return SDValue();
8631 }
8632 
8633 // Returns true if argument is a boolean value which is not serialized into
8634 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8635 static bool isBoolSGPR(SDValue V) {
8636   if (V.getValueType() != MVT::i1)
8637     return false;
8638   switch (V.getOpcode()) {
8639   default: break;
8640   case ISD::SETCC:
8641   case ISD::AND:
8642   case ISD::OR:
8643   case ISD::XOR:
8644   case AMDGPUISD::FP_CLASS:
8645     return true;
8646   }
8647   return false;
8648 }
8649 
8650 // If a constant has all zeroes or all ones within each byte return it.
8651 // Otherwise return 0.
8652 static uint32_t getConstantPermuteMask(uint32_t C) {
8653   // 0xff for any zero byte in the mask
8654   uint32_t ZeroByteMask = 0;
8655   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8656   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8657   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8658   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8659   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8660   if ((NonZeroByteMask & C) != NonZeroByteMask)
8661     return 0; // Partial bytes selected.
8662   return C;
8663 }
8664 
8665 // Check if a node selects whole bytes from its operand 0 starting at a byte
8666 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8667 // or -1 if not succeeded.
8668 // Note byte select encoding:
8669 // value 0-3 selects corresponding source byte;
8670 // value 0xc selects zero;
8671 // value 0xff selects 0xff.
8672 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8673   assert(V.getValueSizeInBits() == 32);
8674 
8675   if (V.getNumOperands() != 2)
8676     return ~0;
8677 
8678   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8679   if (!N1)
8680     return ~0;
8681 
8682   uint32_t C = N1->getZExtValue();
8683 
8684   switch (V.getOpcode()) {
8685   default:
8686     break;
8687   case ISD::AND:
8688     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8689       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8690     }
8691     break;
8692 
8693   case ISD::OR:
8694     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8695       return (0x03020100 & ~ConstMask) | ConstMask;
8696     }
8697     break;
8698 
8699   case ISD::SHL:
8700     if (C % 8)
8701       return ~0;
8702 
8703     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8704 
8705   case ISD::SRL:
8706     if (C % 8)
8707       return ~0;
8708 
8709     return uint32_t(0x0c0c0c0c03020100ull >> C);
8710   }
8711 
8712   return ~0;
8713 }
8714 
8715 SDValue SITargetLowering::performAndCombine(SDNode *N,
8716                                             DAGCombinerInfo &DCI) const {
8717   if (DCI.isBeforeLegalize())
8718     return SDValue();
8719 
8720   SelectionDAG &DAG = DCI.DAG;
8721   EVT VT = N->getValueType(0);
8722   SDValue LHS = N->getOperand(0);
8723   SDValue RHS = N->getOperand(1);
8724 
8725 
8726   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8727   if (VT == MVT::i64 && CRHS) {
8728     if (SDValue Split
8729         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8730       return Split;
8731   }
8732 
8733   if (CRHS && VT == MVT::i32) {
8734     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8735     // nb = number of trailing zeroes in mask
8736     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8737     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8738     uint64_t Mask = CRHS->getZExtValue();
8739     unsigned Bits = countPopulation(Mask);
8740     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8741         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8742       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8743         unsigned Shift = CShift->getZExtValue();
8744         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8745         unsigned Offset = NB + Shift;
8746         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8747           SDLoc SL(N);
8748           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8749                                     LHS->getOperand(0),
8750                                     DAG.getConstant(Offset, SL, MVT::i32),
8751                                     DAG.getConstant(Bits, SL, MVT::i32));
8752           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8753           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8754                                     DAG.getValueType(NarrowVT));
8755           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8756                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8757           return Shl;
8758         }
8759       }
8760     }
8761 
8762     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8763     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8764         isa<ConstantSDNode>(LHS.getOperand(2))) {
8765       uint32_t Sel = getConstantPermuteMask(Mask);
8766       if (!Sel)
8767         return SDValue();
8768 
8769       // Select 0xc for all zero bytes
8770       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8771       SDLoc DL(N);
8772       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8773                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8774     }
8775   }
8776 
8777   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8778   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8779   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8780     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8781     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8782 
8783     SDValue X = LHS.getOperand(0);
8784     SDValue Y = RHS.getOperand(0);
8785     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8786       return SDValue();
8787 
8788     if (LCC == ISD::SETO) {
8789       if (X != LHS.getOperand(1))
8790         return SDValue();
8791 
8792       if (RCC == ISD::SETUNE) {
8793         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8794         if (!C1 || !C1->isInfinity() || C1->isNegative())
8795           return SDValue();
8796 
8797         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8798                               SIInstrFlags::N_SUBNORMAL |
8799                               SIInstrFlags::N_ZERO |
8800                               SIInstrFlags::P_ZERO |
8801                               SIInstrFlags::P_SUBNORMAL |
8802                               SIInstrFlags::P_NORMAL;
8803 
8804         static_assert(((~(SIInstrFlags::S_NAN |
8805                           SIInstrFlags::Q_NAN |
8806                           SIInstrFlags::N_INFINITY |
8807                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8808                       "mask not equal");
8809 
8810         SDLoc DL(N);
8811         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8812                            X, DAG.getConstant(Mask, DL, MVT::i32));
8813       }
8814     }
8815   }
8816 
8817   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8818     std::swap(LHS, RHS);
8819 
8820   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8821       RHS.hasOneUse()) {
8822     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8823     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8824     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8825     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8826     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8827         (RHS.getOperand(0) == LHS.getOperand(0) &&
8828          LHS.getOperand(0) == LHS.getOperand(1))) {
8829       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8830       unsigned NewMask = LCC == ISD::SETO ?
8831         Mask->getZExtValue() & ~OrdMask :
8832         Mask->getZExtValue() & OrdMask;
8833 
8834       SDLoc DL(N);
8835       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8836                          DAG.getConstant(NewMask, DL, MVT::i32));
8837     }
8838   }
8839 
8840   if (VT == MVT::i32 &&
8841       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8842     // and x, (sext cc from i1) => select cc, x, 0
8843     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8844       std::swap(LHS, RHS);
8845     if (isBoolSGPR(RHS.getOperand(0)))
8846       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8847                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8848   }
8849 
8850   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8851   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8852   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8853       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8854     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8855     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8856     if (LHSMask != ~0u && RHSMask != ~0u) {
8857       // Canonicalize the expression in an attempt to have fewer unique masks
8858       // and therefore fewer registers used to hold the masks.
8859       if (LHSMask > RHSMask) {
8860         std::swap(LHSMask, RHSMask);
8861         std::swap(LHS, RHS);
8862       }
8863 
8864       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8865       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8866       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8867       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8868 
8869       // Check of we need to combine values from two sources within a byte.
8870       if (!(LHSUsedLanes & RHSUsedLanes) &&
8871           // If we select high and lower word keep it for SDWA.
8872           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8873           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8874         // Each byte in each mask is either selector mask 0-3, or has higher
8875         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8876         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8877         // mask which is not 0xff wins. By anding both masks we have a correct
8878         // result except that 0x0c shall be corrected to give 0x0c only.
8879         uint32_t Mask = LHSMask & RHSMask;
8880         for (unsigned I = 0; I < 32; I += 8) {
8881           uint32_t ByteSel = 0xff << I;
8882           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8883             Mask &= (0x0c << I) & 0xffffffff;
8884         }
8885 
8886         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8887         // or 0x0c.
8888         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8889         SDLoc DL(N);
8890 
8891         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8892                            LHS.getOperand(0), RHS.getOperand(0),
8893                            DAG.getConstant(Sel, DL, MVT::i32));
8894       }
8895     }
8896   }
8897 
8898   return SDValue();
8899 }
8900 
8901 SDValue SITargetLowering::performOrCombine(SDNode *N,
8902                                            DAGCombinerInfo &DCI) const {
8903   SelectionDAG &DAG = DCI.DAG;
8904   SDValue LHS = N->getOperand(0);
8905   SDValue RHS = N->getOperand(1);
8906 
8907   EVT VT = N->getValueType(0);
8908   if (VT == MVT::i1) {
8909     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8910     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8911         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8912       SDValue Src = LHS.getOperand(0);
8913       if (Src != RHS.getOperand(0))
8914         return SDValue();
8915 
8916       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8917       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8918       if (!CLHS || !CRHS)
8919         return SDValue();
8920 
8921       // Only 10 bits are used.
8922       static const uint32_t MaxMask = 0x3ff;
8923 
8924       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8925       SDLoc DL(N);
8926       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8927                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8928     }
8929 
8930     return SDValue();
8931   }
8932 
8933   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8934   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8935       LHS.getOpcode() == AMDGPUISD::PERM &&
8936       isa<ConstantSDNode>(LHS.getOperand(2))) {
8937     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8938     if (!Sel)
8939       return SDValue();
8940 
8941     Sel |= LHS.getConstantOperandVal(2);
8942     SDLoc DL(N);
8943     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8944                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8945   }
8946 
8947   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8948   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8949   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8950       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8951     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8952     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8953     if (LHSMask != ~0u && RHSMask != ~0u) {
8954       // Canonicalize the expression in an attempt to have fewer unique masks
8955       // and therefore fewer registers used to hold the masks.
8956       if (LHSMask > RHSMask) {
8957         std::swap(LHSMask, RHSMask);
8958         std::swap(LHS, RHS);
8959       }
8960 
8961       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8962       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8963       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8964       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8965 
8966       // Check of we need to combine values from two sources within a byte.
8967       if (!(LHSUsedLanes & RHSUsedLanes) &&
8968           // If we select high and lower word keep it for SDWA.
8969           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8970           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8971         // Kill zero bytes selected by other mask. Zero value is 0xc.
8972         LHSMask &= ~RHSUsedLanes;
8973         RHSMask &= ~LHSUsedLanes;
8974         // Add 4 to each active LHS lane
8975         LHSMask |= LHSUsedLanes & 0x04040404;
8976         // Combine masks
8977         uint32_t Sel = LHSMask | RHSMask;
8978         SDLoc DL(N);
8979 
8980         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8981                            LHS.getOperand(0), RHS.getOperand(0),
8982                            DAG.getConstant(Sel, DL, MVT::i32));
8983       }
8984     }
8985   }
8986 
8987   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
8988     return SDValue();
8989 
8990   // TODO: This could be a generic combine with a predicate for extracting the
8991   // high half of an integer being free.
8992 
8993   // (or i64:x, (zero_extend i32:y)) ->
8994   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8995   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8996       RHS.getOpcode() != ISD::ZERO_EXTEND)
8997     std::swap(LHS, RHS);
8998 
8999   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9000     SDValue ExtSrc = RHS.getOperand(0);
9001     EVT SrcVT = ExtSrc.getValueType();
9002     if (SrcVT == MVT::i32) {
9003       SDLoc SL(N);
9004       SDValue LowLHS, HiBits;
9005       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9006       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9007 
9008       DCI.AddToWorklist(LowOr.getNode());
9009       DCI.AddToWorklist(HiBits.getNode());
9010 
9011       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9012                                 LowOr, HiBits);
9013       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9014     }
9015   }
9016 
9017   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9018   if (CRHS) {
9019     if (SDValue Split
9020           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9021       return Split;
9022   }
9023 
9024   return SDValue();
9025 }
9026 
9027 SDValue SITargetLowering::performXorCombine(SDNode *N,
9028                                             DAGCombinerInfo &DCI) const {
9029   EVT VT = N->getValueType(0);
9030   if (VT != MVT::i64)
9031     return SDValue();
9032 
9033   SDValue LHS = N->getOperand(0);
9034   SDValue RHS = N->getOperand(1);
9035 
9036   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9037   if (CRHS) {
9038     if (SDValue Split
9039           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9040       return Split;
9041   }
9042 
9043   return SDValue();
9044 }
9045 
9046 // Instructions that will be lowered with a final instruction that zeros the
9047 // high result bits.
9048 // XXX - probably only need to list legal operations.
9049 static bool fp16SrcZerosHighBits(unsigned Opc) {
9050   switch (Opc) {
9051   case ISD::FADD:
9052   case ISD::FSUB:
9053   case ISD::FMUL:
9054   case ISD::FDIV:
9055   case ISD::FREM:
9056   case ISD::FMA:
9057   case ISD::FMAD:
9058   case ISD::FCANONICALIZE:
9059   case ISD::FP_ROUND:
9060   case ISD::UINT_TO_FP:
9061   case ISD::SINT_TO_FP:
9062   case ISD::FABS:
9063     // Fabs is lowered to a bit operation, but it's an and which will clear the
9064     // high bits anyway.
9065   case ISD::FSQRT:
9066   case ISD::FSIN:
9067   case ISD::FCOS:
9068   case ISD::FPOWI:
9069   case ISD::FPOW:
9070   case ISD::FLOG:
9071   case ISD::FLOG2:
9072   case ISD::FLOG10:
9073   case ISD::FEXP:
9074   case ISD::FEXP2:
9075   case ISD::FCEIL:
9076   case ISD::FTRUNC:
9077   case ISD::FRINT:
9078   case ISD::FNEARBYINT:
9079   case ISD::FROUND:
9080   case ISD::FFLOOR:
9081   case ISD::FMINNUM:
9082   case ISD::FMAXNUM:
9083   case AMDGPUISD::FRACT:
9084   case AMDGPUISD::CLAMP:
9085   case AMDGPUISD::COS_HW:
9086   case AMDGPUISD::SIN_HW:
9087   case AMDGPUISD::FMIN3:
9088   case AMDGPUISD::FMAX3:
9089   case AMDGPUISD::FMED3:
9090   case AMDGPUISD::FMAD_FTZ:
9091   case AMDGPUISD::RCP:
9092   case AMDGPUISD::RSQ:
9093   case AMDGPUISD::RCP_IFLAG:
9094   case AMDGPUISD::LDEXP:
9095     return true;
9096   default:
9097     // fcopysign, select and others may be lowered to 32-bit bit operations
9098     // which don't zero the high bits.
9099     return false;
9100   }
9101 }
9102 
9103 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9104                                                    DAGCombinerInfo &DCI) const {
9105   if (!Subtarget->has16BitInsts() ||
9106       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9107     return SDValue();
9108 
9109   EVT VT = N->getValueType(0);
9110   if (VT != MVT::i32)
9111     return SDValue();
9112 
9113   SDValue Src = N->getOperand(0);
9114   if (Src.getValueType() != MVT::i16)
9115     return SDValue();
9116 
9117   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9118   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9119   if (Src.getOpcode() == ISD::BITCAST) {
9120     SDValue BCSrc = Src.getOperand(0);
9121     if (BCSrc.getValueType() == MVT::f16 &&
9122         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9123       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9124   }
9125 
9126   return SDValue();
9127 }
9128 
9129 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9130                                                         DAGCombinerInfo &DCI)
9131                                                         const {
9132   SDValue Src = N->getOperand(0);
9133   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9134 
9135   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9136       VTSign->getVT() == MVT::i8) ||
9137       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9138       VTSign->getVT() == MVT::i16)) &&
9139       Src.hasOneUse()) {
9140     auto *M = cast<MemSDNode>(Src);
9141     SDValue Ops[] = {
9142       Src.getOperand(0), // Chain
9143       Src.getOperand(1), // rsrc
9144       Src.getOperand(2), // vindex
9145       Src.getOperand(3), // voffset
9146       Src.getOperand(4), // soffset
9147       Src.getOperand(5), // offset
9148       Src.getOperand(6),
9149       Src.getOperand(7)
9150     };
9151     // replace with BUFFER_LOAD_BYTE/SHORT
9152     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9153                                          Src.getOperand(0).getValueType());
9154     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9155                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9156     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9157                                                           ResList,
9158                                                           Ops, M->getMemoryVT(),
9159                                                           M->getMemOperand());
9160     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9161                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9162   }
9163   return SDValue();
9164 }
9165 
9166 SDValue SITargetLowering::performClassCombine(SDNode *N,
9167                                               DAGCombinerInfo &DCI) const {
9168   SelectionDAG &DAG = DCI.DAG;
9169   SDValue Mask = N->getOperand(1);
9170 
9171   // fp_class x, 0 -> false
9172   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9173     if (CMask->isNullValue())
9174       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9175   }
9176 
9177   if (N->getOperand(0).isUndef())
9178     return DAG.getUNDEF(MVT::i1);
9179 
9180   return SDValue();
9181 }
9182 
9183 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9184                                             DAGCombinerInfo &DCI) const {
9185   EVT VT = N->getValueType(0);
9186   SDValue N0 = N->getOperand(0);
9187 
9188   if (N0.isUndef())
9189     return N0;
9190 
9191   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9192                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9193     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9194                            N->getFlags());
9195   }
9196 
9197   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9198     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9199                            N0.getOperand(0), N->getFlags());
9200   }
9201 
9202   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9203 }
9204 
9205 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9206                                        unsigned MaxDepth) const {
9207   unsigned Opcode = Op.getOpcode();
9208   if (Opcode == ISD::FCANONICALIZE)
9209     return true;
9210 
9211   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9212     auto F = CFP->getValueAPF();
9213     if (F.isNaN() && F.isSignaling())
9214       return false;
9215     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9216   }
9217 
9218   // If source is a result of another standard FP operation it is already in
9219   // canonical form.
9220   if (MaxDepth == 0)
9221     return false;
9222 
9223   switch (Opcode) {
9224   // These will flush denorms if required.
9225   case ISD::FADD:
9226   case ISD::FSUB:
9227   case ISD::FMUL:
9228   case ISD::FCEIL:
9229   case ISD::FFLOOR:
9230   case ISD::FMA:
9231   case ISD::FMAD:
9232   case ISD::FSQRT:
9233   case ISD::FDIV:
9234   case ISD::FREM:
9235   case ISD::FP_ROUND:
9236   case ISD::FP_EXTEND:
9237   case AMDGPUISD::FMUL_LEGACY:
9238   case AMDGPUISD::FMAD_FTZ:
9239   case AMDGPUISD::RCP:
9240   case AMDGPUISD::RSQ:
9241   case AMDGPUISD::RSQ_CLAMP:
9242   case AMDGPUISD::RCP_LEGACY:
9243   case AMDGPUISD::RCP_IFLAG:
9244   case AMDGPUISD::TRIG_PREOP:
9245   case AMDGPUISD::DIV_SCALE:
9246   case AMDGPUISD::DIV_FMAS:
9247   case AMDGPUISD::DIV_FIXUP:
9248   case AMDGPUISD::FRACT:
9249   case AMDGPUISD::LDEXP:
9250   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9251   case AMDGPUISD::CVT_F32_UBYTE0:
9252   case AMDGPUISD::CVT_F32_UBYTE1:
9253   case AMDGPUISD::CVT_F32_UBYTE2:
9254   case AMDGPUISD::CVT_F32_UBYTE3:
9255     return true;
9256 
9257   // It can/will be lowered or combined as a bit operation.
9258   // Need to check their input recursively to handle.
9259   case ISD::FNEG:
9260   case ISD::FABS:
9261   case ISD::FCOPYSIGN:
9262     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9263 
9264   case ISD::FSIN:
9265   case ISD::FCOS:
9266   case ISD::FSINCOS:
9267     return Op.getValueType().getScalarType() != MVT::f16;
9268 
9269   case ISD::FMINNUM:
9270   case ISD::FMAXNUM:
9271   case ISD::FMINNUM_IEEE:
9272   case ISD::FMAXNUM_IEEE:
9273   case AMDGPUISD::CLAMP:
9274   case AMDGPUISD::FMED3:
9275   case AMDGPUISD::FMAX3:
9276   case AMDGPUISD::FMIN3: {
9277     // FIXME: Shouldn't treat the generic operations different based these.
9278     // However, we aren't really required to flush the result from
9279     // minnum/maxnum..
9280 
9281     // snans will be quieted, so we only need to worry about denormals.
9282     if (Subtarget->supportsMinMaxDenormModes() ||
9283         denormalsEnabledForType(DAG, Op.getValueType()))
9284       return true;
9285 
9286     // Flushing may be required.
9287     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9288     // targets need to check their input recursively.
9289 
9290     // FIXME: Does this apply with clamp? It's implemented with max.
9291     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9292       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9293         return false;
9294     }
9295 
9296     return true;
9297   }
9298   case ISD::SELECT: {
9299     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9300            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9301   }
9302   case ISD::BUILD_VECTOR: {
9303     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9304       SDValue SrcOp = Op.getOperand(i);
9305       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9306         return false;
9307     }
9308 
9309     return true;
9310   }
9311   case ISD::EXTRACT_VECTOR_ELT:
9312   case ISD::EXTRACT_SUBVECTOR: {
9313     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9314   }
9315   case ISD::INSERT_VECTOR_ELT: {
9316     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9317            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9318   }
9319   case ISD::UNDEF:
9320     // Could be anything.
9321     return false;
9322 
9323   case ISD::BITCAST: {
9324     // Hack round the mess we make when legalizing extract_vector_elt
9325     SDValue Src = Op.getOperand(0);
9326     if (Src.getValueType() == MVT::i16 &&
9327         Src.getOpcode() == ISD::TRUNCATE) {
9328       SDValue TruncSrc = Src.getOperand(0);
9329       if (TruncSrc.getValueType() == MVT::i32 &&
9330           TruncSrc.getOpcode() == ISD::BITCAST &&
9331           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9332         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9333       }
9334     }
9335 
9336     return false;
9337   }
9338   case ISD::INTRINSIC_WO_CHAIN: {
9339     unsigned IntrinsicID
9340       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9341     // TODO: Handle more intrinsics
9342     switch (IntrinsicID) {
9343     case Intrinsic::amdgcn_cvt_pkrtz:
9344     case Intrinsic::amdgcn_cubeid:
9345     case Intrinsic::amdgcn_frexp_mant:
9346     case Intrinsic::amdgcn_fdot2:
9347     case Intrinsic::amdgcn_rcp:
9348     case Intrinsic::amdgcn_rsq:
9349     case Intrinsic::amdgcn_rsq_clamp:
9350     case Intrinsic::amdgcn_rcp_legacy:
9351     case Intrinsic::amdgcn_rsq_legacy:
9352       return true;
9353     default:
9354       break;
9355     }
9356 
9357     LLVM_FALLTHROUGH;
9358   }
9359   default:
9360     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9361            DAG.isKnownNeverSNaN(Op);
9362   }
9363 
9364   llvm_unreachable("invalid operation");
9365 }
9366 
9367 // Constant fold canonicalize.
9368 SDValue SITargetLowering::getCanonicalConstantFP(
9369   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9370   // Flush denormals to 0 if not enabled.
9371   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9372     return DAG.getConstantFP(0.0, SL, VT);
9373 
9374   if (C.isNaN()) {
9375     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9376     if (C.isSignaling()) {
9377       // Quiet a signaling NaN.
9378       // FIXME: Is this supposed to preserve payload bits?
9379       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9380     }
9381 
9382     // Make sure it is the canonical NaN bitpattern.
9383     //
9384     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9385     // immediate?
9386     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9387       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9388   }
9389 
9390   // Already canonical.
9391   return DAG.getConstantFP(C, SL, VT);
9392 }
9393 
9394 static bool vectorEltWillFoldAway(SDValue Op) {
9395   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9396 }
9397 
9398 SDValue SITargetLowering::performFCanonicalizeCombine(
9399   SDNode *N,
9400   DAGCombinerInfo &DCI) const {
9401   SelectionDAG &DAG = DCI.DAG;
9402   SDValue N0 = N->getOperand(0);
9403   EVT VT = N->getValueType(0);
9404 
9405   // fcanonicalize undef -> qnan
9406   if (N0.isUndef()) {
9407     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9408     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9409   }
9410 
9411   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9412     EVT VT = N->getValueType(0);
9413     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9414   }
9415 
9416   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9417   //                                                   (fcanonicalize k)
9418   //
9419   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9420 
9421   // TODO: This could be better with wider vectors that will be split to v2f16,
9422   // and to consider uses since there aren't that many packed operations.
9423   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9424       isTypeLegal(MVT::v2f16)) {
9425     SDLoc SL(N);
9426     SDValue NewElts[2];
9427     SDValue Lo = N0.getOperand(0);
9428     SDValue Hi = N0.getOperand(1);
9429     EVT EltVT = Lo.getValueType();
9430 
9431     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9432       for (unsigned I = 0; I != 2; ++I) {
9433         SDValue Op = N0.getOperand(I);
9434         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9435           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9436                                               CFP->getValueAPF());
9437         } else if (Op.isUndef()) {
9438           // Handled below based on what the other operand is.
9439           NewElts[I] = Op;
9440         } else {
9441           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9442         }
9443       }
9444 
9445       // If one half is undef, and one is constant, perfer a splat vector rather
9446       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9447       // cheaper to use and may be free with a packed operation.
9448       if (NewElts[0].isUndef()) {
9449         if (isa<ConstantFPSDNode>(NewElts[1]))
9450           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9451             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9452       }
9453 
9454       if (NewElts[1].isUndef()) {
9455         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9456           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9457       }
9458 
9459       return DAG.getBuildVector(VT, SL, NewElts);
9460     }
9461   }
9462 
9463   unsigned SrcOpc = N0.getOpcode();
9464 
9465   // If it's free to do so, push canonicalizes further up the source, which may
9466   // find a canonical source.
9467   //
9468   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9469   // sNaNs.
9470   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9471     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9472     if (CRHS && N0.hasOneUse()) {
9473       SDLoc SL(N);
9474       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9475                                    N0.getOperand(0));
9476       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9477       DCI.AddToWorklist(Canon0.getNode());
9478 
9479       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9480     }
9481   }
9482 
9483   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9484 }
9485 
9486 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9487   switch (Opc) {
9488   case ISD::FMAXNUM:
9489   case ISD::FMAXNUM_IEEE:
9490     return AMDGPUISD::FMAX3;
9491   case ISD::SMAX:
9492     return AMDGPUISD::SMAX3;
9493   case ISD::UMAX:
9494     return AMDGPUISD::UMAX3;
9495   case ISD::FMINNUM:
9496   case ISD::FMINNUM_IEEE:
9497     return AMDGPUISD::FMIN3;
9498   case ISD::SMIN:
9499     return AMDGPUISD::SMIN3;
9500   case ISD::UMIN:
9501     return AMDGPUISD::UMIN3;
9502   default:
9503     llvm_unreachable("Not a min/max opcode");
9504   }
9505 }
9506 
9507 SDValue SITargetLowering::performIntMed3ImmCombine(
9508   SelectionDAG &DAG, const SDLoc &SL,
9509   SDValue Op0, SDValue Op1, bool Signed) const {
9510   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9511   if (!K1)
9512     return SDValue();
9513 
9514   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9515   if (!K0)
9516     return SDValue();
9517 
9518   if (Signed) {
9519     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9520       return SDValue();
9521   } else {
9522     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9523       return SDValue();
9524   }
9525 
9526   EVT VT = K0->getValueType(0);
9527   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9528   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9529     return DAG.getNode(Med3Opc, SL, VT,
9530                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9531   }
9532 
9533   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9534   MVT NVT = MVT::i32;
9535   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9536 
9537   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9538   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9539   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9540 
9541   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9542   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9543 }
9544 
9545 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9546   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9547     return C;
9548 
9549   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9550     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9551       return C;
9552   }
9553 
9554   return nullptr;
9555 }
9556 
9557 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9558                                                   const SDLoc &SL,
9559                                                   SDValue Op0,
9560                                                   SDValue Op1) const {
9561   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9562   if (!K1)
9563     return SDValue();
9564 
9565   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9566   if (!K0)
9567     return SDValue();
9568 
9569   // Ordered >= (although NaN inputs should have folded away by now).
9570   if (K0->getValueAPF() > K1->getValueAPF())
9571     return SDValue();
9572 
9573   const MachineFunction &MF = DAG.getMachineFunction();
9574   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9575 
9576   // TODO: Check IEEE bit enabled?
9577   EVT VT = Op0.getValueType();
9578   if (Info->getMode().DX10Clamp) {
9579     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9580     // hardware fmed3 behavior converting to a min.
9581     // FIXME: Should this be allowing -0.0?
9582     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9583       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9584   }
9585 
9586   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9587   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9588     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9589     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9590     // then give the other result, which is different from med3 with a NaN
9591     // input.
9592     SDValue Var = Op0.getOperand(0);
9593     if (!DAG.isKnownNeverSNaN(Var))
9594       return SDValue();
9595 
9596     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9597 
9598     if ((!K0->hasOneUse() ||
9599          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9600         (!K1->hasOneUse() ||
9601          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9602       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9603                          Var, SDValue(K0, 0), SDValue(K1, 0));
9604     }
9605   }
9606 
9607   return SDValue();
9608 }
9609 
9610 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9611                                                DAGCombinerInfo &DCI) const {
9612   SelectionDAG &DAG = DCI.DAG;
9613 
9614   EVT VT = N->getValueType(0);
9615   unsigned Opc = N->getOpcode();
9616   SDValue Op0 = N->getOperand(0);
9617   SDValue Op1 = N->getOperand(1);
9618 
9619   // Only do this if the inner op has one use since this will just increases
9620   // register pressure for no benefit.
9621 
9622   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9623       !VT.isVector() &&
9624       (VT == MVT::i32 || VT == MVT::f32 ||
9625        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9626     // max(max(a, b), c) -> max3(a, b, c)
9627     // min(min(a, b), c) -> min3(a, b, c)
9628     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9629       SDLoc DL(N);
9630       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9631                          DL,
9632                          N->getValueType(0),
9633                          Op0.getOperand(0),
9634                          Op0.getOperand(1),
9635                          Op1);
9636     }
9637 
9638     // Try commuted.
9639     // max(a, max(b, c)) -> max3(a, b, c)
9640     // min(a, min(b, c)) -> min3(a, b, c)
9641     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9642       SDLoc DL(N);
9643       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9644                          DL,
9645                          N->getValueType(0),
9646                          Op0,
9647                          Op1.getOperand(0),
9648                          Op1.getOperand(1));
9649     }
9650   }
9651 
9652   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9653   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9654     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9655       return Med3;
9656   }
9657 
9658   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9659     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9660       return Med3;
9661   }
9662 
9663   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9664   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9665        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9666        (Opc == AMDGPUISD::FMIN_LEGACY &&
9667         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9668       (VT == MVT::f32 || VT == MVT::f64 ||
9669        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9670        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9671       Op0.hasOneUse()) {
9672     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9673       return Res;
9674   }
9675 
9676   return SDValue();
9677 }
9678 
9679 static bool isClampZeroToOne(SDValue A, SDValue B) {
9680   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9681     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9682       // FIXME: Should this be allowing -0.0?
9683       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9684              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9685     }
9686   }
9687 
9688   return false;
9689 }
9690 
9691 // FIXME: Should only worry about snans for version with chain.
9692 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9693                                               DAGCombinerInfo &DCI) const {
9694   EVT VT = N->getValueType(0);
9695   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9696   // NaNs. With a NaN input, the order of the operands may change the result.
9697 
9698   SelectionDAG &DAG = DCI.DAG;
9699   SDLoc SL(N);
9700 
9701   SDValue Src0 = N->getOperand(0);
9702   SDValue Src1 = N->getOperand(1);
9703   SDValue Src2 = N->getOperand(2);
9704 
9705   if (isClampZeroToOne(Src0, Src1)) {
9706     // const_a, const_b, x -> clamp is safe in all cases including signaling
9707     // nans.
9708     // FIXME: Should this be allowing -0.0?
9709     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9710   }
9711 
9712   const MachineFunction &MF = DAG.getMachineFunction();
9713   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9714 
9715   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9716   // handling no dx10-clamp?
9717   if (Info->getMode().DX10Clamp) {
9718     // If NaNs is clamped to 0, we are free to reorder the inputs.
9719 
9720     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9721       std::swap(Src0, Src1);
9722 
9723     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9724       std::swap(Src1, Src2);
9725 
9726     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9727       std::swap(Src0, Src1);
9728 
9729     if (isClampZeroToOne(Src1, Src2))
9730       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9731   }
9732 
9733   return SDValue();
9734 }
9735 
9736 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9737                                                  DAGCombinerInfo &DCI) const {
9738   SDValue Src0 = N->getOperand(0);
9739   SDValue Src1 = N->getOperand(1);
9740   if (Src0.isUndef() && Src1.isUndef())
9741     return DCI.DAG.getUNDEF(N->getValueType(0));
9742   return SDValue();
9743 }
9744 
9745 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9746 // expanded into a set of cmp/select instructions.
9747 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9748                                                 unsigned NumElem,
9749                                                 bool IsDivergentIdx) {
9750   if (UseDivergentRegisterIndexing)
9751     return false;
9752 
9753   unsigned VecSize = EltSize * NumElem;
9754 
9755   // Sub-dword vectors of size 2 dword or less have better implementation.
9756   if (VecSize <= 64 && EltSize < 32)
9757     return false;
9758 
9759   // Always expand the rest of sub-dword instructions, otherwise it will be
9760   // lowered via memory.
9761   if (EltSize < 32)
9762     return true;
9763 
9764   // Always do this if var-idx is divergent, otherwise it will become a loop.
9765   if (IsDivergentIdx)
9766     return true;
9767 
9768   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9769   unsigned NumInsts = NumElem /* Number of compares */ +
9770                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9771   return NumInsts <= 16;
9772 }
9773 
9774 static bool shouldExpandVectorDynExt(SDNode *N) {
9775   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9776   if (isa<ConstantSDNode>(Idx))
9777     return false;
9778 
9779   SDValue Vec = N->getOperand(0);
9780   EVT VecVT = Vec.getValueType();
9781   EVT EltVT = VecVT.getVectorElementType();
9782   unsigned EltSize = EltVT.getSizeInBits();
9783   unsigned NumElem = VecVT.getVectorNumElements();
9784 
9785   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9786                                                     Idx->isDivergent());
9787 }
9788 
9789 SDValue SITargetLowering::performExtractVectorEltCombine(
9790   SDNode *N, DAGCombinerInfo &DCI) const {
9791   SDValue Vec = N->getOperand(0);
9792   SelectionDAG &DAG = DCI.DAG;
9793 
9794   EVT VecVT = Vec.getValueType();
9795   EVT EltVT = VecVT.getVectorElementType();
9796 
9797   if ((Vec.getOpcode() == ISD::FNEG ||
9798        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9799     SDLoc SL(N);
9800     EVT EltVT = N->getValueType(0);
9801     SDValue Idx = N->getOperand(1);
9802     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9803                               Vec.getOperand(0), Idx);
9804     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9805   }
9806 
9807   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9808   //    =>
9809   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9810   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9811   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9812   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9813     SDLoc SL(N);
9814     EVT EltVT = N->getValueType(0);
9815     SDValue Idx = N->getOperand(1);
9816     unsigned Opc = Vec.getOpcode();
9817 
9818     switch(Opc) {
9819     default:
9820       break;
9821       // TODO: Support other binary operations.
9822     case ISD::FADD:
9823     case ISD::FSUB:
9824     case ISD::FMUL:
9825     case ISD::ADD:
9826     case ISD::UMIN:
9827     case ISD::UMAX:
9828     case ISD::SMIN:
9829     case ISD::SMAX:
9830     case ISD::FMAXNUM:
9831     case ISD::FMINNUM:
9832     case ISD::FMAXNUM_IEEE:
9833     case ISD::FMINNUM_IEEE: {
9834       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9835                                  Vec.getOperand(0), Idx);
9836       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9837                                  Vec.getOperand(1), Idx);
9838 
9839       DCI.AddToWorklist(Elt0.getNode());
9840       DCI.AddToWorklist(Elt1.getNode());
9841       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9842     }
9843     }
9844   }
9845 
9846   unsigned VecSize = VecVT.getSizeInBits();
9847   unsigned EltSize = EltVT.getSizeInBits();
9848 
9849   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9850   if (::shouldExpandVectorDynExt(N)) {
9851     SDLoc SL(N);
9852     SDValue Idx = N->getOperand(1);
9853     SDValue V;
9854     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9855       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9856       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9857       if (I == 0)
9858         V = Elt;
9859       else
9860         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9861     }
9862     return V;
9863   }
9864 
9865   if (!DCI.isBeforeLegalize())
9866     return SDValue();
9867 
9868   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9869   // elements. This exposes more load reduction opportunities by replacing
9870   // multiple small extract_vector_elements with a single 32-bit extract.
9871   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9872   if (isa<MemSDNode>(Vec) &&
9873       EltSize <= 16 &&
9874       EltVT.isByteSized() &&
9875       VecSize > 32 &&
9876       VecSize % 32 == 0 &&
9877       Idx) {
9878     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9879 
9880     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9881     unsigned EltIdx = BitIndex / 32;
9882     unsigned LeftoverBitIdx = BitIndex % 32;
9883     SDLoc SL(N);
9884 
9885     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9886     DCI.AddToWorklist(Cast.getNode());
9887 
9888     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9889                               DAG.getConstant(EltIdx, SL, MVT::i32));
9890     DCI.AddToWorklist(Elt.getNode());
9891     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9892                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9893     DCI.AddToWorklist(Srl.getNode());
9894 
9895     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9896     DCI.AddToWorklist(Trunc.getNode());
9897     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9898   }
9899 
9900   return SDValue();
9901 }
9902 
9903 SDValue
9904 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9905                                                 DAGCombinerInfo &DCI) const {
9906   SDValue Vec = N->getOperand(0);
9907   SDValue Idx = N->getOperand(2);
9908   EVT VecVT = Vec.getValueType();
9909   EVT EltVT = VecVT.getVectorElementType();
9910 
9911   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9912   // => BUILD_VECTOR n x select (e, const-idx)
9913   if (!::shouldExpandVectorDynExt(N))
9914     return SDValue();
9915 
9916   SelectionDAG &DAG = DCI.DAG;
9917   SDLoc SL(N);
9918   SDValue Ins = N->getOperand(1);
9919   EVT IdxVT = Idx.getValueType();
9920 
9921   SmallVector<SDValue, 16> Ops;
9922   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9923     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9924     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9925     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9926     Ops.push_back(V);
9927   }
9928 
9929   return DAG.getBuildVector(VecVT, SL, Ops);
9930 }
9931 
9932 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9933                                           const SDNode *N0,
9934                                           const SDNode *N1) const {
9935   EVT VT = N0->getValueType(0);
9936 
9937   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9938   // support denormals ever.
9939   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9940        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9941         getSubtarget()->hasMadF16())) &&
9942        isOperationLegal(ISD::FMAD, VT))
9943     return ISD::FMAD;
9944 
9945   const TargetOptions &Options = DAG.getTarget().Options;
9946   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9947        (N0->getFlags().hasAllowContract() &&
9948         N1->getFlags().hasAllowContract())) &&
9949       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9950     return ISD::FMA;
9951   }
9952 
9953   return 0;
9954 }
9955 
9956 // For a reassociatable opcode perform:
9957 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9958 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9959                                                SelectionDAG &DAG) const {
9960   EVT VT = N->getValueType(0);
9961   if (VT != MVT::i32 && VT != MVT::i64)
9962     return SDValue();
9963 
9964   unsigned Opc = N->getOpcode();
9965   SDValue Op0 = N->getOperand(0);
9966   SDValue Op1 = N->getOperand(1);
9967 
9968   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9969     return SDValue();
9970 
9971   if (Op0->isDivergent())
9972     std::swap(Op0, Op1);
9973 
9974   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9975     return SDValue();
9976 
9977   SDValue Op2 = Op1.getOperand(1);
9978   Op1 = Op1.getOperand(0);
9979   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9980     return SDValue();
9981 
9982   if (Op1->isDivergent())
9983     std::swap(Op1, Op2);
9984 
9985   // If either operand is constant this will conflict with
9986   // DAGCombiner::ReassociateOps().
9987   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9988       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9989     return SDValue();
9990 
9991   SDLoc SL(N);
9992   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9993   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9994 }
9995 
9996 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9997                            EVT VT,
9998                            SDValue N0, SDValue N1, SDValue N2,
9999                            bool Signed) {
10000   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10001   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10002   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10003   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10004 }
10005 
10006 SDValue SITargetLowering::performAddCombine(SDNode *N,
10007                                             DAGCombinerInfo &DCI) const {
10008   SelectionDAG &DAG = DCI.DAG;
10009   EVT VT = N->getValueType(0);
10010   SDLoc SL(N);
10011   SDValue LHS = N->getOperand(0);
10012   SDValue RHS = N->getOperand(1);
10013 
10014   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10015       && Subtarget->hasMad64_32() &&
10016       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10017       VT.getScalarSizeInBits() <= 64) {
10018     if (LHS.getOpcode() != ISD::MUL)
10019       std::swap(LHS, RHS);
10020 
10021     SDValue MulLHS = LHS.getOperand(0);
10022     SDValue MulRHS = LHS.getOperand(1);
10023     SDValue AddRHS = RHS;
10024 
10025     // TODO: Maybe restrict if SGPR inputs.
10026     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10027         numBitsUnsigned(MulRHS, DAG) <= 32) {
10028       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10029       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10030       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10031       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10032     }
10033 
10034     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10035       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10036       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10037       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10038       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10039     }
10040 
10041     return SDValue();
10042   }
10043 
10044   if (SDValue V = reassociateScalarOps(N, DAG)) {
10045     return V;
10046   }
10047 
10048   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10049     return SDValue();
10050 
10051   // add x, zext (setcc) => addcarry x, 0, setcc
10052   // add x, sext (setcc) => subcarry x, 0, setcc
10053   unsigned Opc = LHS.getOpcode();
10054   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10055       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10056     std::swap(RHS, LHS);
10057 
10058   Opc = RHS.getOpcode();
10059   switch (Opc) {
10060   default: break;
10061   case ISD::ZERO_EXTEND:
10062   case ISD::SIGN_EXTEND:
10063   case ISD::ANY_EXTEND: {
10064     auto Cond = RHS.getOperand(0);
10065     // If this won't be a real VOPC output, we would still need to insert an
10066     // extra instruction anyway.
10067     if (!isBoolSGPR(Cond))
10068       break;
10069     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10070     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10071     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10072     return DAG.getNode(Opc, SL, VTList, Args);
10073   }
10074   case ISD::ADDCARRY: {
10075     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10076     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10077     if (!C || C->getZExtValue() != 0) break;
10078     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10079     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10080   }
10081   }
10082   return SDValue();
10083 }
10084 
10085 SDValue SITargetLowering::performSubCombine(SDNode *N,
10086                                             DAGCombinerInfo &DCI) const {
10087   SelectionDAG &DAG = DCI.DAG;
10088   EVT VT = N->getValueType(0);
10089 
10090   if (VT != MVT::i32)
10091     return SDValue();
10092 
10093   SDLoc SL(N);
10094   SDValue LHS = N->getOperand(0);
10095   SDValue RHS = N->getOperand(1);
10096 
10097   // sub x, zext (setcc) => subcarry x, 0, setcc
10098   // sub x, sext (setcc) => addcarry x, 0, setcc
10099   unsigned Opc = RHS.getOpcode();
10100   switch (Opc) {
10101   default: break;
10102   case ISD::ZERO_EXTEND:
10103   case ISD::SIGN_EXTEND:
10104   case ISD::ANY_EXTEND: {
10105     auto Cond = RHS.getOperand(0);
10106     // If this won't be a real VOPC output, we would still need to insert an
10107     // extra instruction anyway.
10108     if (!isBoolSGPR(Cond))
10109       break;
10110     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10111     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10112     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10113     return DAG.getNode(Opc, SL, VTList, Args);
10114   }
10115   }
10116 
10117   if (LHS.getOpcode() == ISD::SUBCARRY) {
10118     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10119     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10120     if (!C || !C->isNullValue())
10121       return SDValue();
10122     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10123     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10124   }
10125   return SDValue();
10126 }
10127 
10128 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10129   DAGCombinerInfo &DCI) const {
10130 
10131   if (N->getValueType(0) != MVT::i32)
10132     return SDValue();
10133 
10134   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10135   if (!C || C->getZExtValue() != 0)
10136     return SDValue();
10137 
10138   SelectionDAG &DAG = DCI.DAG;
10139   SDValue LHS = N->getOperand(0);
10140 
10141   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10142   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10143   unsigned LHSOpc = LHS.getOpcode();
10144   unsigned Opc = N->getOpcode();
10145   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10146       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10147     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10148     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10149   }
10150   return SDValue();
10151 }
10152 
10153 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10154                                              DAGCombinerInfo &DCI) const {
10155   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10156     return SDValue();
10157 
10158   SelectionDAG &DAG = DCI.DAG;
10159   EVT VT = N->getValueType(0);
10160 
10161   SDLoc SL(N);
10162   SDValue LHS = N->getOperand(0);
10163   SDValue RHS = N->getOperand(1);
10164 
10165   // These should really be instruction patterns, but writing patterns with
10166   // source modiifiers is a pain.
10167 
10168   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10169   if (LHS.getOpcode() == ISD::FADD) {
10170     SDValue A = LHS.getOperand(0);
10171     if (A == LHS.getOperand(1)) {
10172       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10173       if (FusedOp != 0) {
10174         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10175         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10176       }
10177     }
10178   }
10179 
10180   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10181   if (RHS.getOpcode() == ISD::FADD) {
10182     SDValue A = RHS.getOperand(0);
10183     if (A == RHS.getOperand(1)) {
10184       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10185       if (FusedOp != 0) {
10186         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10187         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10188       }
10189     }
10190   }
10191 
10192   return SDValue();
10193 }
10194 
10195 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10196                                              DAGCombinerInfo &DCI) const {
10197   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10198     return SDValue();
10199 
10200   SelectionDAG &DAG = DCI.DAG;
10201   SDLoc SL(N);
10202   EVT VT = N->getValueType(0);
10203   assert(!VT.isVector());
10204 
10205   // Try to get the fneg to fold into the source modifier. This undoes generic
10206   // DAG combines and folds them into the mad.
10207   //
10208   // Only do this if we are not trying to support denormals. v_mad_f32 does
10209   // not support denormals ever.
10210   SDValue LHS = N->getOperand(0);
10211   SDValue RHS = N->getOperand(1);
10212   if (LHS.getOpcode() == ISD::FADD) {
10213     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10214     SDValue A = LHS.getOperand(0);
10215     if (A == LHS.getOperand(1)) {
10216       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10217       if (FusedOp != 0){
10218         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10219         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10220 
10221         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10222       }
10223     }
10224   }
10225 
10226   if (RHS.getOpcode() == ISD::FADD) {
10227     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10228 
10229     SDValue A = RHS.getOperand(0);
10230     if (A == RHS.getOperand(1)) {
10231       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10232       if (FusedOp != 0){
10233         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10234         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10235       }
10236     }
10237   }
10238 
10239   return SDValue();
10240 }
10241 
10242 SDValue SITargetLowering::performFMACombine(SDNode *N,
10243                                             DAGCombinerInfo &DCI) const {
10244   SelectionDAG &DAG = DCI.DAG;
10245   EVT VT = N->getValueType(0);
10246   SDLoc SL(N);
10247 
10248   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10249     return SDValue();
10250 
10251   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10252   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10253   SDValue Op1 = N->getOperand(0);
10254   SDValue Op2 = N->getOperand(1);
10255   SDValue FMA = N->getOperand(2);
10256 
10257   if (FMA.getOpcode() != ISD::FMA ||
10258       Op1.getOpcode() != ISD::FP_EXTEND ||
10259       Op2.getOpcode() != ISD::FP_EXTEND)
10260     return SDValue();
10261 
10262   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10263   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10264   // is sufficient to allow generaing fdot2.
10265   const TargetOptions &Options = DAG.getTarget().Options;
10266   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10267       (N->getFlags().hasAllowContract() &&
10268        FMA->getFlags().hasAllowContract())) {
10269     Op1 = Op1.getOperand(0);
10270     Op2 = Op2.getOperand(0);
10271     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10272         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10273       return SDValue();
10274 
10275     SDValue Vec1 = Op1.getOperand(0);
10276     SDValue Idx1 = Op1.getOperand(1);
10277     SDValue Vec2 = Op2.getOperand(0);
10278 
10279     SDValue FMAOp1 = FMA.getOperand(0);
10280     SDValue FMAOp2 = FMA.getOperand(1);
10281     SDValue FMAAcc = FMA.getOperand(2);
10282 
10283     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10284         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10285       return SDValue();
10286 
10287     FMAOp1 = FMAOp1.getOperand(0);
10288     FMAOp2 = FMAOp2.getOperand(0);
10289     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10290         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10291       return SDValue();
10292 
10293     SDValue Vec3 = FMAOp1.getOperand(0);
10294     SDValue Vec4 = FMAOp2.getOperand(0);
10295     SDValue Idx2 = FMAOp1.getOperand(1);
10296 
10297     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10298         // Idx1 and Idx2 cannot be the same.
10299         Idx1 == Idx2)
10300       return SDValue();
10301 
10302     if (Vec1 == Vec2 || Vec3 == Vec4)
10303       return SDValue();
10304 
10305     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10306       return SDValue();
10307 
10308     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10309         (Vec1 == Vec4 && Vec2 == Vec3)) {
10310       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10311                          DAG.getTargetConstant(0, SL, MVT::i1));
10312     }
10313   }
10314   return SDValue();
10315 }
10316 
10317 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10318                                               DAGCombinerInfo &DCI) const {
10319   SelectionDAG &DAG = DCI.DAG;
10320   SDLoc SL(N);
10321 
10322   SDValue LHS = N->getOperand(0);
10323   SDValue RHS = N->getOperand(1);
10324   EVT VT = LHS.getValueType();
10325   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10326 
10327   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10328   if (!CRHS) {
10329     CRHS = dyn_cast<ConstantSDNode>(LHS);
10330     if (CRHS) {
10331       std::swap(LHS, RHS);
10332       CC = getSetCCSwappedOperands(CC);
10333     }
10334   }
10335 
10336   if (CRHS) {
10337     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10338         isBoolSGPR(LHS.getOperand(0))) {
10339       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10340       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10341       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10342       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10343       if ((CRHS->isAllOnesValue() &&
10344            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10345           (CRHS->isNullValue() &&
10346            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10347         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10348                            DAG.getConstant(-1, SL, MVT::i1));
10349       if ((CRHS->isAllOnesValue() &&
10350            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10351           (CRHS->isNullValue() &&
10352            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10353         return LHS.getOperand(0);
10354     }
10355 
10356     uint64_t CRHSVal = CRHS->getZExtValue();
10357     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10358         LHS.getOpcode() == ISD::SELECT &&
10359         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10360         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10361         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10362         isBoolSGPR(LHS.getOperand(0))) {
10363       // Given CT != FT:
10364       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10365       // setcc (select cc, CT, CF), CF, ne => cc
10366       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10367       // setcc (select cc, CT, CF), CT, eq => cc
10368       uint64_t CT = LHS.getConstantOperandVal(1);
10369       uint64_t CF = LHS.getConstantOperandVal(2);
10370 
10371       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10372           (CT == CRHSVal && CC == ISD::SETNE))
10373         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10374                            DAG.getConstant(-1, SL, MVT::i1));
10375       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10376           (CT == CRHSVal && CC == ISD::SETEQ))
10377         return LHS.getOperand(0);
10378     }
10379   }
10380 
10381   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10382                                            VT != MVT::f16))
10383     return SDValue();
10384 
10385   // Match isinf/isfinite pattern
10386   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10387   // (fcmp one (fabs x), inf) -> (fp_class x,
10388   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10389   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10390     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10391     if (!CRHS)
10392       return SDValue();
10393 
10394     const APFloat &APF = CRHS->getValueAPF();
10395     if (APF.isInfinity() && !APF.isNegative()) {
10396       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10397                                  SIInstrFlags::N_INFINITY;
10398       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10399                                     SIInstrFlags::P_ZERO |
10400                                     SIInstrFlags::N_NORMAL |
10401                                     SIInstrFlags::P_NORMAL |
10402                                     SIInstrFlags::N_SUBNORMAL |
10403                                     SIInstrFlags::P_SUBNORMAL;
10404       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10405       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10406                          DAG.getConstant(Mask, SL, MVT::i32));
10407     }
10408   }
10409 
10410   return SDValue();
10411 }
10412 
10413 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10414                                                      DAGCombinerInfo &DCI) const {
10415   SelectionDAG &DAG = DCI.DAG;
10416   SDLoc SL(N);
10417   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10418 
10419   SDValue Src = N->getOperand(0);
10420   SDValue Shift = N->getOperand(0);
10421 
10422   // TODO: Extend type shouldn't matter (assuming legal types).
10423   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10424     Shift = Shift.getOperand(0);
10425 
10426   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10427     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10428     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10429     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10430     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10431     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10432     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10433       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10434                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10435 
10436       unsigned ShiftOffset = 8 * Offset;
10437       if (Shift.getOpcode() == ISD::SHL)
10438         ShiftOffset -= C->getZExtValue();
10439       else
10440         ShiftOffset += C->getZExtValue();
10441 
10442       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10443         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10444                            MVT::f32, Shift);
10445       }
10446     }
10447   }
10448 
10449   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10450   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10451   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10452     // We simplified Src. If this node is not dead, visit it again so it is
10453     // folded properly.
10454     if (N->getOpcode() != ISD::DELETED_NODE)
10455       DCI.AddToWorklist(N);
10456     return SDValue(N, 0);
10457   }
10458 
10459   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10460   if (SDValue DemandedSrc =
10461           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10462     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10463 
10464   return SDValue();
10465 }
10466 
10467 SDValue SITargetLowering::performClampCombine(SDNode *N,
10468                                               DAGCombinerInfo &DCI) const {
10469   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10470   if (!CSrc)
10471     return SDValue();
10472 
10473   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10474   const APFloat &F = CSrc->getValueAPF();
10475   APFloat Zero = APFloat::getZero(F.getSemantics());
10476   if (F < Zero ||
10477       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10478     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10479   }
10480 
10481   APFloat One(F.getSemantics(), "1.0");
10482   if (F > One)
10483     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10484 
10485   return SDValue(CSrc, 0);
10486 }
10487 
10488 
10489 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10490                                             DAGCombinerInfo &DCI) const {
10491   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10492     return SDValue();
10493   switch (N->getOpcode()) {
10494   default:
10495     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10496   case ISD::ADD:
10497     return performAddCombine(N, DCI);
10498   case ISD::SUB:
10499     return performSubCombine(N, DCI);
10500   case ISD::ADDCARRY:
10501   case ISD::SUBCARRY:
10502     return performAddCarrySubCarryCombine(N, DCI);
10503   case ISD::FADD:
10504     return performFAddCombine(N, DCI);
10505   case ISD::FSUB:
10506     return performFSubCombine(N, DCI);
10507   case ISD::SETCC:
10508     return performSetCCCombine(N, DCI);
10509   case ISD::FMAXNUM:
10510   case ISD::FMINNUM:
10511   case ISD::FMAXNUM_IEEE:
10512   case ISD::FMINNUM_IEEE:
10513   case ISD::SMAX:
10514   case ISD::SMIN:
10515   case ISD::UMAX:
10516   case ISD::UMIN:
10517   case AMDGPUISD::FMIN_LEGACY:
10518   case AMDGPUISD::FMAX_LEGACY:
10519     return performMinMaxCombine(N, DCI);
10520   case ISD::FMA:
10521     return performFMACombine(N, DCI);
10522   case ISD::LOAD: {
10523     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10524       return Widended;
10525     LLVM_FALLTHROUGH;
10526   }
10527   case ISD::STORE:
10528   case ISD::ATOMIC_LOAD:
10529   case ISD::ATOMIC_STORE:
10530   case ISD::ATOMIC_CMP_SWAP:
10531   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10532   case ISD::ATOMIC_SWAP:
10533   case ISD::ATOMIC_LOAD_ADD:
10534   case ISD::ATOMIC_LOAD_SUB:
10535   case ISD::ATOMIC_LOAD_AND:
10536   case ISD::ATOMIC_LOAD_OR:
10537   case ISD::ATOMIC_LOAD_XOR:
10538   case ISD::ATOMIC_LOAD_NAND:
10539   case ISD::ATOMIC_LOAD_MIN:
10540   case ISD::ATOMIC_LOAD_MAX:
10541   case ISD::ATOMIC_LOAD_UMIN:
10542   case ISD::ATOMIC_LOAD_UMAX:
10543   case ISD::ATOMIC_LOAD_FADD:
10544   case AMDGPUISD::ATOMIC_INC:
10545   case AMDGPUISD::ATOMIC_DEC:
10546   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10547   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10548     if (DCI.isBeforeLegalize())
10549       break;
10550     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10551   case ISD::AND:
10552     return performAndCombine(N, DCI);
10553   case ISD::OR:
10554     return performOrCombine(N, DCI);
10555   case ISD::XOR:
10556     return performXorCombine(N, DCI);
10557   case ISD::ZERO_EXTEND:
10558     return performZeroExtendCombine(N, DCI);
10559   case ISD::SIGN_EXTEND_INREG:
10560     return performSignExtendInRegCombine(N , DCI);
10561   case AMDGPUISD::FP_CLASS:
10562     return performClassCombine(N, DCI);
10563   case ISD::FCANONICALIZE:
10564     return performFCanonicalizeCombine(N, DCI);
10565   case AMDGPUISD::RCP:
10566     return performRcpCombine(N, DCI);
10567   case AMDGPUISD::FRACT:
10568   case AMDGPUISD::RSQ:
10569   case AMDGPUISD::RCP_LEGACY:
10570   case AMDGPUISD::RCP_IFLAG:
10571   case AMDGPUISD::RSQ_CLAMP:
10572   case AMDGPUISD::LDEXP: {
10573     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10574     SDValue Src = N->getOperand(0);
10575     if (Src.isUndef())
10576       return Src;
10577     break;
10578   }
10579   case ISD::SINT_TO_FP:
10580   case ISD::UINT_TO_FP:
10581     return performUCharToFloatCombine(N, DCI);
10582   case AMDGPUISD::CVT_F32_UBYTE0:
10583   case AMDGPUISD::CVT_F32_UBYTE1:
10584   case AMDGPUISD::CVT_F32_UBYTE2:
10585   case AMDGPUISD::CVT_F32_UBYTE3:
10586     return performCvtF32UByteNCombine(N, DCI);
10587   case AMDGPUISD::FMED3:
10588     return performFMed3Combine(N, DCI);
10589   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10590     return performCvtPkRTZCombine(N, DCI);
10591   case AMDGPUISD::CLAMP:
10592     return performClampCombine(N, DCI);
10593   case ISD::SCALAR_TO_VECTOR: {
10594     SelectionDAG &DAG = DCI.DAG;
10595     EVT VT = N->getValueType(0);
10596 
10597     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10598     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10599       SDLoc SL(N);
10600       SDValue Src = N->getOperand(0);
10601       EVT EltVT = Src.getValueType();
10602       if (EltVT == MVT::f16)
10603         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10604 
10605       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10606       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10607     }
10608 
10609     break;
10610   }
10611   case ISD::EXTRACT_VECTOR_ELT:
10612     return performExtractVectorEltCombine(N, DCI);
10613   case ISD::INSERT_VECTOR_ELT:
10614     return performInsertVectorEltCombine(N, DCI);
10615   }
10616   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10617 }
10618 
10619 /// Helper function for adjustWritemask
10620 static unsigned SubIdx2Lane(unsigned Idx) {
10621   switch (Idx) {
10622   default: return 0;
10623   case AMDGPU::sub0: return 0;
10624   case AMDGPU::sub1: return 1;
10625   case AMDGPU::sub2: return 2;
10626   case AMDGPU::sub3: return 3;
10627   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10628   }
10629 }
10630 
10631 /// Adjust the writemask of MIMG instructions
10632 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10633                                           SelectionDAG &DAG) const {
10634   unsigned Opcode = Node->getMachineOpcode();
10635 
10636   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10637   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10638   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10639     return Node; // not implemented for D16
10640 
10641   SDNode *Users[5] = { nullptr };
10642   unsigned Lane = 0;
10643   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10644   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10645   unsigned NewDmask = 0;
10646   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10647   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10648   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10649                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10650   unsigned TFCLane = 0;
10651   bool HasChain = Node->getNumValues() > 1;
10652 
10653   if (OldDmask == 0) {
10654     // These are folded out, but on the chance it happens don't assert.
10655     return Node;
10656   }
10657 
10658   unsigned OldBitsSet = countPopulation(OldDmask);
10659   // Work out which is the TFE/LWE lane if that is enabled.
10660   if (UsesTFC) {
10661     TFCLane = OldBitsSet;
10662   }
10663 
10664   // Try to figure out the used register components
10665   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10666        I != E; ++I) {
10667 
10668     // Don't look at users of the chain.
10669     if (I.getUse().getResNo() != 0)
10670       continue;
10671 
10672     // Abort if we can't understand the usage
10673     if (!I->isMachineOpcode() ||
10674         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10675       return Node;
10676 
10677     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10678     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10679     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10680     // set, etc.
10681     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10682 
10683     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10684     if (UsesTFC && Lane == TFCLane) {
10685       Users[Lane] = *I;
10686     } else {
10687       // Set which texture component corresponds to the lane.
10688       unsigned Comp;
10689       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10690         Comp = countTrailingZeros(Dmask);
10691         Dmask &= ~(1 << Comp);
10692       }
10693 
10694       // Abort if we have more than one user per component.
10695       if (Users[Lane])
10696         return Node;
10697 
10698       Users[Lane] = *I;
10699       NewDmask |= 1 << Comp;
10700     }
10701   }
10702 
10703   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10704   bool NoChannels = !NewDmask;
10705   if (NoChannels) {
10706     if (!UsesTFC) {
10707       // No uses of the result and not using TFC. Then do nothing.
10708       return Node;
10709     }
10710     // If the original dmask has one channel - then nothing to do
10711     if (OldBitsSet == 1)
10712       return Node;
10713     // Use an arbitrary dmask - required for the instruction to work
10714     NewDmask = 1;
10715   }
10716   // Abort if there's no change
10717   if (NewDmask == OldDmask)
10718     return Node;
10719 
10720   unsigned BitsSet = countPopulation(NewDmask);
10721 
10722   // Check for TFE or LWE - increase the number of channels by one to account
10723   // for the extra return value
10724   // This will need adjustment for D16 if this is also included in
10725   // adjustWriteMask (this function) but at present D16 are excluded.
10726   unsigned NewChannels = BitsSet + UsesTFC;
10727 
10728   int NewOpcode =
10729       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10730   assert(NewOpcode != -1 &&
10731          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10732          "failed to find equivalent MIMG op");
10733 
10734   // Adjust the writemask in the node
10735   SmallVector<SDValue, 12> Ops;
10736   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10737   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10738   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10739 
10740   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10741 
10742   MVT ResultVT = NewChannels == 1 ?
10743     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10744                            NewChannels == 5 ? 8 : NewChannels);
10745   SDVTList NewVTList = HasChain ?
10746     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10747 
10748 
10749   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10750                                               NewVTList, Ops);
10751 
10752   if (HasChain) {
10753     // Update chain.
10754     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10755     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10756   }
10757 
10758   if (NewChannels == 1) {
10759     assert(Node->hasNUsesOfValue(1, 0));
10760     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10761                                       SDLoc(Node), Users[Lane]->getValueType(0),
10762                                       SDValue(NewNode, 0));
10763     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10764     return nullptr;
10765   }
10766 
10767   // Update the users of the node with the new indices
10768   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10769     SDNode *User = Users[i];
10770     if (!User) {
10771       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10772       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10773       if (i || !NoChannels)
10774         continue;
10775     } else {
10776       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10777       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10778     }
10779 
10780     switch (Idx) {
10781     default: break;
10782     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10783     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10784     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10785     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10786     }
10787   }
10788 
10789   DAG.RemoveDeadNode(Node);
10790   return nullptr;
10791 }
10792 
10793 static bool isFrameIndexOp(SDValue Op) {
10794   if (Op.getOpcode() == ISD::AssertZext)
10795     Op = Op.getOperand(0);
10796 
10797   return isa<FrameIndexSDNode>(Op);
10798 }
10799 
10800 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10801 /// with frame index operands.
10802 /// LLVM assumes that inputs are to these instructions are registers.
10803 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10804                                                         SelectionDAG &DAG) const {
10805   if (Node->getOpcode() == ISD::CopyToReg) {
10806     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10807     SDValue SrcVal = Node->getOperand(2);
10808 
10809     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10810     // to try understanding copies to physical registers.
10811     if (SrcVal.getValueType() == MVT::i1 &&
10812         Register::isPhysicalRegister(DestReg->getReg())) {
10813       SDLoc SL(Node);
10814       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10815       SDValue VReg = DAG.getRegister(
10816         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10817 
10818       SDNode *Glued = Node->getGluedNode();
10819       SDValue ToVReg
10820         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10821                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10822       SDValue ToResultReg
10823         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10824                            VReg, ToVReg.getValue(1));
10825       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10826       DAG.RemoveDeadNode(Node);
10827       return ToResultReg.getNode();
10828     }
10829   }
10830 
10831   SmallVector<SDValue, 8> Ops;
10832   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10833     if (!isFrameIndexOp(Node->getOperand(i))) {
10834       Ops.push_back(Node->getOperand(i));
10835       continue;
10836     }
10837 
10838     SDLoc DL(Node);
10839     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10840                                      Node->getOperand(i).getValueType(),
10841                                      Node->getOperand(i)), 0));
10842   }
10843 
10844   return DAG.UpdateNodeOperands(Node, Ops);
10845 }
10846 
10847 /// Fold the instructions after selecting them.
10848 /// Returns null if users were already updated.
10849 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10850                                           SelectionDAG &DAG) const {
10851   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10852   unsigned Opcode = Node->getMachineOpcode();
10853 
10854   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10855       !TII->isGather4(Opcode)) {
10856     return adjustWritemask(Node, DAG);
10857   }
10858 
10859   if (Opcode == AMDGPU::INSERT_SUBREG ||
10860       Opcode == AMDGPU::REG_SEQUENCE) {
10861     legalizeTargetIndependentNode(Node, DAG);
10862     return Node;
10863   }
10864 
10865   switch (Opcode) {
10866   case AMDGPU::V_DIV_SCALE_F32:
10867   case AMDGPU::V_DIV_SCALE_F64: {
10868     // Satisfy the operand register constraint when one of the inputs is
10869     // undefined. Ordinarily each undef value will have its own implicit_def of
10870     // a vreg, so force these to use a single register.
10871     SDValue Src0 = Node->getOperand(0);
10872     SDValue Src1 = Node->getOperand(1);
10873     SDValue Src2 = Node->getOperand(2);
10874 
10875     if ((Src0.isMachineOpcode() &&
10876          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10877         (Src0 == Src1 || Src0 == Src2))
10878       break;
10879 
10880     MVT VT = Src0.getValueType().getSimpleVT();
10881     const TargetRegisterClass *RC =
10882         getRegClassFor(VT, Src0.getNode()->isDivergent());
10883 
10884     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10885     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10886 
10887     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10888                                       UndefReg, Src0, SDValue());
10889 
10890     // src0 must be the same register as src1 or src2, even if the value is
10891     // undefined, so make sure we don't violate this constraint.
10892     if (Src0.isMachineOpcode() &&
10893         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10894       if (Src1.isMachineOpcode() &&
10895           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10896         Src0 = Src1;
10897       else if (Src2.isMachineOpcode() &&
10898                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10899         Src0 = Src2;
10900       else {
10901         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10902         Src0 = UndefReg;
10903         Src1 = UndefReg;
10904       }
10905     } else
10906       break;
10907 
10908     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10909     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10910       Ops.push_back(Node->getOperand(I));
10911 
10912     Ops.push_back(ImpDef.getValue(1));
10913     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10914   }
10915   default:
10916     break;
10917   }
10918 
10919   return Node;
10920 }
10921 
10922 /// Assign the register class depending on the number of
10923 /// bits set in the writemask
10924 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10925                                                      SDNode *Node) const {
10926   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10927 
10928   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10929 
10930   if (TII->isVOP3(MI.getOpcode())) {
10931     // Make sure constant bus requirements are respected.
10932     TII->legalizeOperandsVOP3(MRI, MI);
10933 
10934     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10935     // This saves a chain-copy of registers and better ballance register
10936     // use between vgpr and agpr as agpr tuples tend to be big.
10937     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10938       unsigned Opc = MI.getOpcode();
10939       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10940       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10941                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10942         if (I == -1)
10943           break;
10944         MachineOperand &Op = MI.getOperand(I);
10945         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10946              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10947             !Register::isVirtualRegister(Op.getReg()) ||
10948             !TRI->isAGPR(MRI, Op.getReg()))
10949           continue;
10950         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10951         if (!Src || !Src->isCopy() ||
10952             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10953           continue;
10954         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10955         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10956         // All uses of agpr64 and agpr32 can also accept vgpr except for
10957         // v_accvgpr_read, but we do not produce agpr reads during selection,
10958         // so no use checks are needed.
10959         MRI.setRegClass(Op.getReg(), NewRC);
10960       }
10961     }
10962 
10963     return;
10964   }
10965 
10966   // Replace unused atomics with the no return version.
10967   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10968   if (NoRetAtomicOp != -1) {
10969     if (!Node->hasAnyUseOfValue(0)) {
10970       MI.setDesc(TII->get(NoRetAtomicOp));
10971       MI.RemoveOperand(0);
10972       return;
10973     }
10974 
10975     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10976     // instruction, because the return type of these instructions is a vec2 of
10977     // the memory type, so it can be tied to the input operand.
10978     // This means these instructions always have a use, so we need to add a
10979     // special case to check if the atomic has only one extract_subreg use,
10980     // which itself has no uses.
10981     if ((Node->hasNUsesOfValue(1, 0) &&
10982          Node->use_begin()->isMachineOpcode() &&
10983          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10984          !Node->use_begin()->hasAnyUseOfValue(0))) {
10985       Register Def = MI.getOperand(0).getReg();
10986 
10987       // Change this into a noret atomic.
10988       MI.setDesc(TII->get(NoRetAtomicOp));
10989       MI.RemoveOperand(0);
10990 
10991       // If we only remove the def operand from the atomic instruction, the
10992       // extract_subreg will be left with a use of a vreg without a def.
10993       // So we need to insert an implicit_def to avoid machine verifier
10994       // errors.
10995       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10996               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10997     }
10998     return;
10999   }
11000 }
11001 
11002 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11003                               uint64_t Val) {
11004   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11005   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11006 }
11007 
11008 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11009                                                 const SDLoc &DL,
11010                                                 SDValue Ptr) const {
11011   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11012 
11013   // Build the half of the subregister with the constants before building the
11014   // full 128-bit register. If we are building multiple resource descriptors,
11015   // this will allow CSEing of the 2-component register.
11016   const SDValue Ops0[] = {
11017     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11018     buildSMovImm32(DAG, DL, 0),
11019     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11020     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11021     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11022   };
11023 
11024   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11025                                                 MVT::v2i32, Ops0), 0);
11026 
11027   // Combine the constants and the pointer.
11028   const SDValue Ops1[] = {
11029     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11030     Ptr,
11031     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11032     SubRegHi,
11033     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11034   };
11035 
11036   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11037 }
11038 
11039 /// Return a resource descriptor with the 'Add TID' bit enabled
11040 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11041 ///        of the resource descriptor) to create an offset, which is added to
11042 ///        the resource pointer.
11043 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11044                                            SDValue Ptr, uint32_t RsrcDword1,
11045                                            uint64_t RsrcDword2And3) const {
11046   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11047   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11048   if (RsrcDword1) {
11049     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11050                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11051                     0);
11052   }
11053 
11054   SDValue DataLo = buildSMovImm32(DAG, DL,
11055                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11056   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11057 
11058   const SDValue Ops[] = {
11059     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11060     PtrLo,
11061     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11062     PtrHi,
11063     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11064     DataLo,
11065     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11066     DataHi,
11067     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11068   };
11069 
11070   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11071 }
11072 
11073 //===----------------------------------------------------------------------===//
11074 //                         SI Inline Assembly Support
11075 //===----------------------------------------------------------------------===//
11076 
11077 std::pair<unsigned, const TargetRegisterClass *>
11078 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11079                                                StringRef Constraint,
11080                                                MVT VT) const {
11081   const TargetRegisterClass *RC = nullptr;
11082   if (Constraint.size() == 1) {
11083     const unsigned BitWidth = VT.getSizeInBits();
11084     switch (Constraint[0]) {
11085     default:
11086       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11087     case 's':
11088     case 'r':
11089       switch (BitWidth) {
11090       case 16:
11091         RC = &AMDGPU::SReg_32RegClass;
11092         break;
11093       case 64:
11094         RC = &AMDGPU::SGPR_64RegClass;
11095         break;
11096       default:
11097         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11098         if (!RC)
11099           return std::make_pair(0U, nullptr);
11100         break;
11101       }
11102       break;
11103     case 'v':
11104       switch (BitWidth) {
11105       case 16:
11106         RC = &AMDGPU::VGPR_32RegClass;
11107         break;
11108       default:
11109         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11110         if (!RC)
11111           return std::make_pair(0U, nullptr);
11112         break;
11113       }
11114       break;
11115     case 'a':
11116       if (!Subtarget->hasMAIInsts())
11117         break;
11118       switch (BitWidth) {
11119       case 16:
11120         RC = &AMDGPU::AGPR_32RegClass;
11121         break;
11122       default:
11123         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11124         if (!RC)
11125           return std::make_pair(0U, nullptr);
11126         break;
11127       }
11128       break;
11129     }
11130     // We actually support i128, i16 and f16 as inline parameters
11131     // even if they are not reported as legal
11132     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11133                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11134       return std::make_pair(0U, RC);
11135   }
11136 
11137   if (Constraint.size() > 1) {
11138     if (Constraint[1] == 'v') {
11139       RC = &AMDGPU::VGPR_32RegClass;
11140     } else if (Constraint[1] == 's') {
11141       RC = &AMDGPU::SGPR_32RegClass;
11142     } else if (Constraint[1] == 'a') {
11143       RC = &AMDGPU::AGPR_32RegClass;
11144     }
11145 
11146     if (RC) {
11147       uint32_t Idx;
11148       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11149       if (!Failed && Idx < RC->getNumRegs())
11150         return std::make_pair(RC->getRegister(Idx), RC);
11151     }
11152   }
11153 
11154   // FIXME: Returns VS_32 for physical SGPR constraints
11155   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11156 }
11157 
11158 SITargetLowering::ConstraintType
11159 SITargetLowering::getConstraintType(StringRef Constraint) const {
11160   if (Constraint.size() == 1) {
11161     switch (Constraint[0]) {
11162     default: break;
11163     case 's':
11164     case 'v':
11165     case 'a':
11166       return C_RegisterClass;
11167     case 'A':
11168       return C_Other;
11169     }
11170   }
11171   return TargetLowering::getConstraintType(Constraint);
11172 }
11173 
11174 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11175                                                     std::string &Constraint,
11176                                                     std::vector<SDValue> &Ops,
11177                                                     SelectionDAG &DAG) const {
11178   if (Constraint.length() == 1 && Constraint[0] == 'A') {
11179     LowerAsmOperandForConstraintA(Op, Ops, DAG);
11180   } else {
11181     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11182   }
11183 }
11184 
11185 void SITargetLowering::LowerAsmOperandForConstraintA(SDValue Op,
11186                                                      std::vector<SDValue> &Ops,
11187                                                      SelectionDAG &DAG) const {
11188   unsigned Size = Op.getScalarValueSizeInBits();
11189   if (Size > 64)
11190     return;
11191 
11192   uint64_t Val;
11193   bool IsConst = false;
11194   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11195     Val = C->getSExtValue();
11196     IsConst = true;
11197   } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11198     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11199     IsConst = true;
11200   } else if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11201     if (Size != 16 || Op.getNumOperands() != 2)
11202       return;
11203     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11204       return;
11205     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11206       Val = C->getSExtValue();
11207       IsConst = true;
11208     } else if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11209       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11210       IsConst = true;
11211     }
11212   }
11213 
11214   if (IsConst) {
11215     bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11216     if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11217         (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11218         (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11219       // Clear unused bits of fp constants
11220       if (!AMDGPU::isInlinableIntLiteral(Val)) {
11221         unsigned UnusedBits = 64 - Size;
11222         Val = (Val << UnusedBits) >> UnusedBits;
11223       }
11224       auto Res = DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64);
11225       Ops.push_back(Res);
11226     }
11227   }
11228 }
11229 
11230 // Figure out which registers should be reserved for stack access. Only after
11231 // the function is legalized do we know all of the non-spill stack objects or if
11232 // calls are present.
11233 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11234   MachineRegisterInfo &MRI = MF.getRegInfo();
11235   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11236   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11237   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11238 
11239   if (Info->isEntryFunction()) {
11240     // Callable functions have fixed registers used for stack access.
11241     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11242   }
11243 
11244   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11245                              Info->getStackPtrOffsetReg()));
11246   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11247     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11248 
11249   // We need to worry about replacing the default register with itself in case
11250   // of MIR testcases missing the MFI.
11251   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11252     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11253 
11254   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11255     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11256 
11257   Info->limitOccupancy(MF);
11258 
11259   if (ST.isWave32() && !MF.empty()) {
11260     // Add VCC_HI def because many instructions marked as imp-use VCC where
11261     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11262     // having a use of undef.
11263 
11264     const SIInstrInfo *TII = ST.getInstrInfo();
11265     DebugLoc DL;
11266 
11267     MachineBasicBlock &MBB = MF.front();
11268     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11269     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11270 
11271     for (auto &MBB : MF) {
11272       for (auto &MI : MBB) {
11273         TII->fixImplicitOperands(MI);
11274       }
11275     }
11276   }
11277 
11278   TargetLoweringBase::finalizeLowering(MF);
11279 
11280   // Allocate a VGPR for future SGPR Spill if
11281   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11282   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11283   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11284       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11285     Info->reserveVGPRforSGPRSpills(MF);
11286 }
11287 
11288 void SITargetLowering::computeKnownBitsForFrameIndex(
11289   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11290   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11291 
11292   // Set the high bits to zero based on the maximum allowed scratch size per
11293   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11294   // calculation won't overflow, so assume the sign bit is never set.
11295   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11296 }
11297 
11298 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11299   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11300   const Align CacheLineAlign = Align(64);
11301 
11302   // Pre-GFX10 target did not benefit from loop alignment
11303   if (!ML || DisableLoopAlignment ||
11304       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11305       getSubtarget()->hasInstFwdPrefetchBug())
11306     return PrefAlign;
11307 
11308   // On GFX10 I$ is 4 x 64 bytes cache lines.
11309   // By default prefetcher keeps one cache line behind and reads two ahead.
11310   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11311   // behind and one ahead.
11312   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11313   // If loop fits 64 bytes it always spans no more than two cache lines and
11314   // does not need an alignment.
11315   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11316   // Else if loop is less or equal 192 bytes we need two lines behind.
11317 
11318   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11319   const MachineBasicBlock *Header = ML->getHeader();
11320   if (Header->getAlignment() != PrefAlign)
11321     return Header->getAlignment(); // Already processed.
11322 
11323   unsigned LoopSize = 0;
11324   for (const MachineBasicBlock *MBB : ML->blocks()) {
11325     // If inner loop block is aligned assume in average half of the alignment
11326     // size to be added as nops.
11327     if (MBB != Header)
11328       LoopSize += MBB->getAlignment().value() / 2;
11329 
11330     for (const MachineInstr &MI : *MBB) {
11331       LoopSize += TII->getInstSizeInBytes(MI);
11332       if (LoopSize > 192)
11333         return PrefAlign;
11334     }
11335   }
11336 
11337   if (LoopSize <= 64)
11338     return PrefAlign;
11339 
11340   if (LoopSize <= 128)
11341     return CacheLineAlign;
11342 
11343   // If any of parent loops is surrounded by prefetch instructions do not
11344   // insert new for inner loop, which would reset parent's settings.
11345   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11346     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11347       auto I = Exit->getFirstNonDebugInstr();
11348       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11349         return CacheLineAlign;
11350     }
11351   }
11352 
11353   MachineBasicBlock *Pre = ML->getLoopPreheader();
11354   MachineBasicBlock *Exit = ML->getExitBlock();
11355 
11356   if (Pre && Exit) {
11357     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11358             TII->get(AMDGPU::S_INST_PREFETCH))
11359       .addImm(1); // prefetch 2 lines behind PC
11360 
11361     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11362             TII->get(AMDGPU::S_INST_PREFETCH))
11363       .addImm(2); // prefetch 1 line behind PC
11364   }
11365 
11366   return CacheLineAlign;
11367 }
11368 
11369 LLVM_ATTRIBUTE_UNUSED
11370 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11371   assert(N->getOpcode() == ISD::CopyFromReg);
11372   do {
11373     // Follow the chain until we find an INLINEASM node.
11374     N = N->getOperand(0).getNode();
11375     if (N->getOpcode() == ISD::INLINEASM ||
11376         N->getOpcode() == ISD::INLINEASM_BR)
11377       return true;
11378   } while (N->getOpcode() == ISD::CopyFromReg);
11379   return false;
11380 }
11381 
11382 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11383   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11384 {
11385   switch (N->getOpcode()) {
11386     case ISD::CopyFromReg:
11387     {
11388       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11389       const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11390       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11391       Register Reg = R->getReg();
11392 
11393       // FIXME: Why does this need to consider isLiveIn?
11394       if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11395         return !TRI->isSGPRReg(MRI, Reg);
11396 
11397       if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11398         return KDA->isDivergent(V);
11399 
11400       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11401       return !TRI->isSGPRReg(MRI, Reg);
11402     }
11403     break;
11404     case ISD::LOAD: {
11405       const LoadSDNode *L = cast<LoadSDNode>(N);
11406       unsigned AS = L->getAddressSpace();
11407       // A flat load may access private memory.
11408       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11409     } break;
11410     case ISD::CALLSEQ_END:
11411     return true;
11412     break;
11413     case ISD::INTRINSIC_WO_CHAIN:
11414     {
11415 
11416     }
11417       return AMDGPU::isIntrinsicSourceOfDivergence(
11418       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11419     case ISD::INTRINSIC_W_CHAIN:
11420       return AMDGPU::isIntrinsicSourceOfDivergence(
11421       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11422   }
11423   return false;
11424 }
11425 
11426 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11427                                                EVT VT) const {
11428   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11429   case MVT::f32:
11430     return hasFP32Denormals(DAG.getMachineFunction());
11431   case MVT::f64:
11432   case MVT::f16:
11433     return hasFP64FP16Denormals(DAG.getMachineFunction());
11434   default:
11435     return false;
11436   }
11437 }
11438 
11439 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11440                                                     const SelectionDAG &DAG,
11441                                                     bool SNaN,
11442                                                     unsigned Depth) const {
11443   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11444     const MachineFunction &MF = DAG.getMachineFunction();
11445     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11446 
11447     if (Info->getMode().DX10Clamp)
11448       return true; // Clamped to 0.
11449     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11450   }
11451 
11452   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11453                                                             SNaN, Depth);
11454 }
11455 
11456 TargetLowering::AtomicExpansionKind
11457 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11458   switch (RMW->getOperation()) {
11459   case AtomicRMWInst::FAdd: {
11460     Type *Ty = RMW->getType();
11461 
11462     // We don't have a way to support 16-bit atomics now, so just leave them
11463     // as-is.
11464     if (Ty->isHalfTy())
11465       return AtomicExpansionKind::None;
11466 
11467     if (!Ty->isFloatTy())
11468       return AtomicExpansionKind::CmpXChg;
11469 
11470     // TODO: Do have these for flat. Older targets also had them for buffers.
11471     unsigned AS = RMW->getPointerAddressSpace();
11472 
11473     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11474       return RMW->use_empty() ? AtomicExpansionKind::None :
11475                                 AtomicExpansionKind::CmpXChg;
11476     }
11477 
11478     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11479       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11480   }
11481   default:
11482     break;
11483   }
11484 
11485   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11486 }
11487 
11488 const TargetRegisterClass *
11489 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11490   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11491   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11492   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11493     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11494                                                : &AMDGPU::SReg_32RegClass;
11495   if (!TRI->isSGPRClass(RC) && !isDivergent)
11496     return TRI->getEquivalentSGPRClass(RC);
11497   else if (TRI->isSGPRClass(RC) && isDivergent)
11498     return TRI->getEquivalentVGPRClass(RC);
11499 
11500   return RC;
11501 }
11502 
11503 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11504 // uniform values (as produced by the mask results of control flow intrinsics)
11505 // used outside of divergent blocks. The phi users need to also be treated as
11506 // always uniform.
11507 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11508                       unsigned WaveSize) {
11509   // FIXME: We asssume we never cast the mask results of a control flow
11510   // intrinsic.
11511   // Early exit if the type won't be consistent as a compile time hack.
11512   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11513   if (!IT || IT->getBitWidth() != WaveSize)
11514     return false;
11515 
11516   if (!isa<Instruction>(V))
11517     return false;
11518   if (!Visited.insert(V).second)
11519     return false;
11520   bool Result = false;
11521   for (auto U : V->users()) {
11522     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11523       if (V == U->getOperand(1)) {
11524         switch (Intrinsic->getIntrinsicID()) {
11525         default:
11526           Result = false;
11527           break;
11528         case Intrinsic::amdgcn_if_break:
11529         case Intrinsic::amdgcn_if:
11530         case Intrinsic::amdgcn_else:
11531           Result = true;
11532           break;
11533         }
11534       }
11535       if (V == U->getOperand(0)) {
11536         switch (Intrinsic->getIntrinsicID()) {
11537         default:
11538           Result = false;
11539           break;
11540         case Intrinsic::amdgcn_end_cf:
11541         case Intrinsic::amdgcn_loop:
11542           Result = true;
11543           break;
11544         }
11545       }
11546     } else {
11547       Result = hasCFUser(U, Visited, WaveSize);
11548     }
11549     if (Result)
11550       break;
11551   }
11552   return Result;
11553 }
11554 
11555 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11556                                                const Value *V) const {
11557   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11558     if (CI->isInlineAsm()) {
11559       // FIXME: This cannot give a correct answer. This should only trigger in
11560       // the case where inline asm returns mixed SGPR and VGPR results, used
11561       // outside the defining block. We don't have a specific result to
11562       // consider, so this assumes if any value is SGPR, the overall register
11563       // also needs to be SGPR.
11564       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11565       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11566           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11567       for (auto &TC : TargetConstraints) {
11568         if (TC.Type == InlineAsm::isOutput) {
11569           ComputeConstraintToUse(TC, SDValue());
11570           unsigned AssignedReg;
11571           const TargetRegisterClass *RC;
11572           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11573               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11574           if (RC) {
11575             MachineRegisterInfo &MRI = MF.getRegInfo();
11576             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11577               return true;
11578             else if (SIRI->isSGPRClass(RC))
11579               return true;
11580           }
11581         }
11582       }
11583     }
11584   }
11585   SmallPtrSet<const Value *, 16> Visited;
11586   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11587 }
11588