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/GlobalISel/GISelKnownBits.h"
39 #include "llvm/CodeGen/MachineBasicBlock.h"
40 #include "llvm/CodeGen/MachineFrameInfo.h"
41 #include "llvm/CodeGen/MachineFunction.h"
42 #include "llvm/CodeGen/MachineInstr.h"
43 #include "llvm/CodeGen/MachineInstrBuilder.h"
44 #include "llvm/CodeGen/MachineLoopInfo.h"
45 #include "llvm/CodeGen/MachineMemOperand.h"
46 #include "llvm/CodeGen/MachineModuleInfo.h"
47 #include "llvm/CodeGen/MachineOperand.h"
48 #include "llvm/CodeGen/MachineRegisterInfo.h"
49 #include "llvm/CodeGen/SelectionDAG.h"
50 #include "llvm/CodeGen/SelectionDAGNodes.h"
51 #include "llvm/CodeGen/TargetCallingConv.h"
52 #include "llvm/CodeGen/TargetRegisterInfo.h"
53 #include "llvm/CodeGen/ValueTypes.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/DiagnosticInfo.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/GlobalValue.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/Support/Casting.h"
67 #include "llvm/Support/CodeGen.h"
68 #include "llvm/Support/CommandLine.h"
69 #include "llvm/Support/Compiler.h"
70 #include "llvm/Support/ErrorHandling.h"
71 #include "llvm/Support/KnownBits.h"
72 #include "llvm/Support/MachineValueType.h"
73 #include "llvm/Support/MathExtras.h"
74 #include "llvm/Target/TargetOptions.h"
75 #include <cassert>
76 #include <cmath>
77 #include <cstdint>
78 #include <iterator>
79 #include <tuple>
80 #include <utility>
81 #include <vector>
82 
83 using namespace llvm;
84 
85 #define DEBUG_TYPE "si-lower"
86 
87 STATISTIC(NumTailCalls, "Number of tail calls");
88 
89 static cl::opt<bool> DisableLoopAlignment(
90   "amdgpu-disable-loop-alignment",
91   cl::desc("Do not align and prefetch loops"),
92   cl::init(false));
93 
94 static cl::opt<bool> VGPRReserveforSGPRSpill(
95     "amdgpu-reserve-vgpr-for-sgpr-spill",
96     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
97 
98 static cl::opt<bool> UseDivergentRegisterIndexing(
99   "amdgpu-use-divergent-register-indexing",
100   cl::Hidden,
101   cl::desc("Use indirect register addressing for divergent indexes"),
102   cl::init(false));
103 
104 static bool hasFP32Denormals(const MachineFunction &MF) {
105   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
106   return Info->getMode().allFP32Denormals();
107 }
108 
109 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
110   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
111   return Info->getMode().allFP64FP16Denormals();
112 }
113 
114 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
115   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
116   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
117     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
118       return AMDGPU::SGPR0 + Reg;
119     }
120   }
121   llvm_unreachable("Cannot allocate sgpr");
122 }
123 
124 SITargetLowering::SITargetLowering(const TargetMachine &TM,
125                                    const GCNSubtarget &STI)
126     : AMDGPUTargetLowering(TM, STI),
127       Subtarget(&STI) {
128   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
129   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
130 
131   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
132   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
133 
134   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
135   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
136   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
137 
138   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
139   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
140 
141   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
142   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
143 
144   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
145   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
146 
147   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
148   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
149 
150   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
151   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
152 
153   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
154   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
155 
156   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
157   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
158 
159   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
160   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
161 
162   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
163   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
164 
165   if (Subtarget->has16BitInsts()) {
166     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
167     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
168 
169     // Unless there are also VOP3P operations, not operations are really legal.
170     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
171     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
172     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
173     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
174   }
175 
176   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
177   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
178 
179   computeRegisterProperties(Subtarget->getRegisterInfo());
180 
181   // The boolean content concept here is too inflexible. Compares only ever
182   // really produce a 1-bit result. Any copy/extend from these will turn into a
183   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
184   // it's what most targets use.
185   setBooleanContents(ZeroOrOneBooleanContent);
186   setBooleanVectorContents(ZeroOrOneBooleanContent);
187 
188   // We need to custom lower vector stores from local memory
189   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
190   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
195   setOperationAction(ISD::LOAD, MVT::i1, Custom);
196   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
197 
198   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
199   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
202   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
203   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
204   setOperationAction(ISD::STORE, MVT::i1, Custom);
205   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
206 
207   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
208   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
209   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
210   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
211   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
212   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
213   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
214   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
215   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
216   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
217   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
218   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
219   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
220   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
221   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
222   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
223 
224   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
225   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
226   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
227   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
228   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
229 
230   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
231   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
232 
233   setOperationAction(ISD::SELECT, MVT::i1, Promote);
234   setOperationAction(ISD::SELECT, MVT::i64, Custom);
235   setOperationAction(ISD::SELECT, MVT::f64, Promote);
236   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
237 
238   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
239   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
241   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
242   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
243 
244   setOperationAction(ISD::SETCC, MVT::i1, Promote);
245   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
246   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
247   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
248 
249   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
250   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
251   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
252   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
253   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
254   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
255   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
256   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
257 
258   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
266 
267   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
268   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
269   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
270   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
271   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
272   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
273 
274   setOperationAction(ISD::UADDO, MVT::i32, Legal);
275   setOperationAction(ISD::USUBO, MVT::i32, Legal);
276 
277   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
278   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
279 
280   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
281   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
282   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
283 
284 #if 0
285   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
286   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
287 #endif
288 
289   // We only support LOAD/STORE and vector manipulation ops for vectors
290   // with > 4 elements.
291   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
292                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
293                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
294                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
295     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
296       switch (Op) {
297       case ISD::LOAD:
298       case ISD::STORE:
299       case ISD::BUILD_VECTOR:
300       case ISD::BITCAST:
301       case ISD::EXTRACT_VECTOR_ELT:
302       case ISD::INSERT_VECTOR_ELT:
303       case ISD::INSERT_SUBVECTOR:
304       case ISD::EXTRACT_SUBVECTOR:
305       case ISD::SCALAR_TO_VECTOR:
306         break;
307       case ISD::CONCAT_VECTORS:
308         setOperationAction(Op, VT, Custom);
309         break;
310       default:
311         setOperationAction(Op, VT, Expand);
312         break;
313       }
314     }
315   }
316 
317   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
318 
319   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
320   // is expanded to avoid having two separate loops in case the index is a VGPR.
321 
322   // Most operations are naturally 32-bit vector operations. We only support
323   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
324   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
325     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
326     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
327 
328     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
329     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
330 
331     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
332     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
333 
334     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
335     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
336   }
337 
338   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
339     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
340     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
341 
342     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
343     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
344 
345     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
346     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
347 
348     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
349     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
350   }
351 
352   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
353     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
354     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
355 
356     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
357     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
358 
359     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
360     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
361 
362     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
363     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
364   }
365 
366   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
367     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
368     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
369 
370     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
371     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
372 
373     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
374     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
375 
376     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
377     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
378   }
379 
380   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
382   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
383   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
384 
385   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
386   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
387 
388   // Avoid stack access for these.
389   // TODO: Generalize to more vector types.
390   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
394 
395   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
400 
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
403   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
404 
405   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
406   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
407   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
408   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
409 
410   // Deal with vec3 vector operations when widened to vec4.
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
415 
416   // Deal with vec5 vector operations when widened to vec8.
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
419   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
420   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
421 
422   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
423   // and output demarshalling
424   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
425   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
426 
427   // We can't return success/failure, only the old value,
428   // let LLVM add the comparison
429   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
430   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
431 
432   if (Subtarget->hasFlatAddressSpace()) {
433     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
434     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
435   }
436 
437   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
438 
439   // FIXME: This should be narrowed to i32, but that only happens if i64 is
440   // illegal.
441   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
442   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
443   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
444 
445   // On SI this is s_memtime and s_memrealtime on VI.
446   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
447   setOperationAction(ISD::TRAP, MVT::Other, Custom);
448   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
449 
450   if (Subtarget->has16BitInsts()) {
451     setOperationAction(ISD::FPOW, MVT::f16, Promote);
452     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
453     setOperationAction(ISD::FLOG, MVT::f16, Custom);
454     setOperationAction(ISD::FEXP, MVT::f16, Custom);
455     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
456   }
457 
458   if (Subtarget->hasMadMacF32Insts())
459     setOperationAction(ISD::FMAD, MVT::f32, Legal);
460 
461   if (!Subtarget->hasBFI()) {
462     // fcopysign can be done in a single instruction with BFI.
463     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
464     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
465   }
466 
467   if (!Subtarget->hasBCNT(32))
468     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
469 
470   if (!Subtarget->hasBCNT(64))
471     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
472 
473   if (Subtarget->hasFFBH())
474     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
475 
476   if (Subtarget->hasFFBL())
477     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
478 
479   // We only really have 32-bit BFE instructions (and 16-bit on VI).
480   //
481   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
482   // effort to match them now. We want this to be false for i64 cases when the
483   // extraction isn't restricted to the upper or lower half. Ideally we would
484   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
485   // span the midpoint are probably relatively rare, so don't worry about them
486   // for now.
487   if (Subtarget->hasBFE())
488     setHasExtractBitsInsn(true);
489 
490   // Clamp modifier on add/sub
491   if (Subtarget->hasIntClamp()) {
492     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
493     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
494   }
495 
496   if (Subtarget->hasAddNoCarry()) {
497     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
498     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
500     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
501   }
502 
503   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
504   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
506   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
507 
508 
509   // These are really only legal for ieee_mode functions. We should be avoiding
510   // them for functions that don't have ieee_mode enabled, so just say they are
511   // legal.
512   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
513   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
515   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
516 
517 
518   if (Subtarget->haveRoundOpsF64()) {
519     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
520     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
521     setOperationAction(ISD::FRINT, MVT::f64, Legal);
522   } else {
523     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
524     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
525     setOperationAction(ISD::FRINT, MVT::f64, Custom);
526     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
527   }
528 
529   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
530 
531   setOperationAction(ISD::FSIN, MVT::f32, Custom);
532   setOperationAction(ISD::FCOS, MVT::f32, Custom);
533   setOperationAction(ISD::FDIV, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f64, Custom);
535 
536   if (Subtarget->has16BitInsts()) {
537     setOperationAction(ISD::Constant, MVT::i16, Legal);
538 
539     setOperationAction(ISD::SMIN, MVT::i16, Legal);
540     setOperationAction(ISD::SMAX, MVT::i16, Legal);
541 
542     setOperationAction(ISD::UMIN, MVT::i16, Legal);
543     setOperationAction(ISD::UMAX, MVT::i16, Legal);
544 
545     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
546     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
547 
548     setOperationAction(ISD::ROTR, MVT::i16, Promote);
549     setOperationAction(ISD::ROTL, MVT::i16, Promote);
550 
551     setOperationAction(ISD::SDIV, MVT::i16, Promote);
552     setOperationAction(ISD::UDIV, MVT::i16, Promote);
553     setOperationAction(ISD::SREM, MVT::i16, Promote);
554     setOperationAction(ISD::UREM, MVT::i16, Promote);
555     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
556     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
557 
558     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
559 
560     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
561     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
562     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
564     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
565 
566     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
567 
568     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
569 
570     setOperationAction(ISD::LOAD, MVT::i16, Custom);
571 
572     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
573 
574     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
575     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
576     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
577     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
578 
579     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
580     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
581 
582     // F16 - Constant Actions.
583     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
584 
585     // F16 - Load/Store Actions.
586     setOperationAction(ISD::LOAD, MVT::f16, Promote);
587     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
588     setOperationAction(ISD::STORE, MVT::f16, Promote);
589     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
590 
591     // F16 - VOP1 Actions.
592     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
593     setOperationAction(ISD::FCOS, MVT::f16, Custom);
594     setOperationAction(ISD::FSIN, MVT::f16, Custom);
595 
596     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
597     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
598 
599     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
600     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
601     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
602     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::FROUND, MVT::f16, Custom);
604 
605     // F16 - VOP2 Actions.
606     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
607     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
608 
609     setOperationAction(ISD::FDIV, MVT::f16, Custom);
610 
611     // F16 - VOP3 Actions.
612     setOperationAction(ISD::FMA, MVT::f16, Legal);
613     if (STI.hasMadF16())
614       setOperationAction(ISD::FMAD, MVT::f16, Legal);
615 
616     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
617       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
618         switch (Op) {
619         case ISD::LOAD:
620         case ISD::STORE:
621         case ISD::BUILD_VECTOR:
622         case ISD::BITCAST:
623         case ISD::EXTRACT_VECTOR_ELT:
624         case ISD::INSERT_VECTOR_ELT:
625         case ISD::INSERT_SUBVECTOR:
626         case ISD::EXTRACT_SUBVECTOR:
627         case ISD::SCALAR_TO_VECTOR:
628           break;
629         case ISD::CONCAT_VECTORS:
630           setOperationAction(Op, VT, Custom);
631           break;
632         default:
633           setOperationAction(Op, VT, Expand);
634           break;
635         }
636       }
637     }
638 
639     // v_perm_b32 can handle either of these.
640     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
641     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
642     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
643 
644     // XXX - Do these do anything? Vector constants turn into build_vector.
645     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
646     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
647 
648     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
649     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
650 
651     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
652     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
653     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
654     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
655 
656     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
657     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
658     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
659     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
660 
661     setOperationAction(ISD::AND, MVT::v2i16, Promote);
662     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
663     setOperationAction(ISD::OR, MVT::v2i16, Promote);
664     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
665     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
666     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
667 
668     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
669     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
670     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
671     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
672 
673     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
674     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
675     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
676     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
677 
678     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
679     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
680     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
682 
683     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
684     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
685     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
686 
687     if (!Subtarget->hasVOP3PInsts()) {
688       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
689       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
690     }
691 
692     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
693     // This isn't really legal, but this avoids the legalizer unrolling it (and
694     // allows matching fneg (fabs x) patterns)
695     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
696 
697     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
698     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
699     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
700     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
701 
702     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
703     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
704 
705     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
706     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
707   }
708 
709   if (Subtarget->hasVOP3PInsts()) {
710     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
711     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
712     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
713     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
714     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
716     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
717     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
718     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
719     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
720 
721     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
722     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
723     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
725 
726     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
727     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
728     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
729 
730     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
731     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
732 
733     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
734 
735     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
737 
738     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
739     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
740 
741     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
742     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
743     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
744     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
745     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
746     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
747 
748     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
749     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
750     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
751     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
752 
753     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
754     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
755     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
757 
758     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
759     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
760     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
761 
762     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
763     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
764 
765     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
766     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
767     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
768 
769     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
770     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
771     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
772   }
773 
774   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
775   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
776 
777   if (Subtarget->has16BitInsts()) {
778     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
779     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
780     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
781     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
782   } else {
783     // Legalization hack.
784     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
785     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
786 
787     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
788     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
789   }
790 
791   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
792     setOperationAction(ISD::SELECT, VT, Custom);
793   }
794 
795   setOperationAction(ISD::SMULO, MVT::i64, Custom);
796   setOperationAction(ISD::UMULO, MVT::i64, Custom);
797 
798   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
799   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
800   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
801   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
802   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
803   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
804   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
805 
806   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
807   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
808   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
809   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
810   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
811   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
812   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
813   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
814   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
815 
816   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
817   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
818   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
819   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
820   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
821   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
822   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
823   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
824 
825   setTargetDAGCombine(ISD::ADD);
826   setTargetDAGCombine(ISD::ADDCARRY);
827   setTargetDAGCombine(ISD::SUB);
828   setTargetDAGCombine(ISD::SUBCARRY);
829   setTargetDAGCombine(ISD::FADD);
830   setTargetDAGCombine(ISD::FSUB);
831   setTargetDAGCombine(ISD::FMINNUM);
832   setTargetDAGCombine(ISD::FMAXNUM);
833   setTargetDAGCombine(ISD::FMINNUM_IEEE);
834   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
835   setTargetDAGCombine(ISD::FMA);
836   setTargetDAGCombine(ISD::SMIN);
837   setTargetDAGCombine(ISD::SMAX);
838   setTargetDAGCombine(ISD::UMIN);
839   setTargetDAGCombine(ISD::UMAX);
840   setTargetDAGCombine(ISD::SETCC);
841   setTargetDAGCombine(ISD::AND);
842   setTargetDAGCombine(ISD::OR);
843   setTargetDAGCombine(ISD::XOR);
844   setTargetDAGCombine(ISD::SINT_TO_FP);
845   setTargetDAGCombine(ISD::UINT_TO_FP);
846   setTargetDAGCombine(ISD::FCANONICALIZE);
847   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
848   setTargetDAGCombine(ISD::ZERO_EXTEND);
849   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
850   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
851   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
852 
853   // All memory operations. Some folding on the pointer operand is done to help
854   // matching the constant offsets in the addressing modes.
855   setTargetDAGCombine(ISD::LOAD);
856   setTargetDAGCombine(ISD::STORE);
857   setTargetDAGCombine(ISD::ATOMIC_LOAD);
858   setTargetDAGCombine(ISD::ATOMIC_STORE);
859   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
860   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
861   setTargetDAGCombine(ISD::ATOMIC_SWAP);
862   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
863   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
864   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
865   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
866   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
867   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
868   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
869   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
870   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
871   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
872   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
873 
874   // FIXME: In other contexts we pretend this is a per-function property.
875   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
876 
877   setSchedulingPreference(Sched::RegPressure);
878 }
879 
880 const GCNSubtarget *SITargetLowering::getSubtarget() const {
881   return Subtarget;
882 }
883 
884 //===----------------------------------------------------------------------===//
885 // TargetLowering queries
886 //===----------------------------------------------------------------------===//
887 
888 // v_mad_mix* support a conversion from f16 to f32.
889 //
890 // There is only one special case when denormals are enabled we don't currently,
891 // where this is OK to use.
892 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
893                                        EVT DestVT, EVT SrcVT) const {
894   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
895           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
896     DestVT.getScalarType() == MVT::f32 &&
897     SrcVT.getScalarType() == MVT::f16 &&
898     // TODO: This probably only requires no input flushing?
899     !hasFP32Denormals(DAG.getMachineFunction());
900 }
901 
902 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
903   // SI has some legal vector types, but no legal vector operations. Say no
904   // shuffles are legal in order to prefer scalarizing some vector operations.
905   return false;
906 }
907 
908 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
909                                                     CallingConv::ID CC,
910                                                     EVT VT) const {
911   if (CC == CallingConv::AMDGPU_KERNEL)
912     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
913 
914   if (VT.isVector()) {
915     EVT ScalarVT = VT.getScalarType();
916     unsigned Size = ScalarVT.getSizeInBits();
917     if (Size == 32)
918       return ScalarVT.getSimpleVT();
919 
920     if (Size > 32)
921       return MVT::i32;
922 
923     if (Size == 16 && Subtarget->has16BitInsts())
924       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
925   } else if (VT.getSizeInBits() > 32)
926     return MVT::i32;
927 
928   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
929 }
930 
931 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
932                                                          CallingConv::ID CC,
933                                                          EVT VT) const {
934   if (CC == CallingConv::AMDGPU_KERNEL)
935     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
936 
937   if (VT.isVector()) {
938     unsigned NumElts = VT.getVectorNumElements();
939     EVT ScalarVT = VT.getScalarType();
940     unsigned Size = ScalarVT.getSizeInBits();
941 
942     if (Size == 32)
943       return NumElts;
944 
945     if (Size > 32)
946       return NumElts * ((Size + 31) / 32);
947 
948     if (Size == 16 && Subtarget->has16BitInsts())
949       return (NumElts + 1) / 2;
950   } else if (VT.getSizeInBits() > 32)
951     return (VT.getSizeInBits() + 31) / 32;
952 
953   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
954 }
955 
956 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
957   LLVMContext &Context, CallingConv::ID CC,
958   EVT VT, EVT &IntermediateVT,
959   unsigned &NumIntermediates, MVT &RegisterVT) const {
960   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
961     unsigned NumElts = VT.getVectorNumElements();
962     EVT ScalarVT = VT.getScalarType();
963     unsigned Size = ScalarVT.getSizeInBits();
964     if (Size == 32) {
965       RegisterVT = ScalarVT.getSimpleVT();
966       IntermediateVT = RegisterVT;
967       NumIntermediates = NumElts;
968       return NumIntermediates;
969     }
970 
971     if (Size > 32) {
972       RegisterVT = MVT::i32;
973       IntermediateVT = RegisterVT;
974       NumIntermediates = NumElts * ((Size + 31) / 32);
975       return NumIntermediates;
976     }
977 
978     // FIXME: We should fix the ABI to be the same on targets without 16-bit
979     // support, but unless we can properly handle 3-vectors, it will be still be
980     // inconsistent.
981     if (Size == 16 && Subtarget->has16BitInsts()) {
982       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
983       IntermediateVT = RegisterVT;
984       NumIntermediates = (NumElts + 1) / 2;
985       return NumIntermediates;
986     }
987   }
988 
989   return TargetLowering::getVectorTypeBreakdownForCallingConv(
990     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
991 }
992 
993 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
994   assert(DMaskLanes != 0);
995 
996   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
997     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
998     return EVT::getVectorVT(Ty->getContext(),
999                             EVT::getEVT(VT->getElementType()),
1000                             NumElts);
1001   }
1002 
1003   return EVT::getEVT(Ty);
1004 }
1005 
1006 // Peek through TFE struct returns to only use the data size.
1007 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1008   auto *ST = dyn_cast<StructType>(Ty);
1009   if (!ST)
1010     return memVTFromImageData(Ty, DMaskLanes);
1011 
1012   // Some intrinsics return an aggregate type - special case to work out the
1013   // correct memVT.
1014   //
1015   // Only limited forms of aggregate type currently expected.
1016   if (ST->getNumContainedTypes() != 2 ||
1017       !ST->getContainedType(1)->isIntegerTy(32))
1018     return EVT();
1019   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1020 }
1021 
1022 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1023                                           const CallInst &CI,
1024                                           MachineFunction &MF,
1025                                           unsigned IntrID) const {
1026   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1027           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1028     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1029                                                   (Intrinsic::ID)IntrID);
1030     if (Attr.hasFnAttribute(Attribute::ReadNone))
1031       return false;
1032 
1033     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1034 
1035     if (RsrcIntr->IsImage) {
1036       Info.ptrVal = MFI->getImagePSV(
1037         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1038         CI.getArgOperand(RsrcIntr->RsrcArg));
1039       Info.align.reset();
1040     } else {
1041       Info.ptrVal = MFI->getBufferPSV(
1042         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1043         CI.getArgOperand(RsrcIntr->RsrcArg));
1044     }
1045 
1046     Info.flags = MachineMemOperand::MODereferenceable;
1047     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1048       unsigned DMaskLanes = 4;
1049 
1050       if (RsrcIntr->IsImage) {
1051         const AMDGPU::ImageDimIntrinsicInfo *Intr
1052           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1053         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1054           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1055 
1056         if (!BaseOpcode->Gather4) {
1057           // If this isn't a gather, we may have excess loaded elements in the
1058           // IR type. Check the dmask for the real number of elements loaded.
1059           unsigned DMask
1060             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1061           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1062         }
1063 
1064         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1065       } else
1066         Info.memVT = EVT::getEVT(CI.getType());
1067 
1068       // FIXME: What does alignment mean for an image?
1069       Info.opc = ISD::INTRINSIC_W_CHAIN;
1070       Info.flags |= MachineMemOperand::MOLoad;
1071     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1072       Info.opc = ISD::INTRINSIC_VOID;
1073 
1074       Type *DataTy = CI.getArgOperand(0)->getType();
1075       if (RsrcIntr->IsImage) {
1076         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1077         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1078         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1079       } else
1080         Info.memVT = EVT::getEVT(DataTy);
1081 
1082       Info.flags |= MachineMemOperand::MOStore;
1083     } else {
1084       // Atomic
1085       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1086                                             ISD::INTRINSIC_W_CHAIN;
1087       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1088       Info.flags = MachineMemOperand::MOLoad |
1089                    MachineMemOperand::MOStore |
1090                    MachineMemOperand::MODereferenceable;
1091 
1092       // XXX - Should this be volatile without known ordering?
1093       Info.flags |= MachineMemOperand::MOVolatile;
1094     }
1095     return true;
1096   }
1097 
1098   switch (IntrID) {
1099   case Intrinsic::amdgcn_atomic_inc:
1100   case Intrinsic::amdgcn_atomic_dec:
1101   case Intrinsic::amdgcn_ds_ordered_add:
1102   case Intrinsic::amdgcn_ds_ordered_swap:
1103   case Intrinsic::amdgcn_ds_fadd:
1104   case Intrinsic::amdgcn_ds_fmin:
1105   case Intrinsic::amdgcn_ds_fmax: {
1106     Info.opc = ISD::INTRINSIC_W_CHAIN;
1107     Info.memVT = MVT::getVT(CI.getType());
1108     Info.ptrVal = CI.getOperand(0);
1109     Info.align.reset();
1110     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1111 
1112     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1113     if (!Vol->isZero())
1114       Info.flags |= MachineMemOperand::MOVolatile;
1115 
1116     return true;
1117   }
1118   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1119     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1120 
1121     Info.opc = ISD::INTRINSIC_VOID;
1122     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1123     Info.ptrVal = MFI->getBufferPSV(
1124       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1125       CI.getArgOperand(1));
1126     Info.align.reset();
1127     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1128 
1129     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1130     if (!Vol || !Vol->isZero())
1131       Info.flags |= MachineMemOperand::MOVolatile;
1132 
1133     return true;
1134   }
1135   case Intrinsic::amdgcn_global_atomic_fadd: {
1136     Info.opc = ISD::INTRINSIC_VOID;
1137     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1138                             ->getPointerElementType());
1139     Info.ptrVal = CI.getOperand(0);
1140     Info.align.reset();
1141     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1142 
1143     return true;
1144   }
1145   case Intrinsic::amdgcn_ds_append:
1146   case Intrinsic::amdgcn_ds_consume: {
1147     Info.opc = ISD::INTRINSIC_W_CHAIN;
1148     Info.memVT = MVT::getVT(CI.getType());
1149     Info.ptrVal = CI.getOperand(0);
1150     Info.align.reset();
1151     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1152 
1153     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1154     if (!Vol->isZero())
1155       Info.flags |= MachineMemOperand::MOVolatile;
1156 
1157     return true;
1158   }
1159   case Intrinsic::amdgcn_global_atomic_csub: {
1160     Info.opc = ISD::INTRINSIC_W_CHAIN;
1161     Info.memVT = MVT::getVT(CI.getType());
1162     Info.ptrVal = CI.getOperand(0);
1163     Info.align.reset();
1164     Info.flags = MachineMemOperand::MOLoad |
1165                  MachineMemOperand::MOStore |
1166                  MachineMemOperand::MOVolatile;
1167     return true;
1168   }
1169   case Intrinsic::amdgcn_ds_gws_init:
1170   case Intrinsic::amdgcn_ds_gws_barrier:
1171   case Intrinsic::amdgcn_ds_gws_sema_v:
1172   case Intrinsic::amdgcn_ds_gws_sema_br:
1173   case Intrinsic::amdgcn_ds_gws_sema_p:
1174   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1175     Info.opc = ISD::INTRINSIC_VOID;
1176 
1177     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1178     Info.ptrVal =
1179         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1180 
1181     // This is an abstract access, but we need to specify a type and size.
1182     Info.memVT = MVT::i32;
1183     Info.size = 4;
1184     Info.align = Align(4);
1185 
1186     Info.flags = MachineMemOperand::MOStore;
1187     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1188       Info.flags = MachineMemOperand::MOLoad;
1189     return true;
1190   }
1191   default:
1192     return false;
1193   }
1194 }
1195 
1196 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1197                                             SmallVectorImpl<Value*> &Ops,
1198                                             Type *&AccessTy) const {
1199   switch (II->getIntrinsicID()) {
1200   case Intrinsic::amdgcn_atomic_inc:
1201   case Intrinsic::amdgcn_atomic_dec:
1202   case Intrinsic::amdgcn_ds_ordered_add:
1203   case Intrinsic::amdgcn_ds_ordered_swap:
1204   case Intrinsic::amdgcn_ds_append:
1205   case Intrinsic::amdgcn_ds_consume:
1206   case Intrinsic::amdgcn_ds_fadd:
1207   case Intrinsic::amdgcn_ds_fmin:
1208   case Intrinsic::amdgcn_ds_fmax:
1209   case Intrinsic::amdgcn_global_atomic_fadd:
1210   case Intrinsic::amdgcn_global_atomic_csub: {
1211     Value *Ptr = II->getArgOperand(0);
1212     AccessTy = II->getType();
1213     Ops.push_back(Ptr);
1214     return true;
1215   }
1216   default:
1217     return false;
1218   }
1219 }
1220 
1221 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1222   if (!Subtarget->hasFlatInstOffsets()) {
1223     // Flat instructions do not have offsets, and only have the register
1224     // address.
1225     return AM.BaseOffs == 0 && AM.Scale == 0;
1226   }
1227 
1228   return AM.Scale == 0 &&
1229          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1230                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1231                                   /*Signed=*/false));
1232 }
1233 
1234 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1235   if (Subtarget->hasFlatGlobalInsts())
1236     return AM.Scale == 0 &&
1237            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1238                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1239                                     /*Signed=*/true));
1240 
1241   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1242       // Assume the we will use FLAT for all global memory accesses
1243       // on VI.
1244       // FIXME: This assumption is currently wrong.  On VI we still use
1245       // MUBUF instructions for the r + i addressing mode.  As currently
1246       // implemented, the MUBUF instructions only work on buffer < 4GB.
1247       // It may be possible to support > 4GB buffers with MUBUF instructions,
1248       // by setting the stride value in the resource descriptor which would
1249       // increase the size limit to (stride * 4GB).  However, this is risky,
1250       // because it has never been validated.
1251     return isLegalFlatAddressingMode(AM);
1252   }
1253 
1254   return isLegalMUBUFAddressingMode(AM);
1255 }
1256 
1257 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1258   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1259   // additionally can do r + r + i with addr64. 32-bit has more addressing
1260   // mode options. Depending on the resource constant, it can also do
1261   // (i64 r0) + (i32 r1) * (i14 i).
1262   //
1263   // Private arrays end up using a scratch buffer most of the time, so also
1264   // assume those use MUBUF instructions. Scratch loads / stores are currently
1265   // implemented as mubuf instructions with offen bit set, so slightly
1266   // different than the normal addr64.
1267   if (!isUInt<12>(AM.BaseOffs))
1268     return false;
1269 
1270   // FIXME: Since we can split immediate into soffset and immediate offset,
1271   // would it make sense to allow any immediate?
1272 
1273   switch (AM.Scale) {
1274   case 0: // r + i or just i, depending on HasBaseReg.
1275     return true;
1276   case 1:
1277     return true; // We have r + r or r + i.
1278   case 2:
1279     if (AM.HasBaseReg) {
1280       // Reject 2 * r + r.
1281       return false;
1282     }
1283 
1284     // Allow 2 * r as r + r
1285     // Or  2 * r + i is allowed as r + r + i.
1286     return true;
1287   default: // Don't allow n * r
1288     return false;
1289   }
1290 }
1291 
1292 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1293                                              const AddrMode &AM, Type *Ty,
1294                                              unsigned AS, Instruction *I) const {
1295   // No global is ever allowed as a base.
1296   if (AM.BaseGV)
1297     return false;
1298 
1299   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1300     return isLegalGlobalAddressingMode(AM);
1301 
1302   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1303       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1304       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1305     // If the offset isn't a multiple of 4, it probably isn't going to be
1306     // correctly aligned.
1307     // FIXME: Can we get the real alignment here?
1308     if (AM.BaseOffs % 4 != 0)
1309       return isLegalMUBUFAddressingMode(AM);
1310 
1311     // There are no SMRD extloads, so if we have to do a small type access we
1312     // will use a MUBUF load.
1313     // FIXME?: We also need to do this if unaligned, but we don't know the
1314     // alignment here.
1315     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1316       return isLegalGlobalAddressingMode(AM);
1317 
1318     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1319       // SMRD instructions have an 8-bit, dword offset on SI.
1320       if (!isUInt<8>(AM.BaseOffs / 4))
1321         return false;
1322     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1323       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1324       // in 8-bits, it can use a smaller encoding.
1325       if (!isUInt<32>(AM.BaseOffs / 4))
1326         return false;
1327     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1328       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1329       if (!isUInt<20>(AM.BaseOffs))
1330         return false;
1331     } else
1332       llvm_unreachable("unhandled generation");
1333 
1334     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1335       return true;
1336 
1337     if (AM.Scale == 1 && AM.HasBaseReg)
1338       return true;
1339 
1340     return false;
1341 
1342   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1343     return isLegalMUBUFAddressingMode(AM);
1344   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1345              AS == AMDGPUAS::REGION_ADDRESS) {
1346     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1347     // field.
1348     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1349     // an 8-bit dword offset but we don't know the alignment here.
1350     if (!isUInt<16>(AM.BaseOffs))
1351       return false;
1352 
1353     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1354       return true;
1355 
1356     if (AM.Scale == 1 && AM.HasBaseReg)
1357       return true;
1358 
1359     return false;
1360   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1361              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1362     // For an unknown address space, this usually means that this is for some
1363     // reason being used for pure arithmetic, and not based on some addressing
1364     // computation. We don't have instructions that compute pointers with any
1365     // addressing modes, so treat them as having no offset like flat
1366     // instructions.
1367     return isLegalFlatAddressingMode(AM);
1368   }
1369 
1370   // Assume a user alias of global for unknown address spaces.
1371   return isLegalGlobalAddressingMode(AM);
1372 }
1373 
1374 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1375                                         const SelectionDAG &DAG) const {
1376   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1377     return (MemVT.getSizeInBits() <= 4 * 32);
1378   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1379     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1380     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1381   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1382     return (MemVT.getSizeInBits() <= 2 * 32);
1383   }
1384   return true;
1385 }
1386 
1387 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1388     unsigned Size, unsigned AddrSpace, Align Alignment,
1389     MachineMemOperand::Flags Flags, bool *IsFast) const {
1390   if (IsFast)
1391     *IsFast = false;
1392 
1393   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1394       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1395     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1396     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1397     // with adjacent offsets.
1398     bool AlignedBy4 = Alignment >= Align(4);
1399     if (IsFast)
1400       *IsFast = AlignedBy4;
1401 
1402     return AlignedBy4;
1403   }
1404 
1405   // FIXME: We have to be conservative here and assume that flat operations
1406   // will access scratch.  If we had access to the IR function, then we
1407   // could determine if any private memory was used in the function.
1408   if (!Subtarget->hasUnalignedScratchAccess() &&
1409       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1410        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1411     bool AlignedBy4 = Alignment >= Align(4);
1412     if (IsFast)
1413       *IsFast = AlignedBy4;
1414 
1415     return AlignedBy4;
1416   }
1417 
1418   if (Subtarget->hasUnalignedBufferAccess()) {
1419     // If we have an uniform constant load, it still requires using a slow
1420     // buffer instruction if unaligned.
1421     if (IsFast) {
1422       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1423       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1424       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1425                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1426         Alignment >= Align(4) : Alignment != Align(2);
1427     }
1428 
1429     return true;
1430   }
1431 
1432   // Smaller than dword value must be aligned.
1433   if (Size < 32)
1434     return false;
1435 
1436   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1437   // byte-address are ignored, thus forcing Dword alignment.
1438   // This applies to private, global, and constant memory.
1439   if (IsFast)
1440     *IsFast = true;
1441 
1442   return Size >= 32 && Alignment >= Align(4);
1443 }
1444 
1445 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1446     EVT VT, unsigned AddrSpace, unsigned Alignment,
1447     MachineMemOperand::Flags Flags, bool *IsFast) const {
1448   if (IsFast)
1449     *IsFast = false;
1450 
1451   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1452   // which isn't a simple VT.
1453   // Until MVT is extended to handle this, simply check for the size and
1454   // rely on the condition below: allow accesses if the size is a multiple of 4.
1455   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1456                            VT.getStoreSize() > 16)) {
1457     return false;
1458   }
1459 
1460   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1461                                             Align(Alignment), Flags, IsFast);
1462 }
1463 
1464 EVT SITargetLowering::getOptimalMemOpType(
1465     const MemOp &Op, const AttributeList &FuncAttributes) const {
1466   // FIXME: Should account for address space here.
1467 
1468   // The default fallback uses the private pointer size as a guess for a type to
1469   // use. Make sure we switch these to 64-bit accesses.
1470 
1471   if (Op.size() >= 16 &&
1472       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1473     return MVT::v4i32;
1474 
1475   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1476     return MVT::v2i32;
1477 
1478   // Use the default.
1479   return MVT::Other;
1480 }
1481 
1482 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1483   const MemSDNode *MemNode = cast<MemSDNode>(N);
1484   const Value *Ptr = MemNode->getMemOperand()->getValue();
1485   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1486   return I && I->getMetadata("amdgpu.noclobber");
1487 }
1488 
1489 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1490                                            unsigned DestAS) const {
1491   // Flat -> private/local is a simple truncate.
1492   // Flat -> global is no-op
1493   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1494     return true;
1495 
1496   const GCNTargetMachine &TM =
1497       static_cast<const GCNTargetMachine &>(getTargetMachine());
1498   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1499 }
1500 
1501 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1502   const MemSDNode *MemNode = cast<MemSDNode>(N);
1503 
1504   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1505 }
1506 
1507 TargetLoweringBase::LegalizeTypeAction
1508 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1509   int NumElts = VT.getVectorNumElements();
1510   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1511     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1512   return TargetLoweringBase::getPreferredVectorAction(VT);
1513 }
1514 
1515 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1516                                                          Type *Ty) const {
1517   // FIXME: Could be smarter if called for vector constants.
1518   return true;
1519 }
1520 
1521 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1522   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1523     switch (Op) {
1524     case ISD::LOAD:
1525     case ISD::STORE:
1526 
1527     // These operations are done with 32-bit instructions anyway.
1528     case ISD::AND:
1529     case ISD::OR:
1530     case ISD::XOR:
1531     case ISD::SELECT:
1532       // TODO: Extensions?
1533       return true;
1534     default:
1535       return false;
1536     }
1537   }
1538 
1539   // SimplifySetCC uses this function to determine whether or not it should
1540   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1541   if (VT == MVT::i1 && Op == ISD::SETCC)
1542     return false;
1543 
1544   return TargetLowering::isTypeDesirableForOp(Op, VT);
1545 }
1546 
1547 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1548                                                    const SDLoc &SL,
1549                                                    SDValue Chain,
1550                                                    uint64_t Offset) const {
1551   const DataLayout &DL = DAG.getDataLayout();
1552   MachineFunction &MF = DAG.getMachineFunction();
1553   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1554 
1555   const ArgDescriptor *InputPtrReg;
1556   const TargetRegisterClass *RC;
1557   LLT ArgTy;
1558 
1559   std::tie(InputPtrReg, RC, ArgTy) =
1560       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1561 
1562   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1563   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1564   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1565     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1566 
1567   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1568 }
1569 
1570 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1571                                             const SDLoc &SL) const {
1572   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1573                                                FIRST_IMPLICIT);
1574   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1575 }
1576 
1577 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1578                                          const SDLoc &SL, SDValue Val,
1579                                          bool Signed,
1580                                          const ISD::InputArg *Arg) const {
1581   // First, if it is a widened vector, narrow it.
1582   if (VT.isVector() &&
1583       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1584     EVT NarrowedVT =
1585         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1586                          VT.getVectorNumElements());
1587     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1588                       DAG.getConstant(0, SL, MVT::i32));
1589   }
1590 
1591   // Then convert the vector elements or scalar value.
1592   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1593       VT.bitsLT(MemVT)) {
1594     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1595     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1596   }
1597 
1598   if (MemVT.isFloatingPoint())
1599     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1600   else if (Signed)
1601     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1602   else
1603     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1604 
1605   return Val;
1606 }
1607 
1608 SDValue SITargetLowering::lowerKernargMemParameter(
1609     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1610     uint64_t Offset, Align Alignment, bool Signed,
1611     const ISD::InputArg *Arg) const {
1612   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1613 
1614   // Try to avoid using an extload by loading earlier than the argument address,
1615   // and extracting the relevant bits. The load should hopefully be merged with
1616   // the previous argument.
1617   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1618     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1619     int64_t AlignDownOffset = alignDown(Offset, 4);
1620     int64_t OffsetDiff = Offset - AlignDownOffset;
1621 
1622     EVT IntVT = MemVT.changeTypeToInteger();
1623 
1624     // TODO: If we passed in the base kernel offset we could have a better
1625     // alignment than 4, but we don't really need it.
1626     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1627     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1628                                MachineMemOperand::MODereferenceable |
1629                                MachineMemOperand::MOInvariant);
1630 
1631     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1632     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1633 
1634     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1635     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1636     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1637 
1638 
1639     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1640   }
1641 
1642   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1643   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1644                              MachineMemOperand::MODereferenceable |
1645                                  MachineMemOperand::MOInvariant);
1646 
1647   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1648   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1649 }
1650 
1651 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1652                                               const SDLoc &SL, SDValue Chain,
1653                                               const ISD::InputArg &Arg) const {
1654   MachineFunction &MF = DAG.getMachineFunction();
1655   MachineFrameInfo &MFI = MF.getFrameInfo();
1656 
1657   if (Arg.Flags.isByVal()) {
1658     unsigned Size = Arg.Flags.getByValSize();
1659     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1660     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1661   }
1662 
1663   unsigned ArgOffset = VA.getLocMemOffset();
1664   unsigned ArgSize = VA.getValVT().getStoreSize();
1665 
1666   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1667 
1668   // Create load nodes to retrieve arguments from the stack.
1669   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1670   SDValue ArgValue;
1671 
1672   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1673   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1674   MVT MemVT = VA.getValVT();
1675 
1676   switch (VA.getLocInfo()) {
1677   default:
1678     break;
1679   case CCValAssign::BCvt:
1680     MemVT = VA.getLocVT();
1681     break;
1682   case CCValAssign::SExt:
1683     ExtType = ISD::SEXTLOAD;
1684     break;
1685   case CCValAssign::ZExt:
1686     ExtType = ISD::ZEXTLOAD;
1687     break;
1688   case CCValAssign::AExt:
1689     ExtType = ISD::EXTLOAD;
1690     break;
1691   }
1692 
1693   ArgValue = DAG.getExtLoad(
1694     ExtType, SL, VA.getLocVT(), Chain, FIN,
1695     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1696     MemVT);
1697   return ArgValue;
1698 }
1699 
1700 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1701   const SIMachineFunctionInfo &MFI,
1702   EVT VT,
1703   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1704   const ArgDescriptor *Reg;
1705   const TargetRegisterClass *RC;
1706   LLT Ty;
1707 
1708   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1709   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1710 }
1711 
1712 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1713                                    CallingConv::ID CallConv,
1714                                    ArrayRef<ISD::InputArg> Ins,
1715                                    BitVector &Skipped,
1716                                    FunctionType *FType,
1717                                    SIMachineFunctionInfo *Info) {
1718   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1719     const ISD::InputArg *Arg = &Ins[I];
1720 
1721     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1722            "vector type argument should have been split");
1723 
1724     // First check if it's a PS input addr.
1725     if (CallConv == CallingConv::AMDGPU_PS &&
1726         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1727       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1728 
1729       // Inconveniently only the first part of the split is marked as isSplit,
1730       // so skip to the end. We only want to increment PSInputNum once for the
1731       // entire split argument.
1732       if (Arg->Flags.isSplit()) {
1733         while (!Arg->Flags.isSplitEnd()) {
1734           assert((!Arg->VT.isVector() ||
1735                   Arg->VT.getScalarSizeInBits() == 16) &&
1736                  "unexpected vector split in ps argument type");
1737           if (!SkipArg)
1738             Splits.push_back(*Arg);
1739           Arg = &Ins[++I];
1740         }
1741       }
1742 
1743       if (SkipArg) {
1744         // We can safely skip PS inputs.
1745         Skipped.set(Arg->getOrigArgIndex());
1746         ++PSInputNum;
1747         continue;
1748       }
1749 
1750       Info->markPSInputAllocated(PSInputNum);
1751       if (Arg->Used)
1752         Info->markPSInputEnabled(PSInputNum);
1753 
1754       ++PSInputNum;
1755     }
1756 
1757     Splits.push_back(*Arg);
1758   }
1759 }
1760 
1761 // Allocate special inputs passed in VGPRs.
1762 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1763                                                       MachineFunction &MF,
1764                                                       const SIRegisterInfo &TRI,
1765                                                       SIMachineFunctionInfo &Info) const {
1766   const LLT S32 = LLT::scalar(32);
1767   MachineRegisterInfo &MRI = MF.getRegInfo();
1768 
1769   if (Info.hasWorkItemIDX()) {
1770     Register Reg = AMDGPU::VGPR0;
1771     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1772 
1773     CCInfo.AllocateReg(Reg);
1774     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1775   }
1776 
1777   if (Info.hasWorkItemIDY()) {
1778     Register Reg = AMDGPU::VGPR1;
1779     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1780 
1781     CCInfo.AllocateReg(Reg);
1782     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1783   }
1784 
1785   if (Info.hasWorkItemIDZ()) {
1786     Register Reg = AMDGPU::VGPR2;
1787     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1788 
1789     CCInfo.AllocateReg(Reg);
1790     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1791   }
1792 }
1793 
1794 // Try to allocate a VGPR at the end of the argument list, or if no argument
1795 // VGPRs are left allocating a stack slot.
1796 // If \p Mask is is given it indicates bitfield position in the register.
1797 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1798 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1799                                          ArgDescriptor Arg = ArgDescriptor()) {
1800   if (Arg.isSet())
1801     return ArgDescriptor::createArg(Arg, Mask);
1802 
1803   ArrayRef<MCPhysReg> ArgVGPRs
1804     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1805   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1806   if (RegIdx == ArgVGPRs.size()) {
1807     // Spill to stack required.
1808     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1809 
1810     return ArgDescriptor::createStack(Offset, Mask);
1811   }
1812 
1813   unsigned Reg = ArgVGPRs[RegIdx];
1814   Reg = CCInfo.AllocateReg(Reg);
1815   assert(Reg != AMDGPU::NoRegister);
1816 
1817   MachineFunction &MF = CCInfo.getMachineFunction();
1818   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1819   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1820   return ArgDescriptor::createRegister(Reg, Mask);
1821 }
1822 
1823 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1824                                              const TargetRegisterClass *RC,
1825                                              unsigned NumArgRegs) {
1826   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1827   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1828   if (RegIdx == ArgSGPRs.size())
1829     report_fatal_error("ran out of SGPRs for arguments");
1830 
1831   unsigned Reg = ArgSGPRs[RegIdx];
1832   Reg = CCInfo.AllocateReg(Reg);
1833   assert(Reg != AMDGPU::NoRegister);
1834 
1835   MachineFunction &MF = CCInfo.getMachineFunction();
1836   MF.addLiveIn(Reg, RC);
1837   return ArgDescriptor::createRegister(Reg);
1838 }
1839 
1840 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1841   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1842 }
1843 
1844 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1845   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1846 }
1847 
1848 /// Allocate implicit function VGPR arguments at the end of allocated user
1849 /// arguments.
1850 void SITargetLowering::allocateSpecialInputVGPRs(
1851   CCState &CCInfo, MachineFunction &MF,
1852   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1853   const unsigned Mask = 0x3ff;
1854   ArgDescriptor Arg;
1855 
1856   if (Info.hasWorkItemIDX()) {
1857     Arg = allocateVGPR32Input(CCInfo, Mask);
1858     Info.setWorkItemIDX(Arg);
1859   }
1860 
1861   if (Info.hasWorkItemIDY()) {
1862     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1863     Info.setWorkItemIDY(Arg);
1864   }
1865 
1866   if (Info.hasWorkItemIDZ())
1867     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1868 }
1869 
1870 /// Allocate implicit function VGPR arguments in fixed registers.
1871 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1872   CCState &CCInfo, MachineFunction &MF,
1873   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1874   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1875   if (!Reg)
1876     report_fatal_error("failed to allocated VGPR for implicit arguments");
1877 
1878   const unsigned Mask = 0x3ff;
1879   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1880   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1881   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1882 }
1883 
1884 void SITargetLowering::allocateSpecialInputSGPRs(
1885   CCState &CCInfo,
1886   MachineFunction &MF,
1887   const SIRegisterInfo &TRI,
1888   SIMachineFunctionInfo &Info) const {
1889   auto &ArgInfo = Info.getArgInfo();
1890 
1891   // TODO: Unify handling with private memory pointers.
1892 
1893   if (Info.hasDispatchPtr())
1894     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1895 
1896   if (Info.hasQueuePtr())
1897     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1898 
1899   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1900   // constant offset from the kernarg segment.
1901   if (Info.hasImplicitArgPtr())
1902     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1903 
1904   if (Info.hasDispatchID())
1905     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1906 
1907   // flat_scratch_init is not applicable for non-kernel functions.
1908 
1909   if (Info.hasWorkGroupIDX())
1910     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1911 
1912   if (Info.hasWorkGroupIDY())
1913     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1914 
1915   if (Info.hasWorkGroupIDZ())
1916     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1917 }
1918 
1919 // Allocate special inputs passed in user SGPRs.
1920 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1921                                             MachineFunction &MF,
1922                                             const SIRegisterInfo &TRI,
1923                                             SIMachineFunctionInfo &Info) const {
1924   if (Info.hasImplicitBufferPtr()) {
1925     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1926     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1927     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1928   }
1929 
1930   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1931   if (Info.hasPrivateSegmentBuffer()) {
1932     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1933     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1934     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1935   }
1936 
1937   if (Info.hasDispatchPtr()) {
1938     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1939     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1940     CCInfo.AllocateReg(DispatchPtrReg);
1941   }
1942 
1943   if (Info.hasQueuePtr()) {
1944     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1945     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1946     CCInfo.AllocateReg(QueuePtrReg);
1947   }
1948 
1949   if (Info.hasKernargSegmentPtr()) {
1950     MachineRegisterInfo &MRI = MF.getRegInfo();
1951     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1952     CCInfo.AllocateReg(InputPtrReg);
1953 
1954     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1955     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1956   }
1957 
1958   if (Info.hasDispatchID()) {
1959     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1960     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1961     CCInfo.AllocateReg(DispatchIDReg);
1962   }
1963 
1964   if (Info.hasFlatScratchInit()) {
1965     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1966     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1967     CCInfo.AllocateReg(FlatScratchInitReg);
1968   }
1969 
1970   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1971   // these from the dispatch pointer.
1972 }
1973 
1974 // Allocate special input registers that are initialized per-wave.
1975 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1976                                            MachineFunction &MF,
1977                                            SIMachineFunctionInfo &Info,
1978                                            CallingConv::ID CallConv,
1979                                            bool IsShader) const {
1980   if (Info.hasWorkGroupIDX()) {
1981     unsigned Reg = Info.addWorkGroupIDX();
1982     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1983     CCInfo.AllocateReg(Reg);
1984   }
1985 
1986   if (Info.hasWorkGroupIDY()) {
1987     unsigned Reg = Info.addWorkGroupIDY();
1988     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1989     CCInfo.AllocateReg(Reg);
1990   }
1991 
1992   if (Info.hasWorkGroupIDZ()) {
1993     unsigned Reg = Info.addWorkGroupIDZ();
1994     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1995     CCInfo.AllocateReg(Reg);
1996   }
1997 
1998   if (Info.hasWorkGroupInfo()) {
1999     unsigned Reg = Info.addWorkGroupInfo();
2000     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2001     CCInfo.AllocateReg(Reg);
2002   }
2003 
2004   if (Info.hasPrivateSegmentWaveByteOffset()) {
2005     // Scratch wave offset passed in system SGPR.
2006     unsigned PrivateSegmentWaveByteOffsetReg;
2007 
2008     if (IsShader) {
2009       PrivateSegmentWaveByteOffsetReg =
2010         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2011 
2012       // This is true if the scratch wave byte offset doesn't have a fixed
2013       // location.
2014       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2015         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2016         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2017       }
2018     } else
2019       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2020 
2021     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2022     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2023   }
2024 }
2025 
2026 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2027                                      MachineFunction &MF,
2028                                      const SIRegisterInfo &TRI,
2029                                      SIMachineFunctionInfo &Info) {
2030   // Now that we've figured out where the scratch register inputs are, see if
2031   // should reserve the arguments and use them directly.
2032   MachineFrameInfo &MFI = MF.getFrameInfo();
2033   bool HasStackObjects = MFI.hasStackObjects();
2034   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2035 
2036   // Record that we know we have non-spill stack objects so we don't need to
2037   // check all stack objects later.
2038   if (HasStackObjects)
2039     Info.setHasNonSpillStackObjects(true);
2040 
2041   // Everything live out of a block is spilled with fast regalloc, so it's
2042   // almost certain that spilling will be required.
2043   if (TM.getOptLevel() == CodeGenOpt::None)
2044     HasStackObjects = true;
2045 
2046   // For now assume stack access is needed in any callee functions, so we need
2047   // the scratch registers to pass in.
2048   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2049 
2050   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2051     // If we have stack objects, we unquestionably need the private buffer
2052     // resource. For the Code Object V2 ABI, this will be the first 4 user
2053     // SGPR inputs. We can reserve those and use them directly.
2054 
2055     Register PrivateSegmentBufferReg =
2056         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2057     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2058   } else {
2059     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2060     // We tentatively reserve the last registers (skipping the last registers
2061     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2062     // we'll replace these with the ones immediately after those which were
2063     // really allocated. In the prologue copies will be inserted from the
2064     // argument to these reserved registers.
2065 
2066     // Without HSA, relocations are used for the scratch pointer and the
2067     // buffer resource setup is always inserted in the prologue. Scratch wave
2068     // offset is still in an input SGPR.
2069     Info.setScratchRSrcReg(ReservedBufferReg);
2070   }
2071 
2072   MachineRegisterInfo &MRI = MF.getRegInfo();
2073 
2074   // For entry functions we have to set up the stack pointer if we use it,
2075   // whereas non-entry functions get this "for free". This means there is no
2076   // intrinsic advantage to using S32 over S34 in cases where we do not have
2077   // calls but do need a frame pointer (i.e. if we are requested to have one
2078   // because frame pointer elimination is disabled). To keep things simple we
2079   // only ever use S32 as the call ABI stack pointer, and so using it does not
2080   // imply we need a separate frame pointer.
2081   //
2082   // Try to use s32 as the SP, but move it if it would interfere with input
2083   // arguments. This won't work with calls though.
2084   //
2085   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2086   // registers.
2087   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2088     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2089   } else {
2090     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2091 
2092     if (MFI.hasCalls())
2093       report_fatal_error("call in graphics shader with too many input SGPRs");
2094 
2095     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2096       if (!MRI.isLiveIn(Reg)) {
2097         Info.setStackPtrOffsetReg(Reg);
2098         break;
2099       }
2100     }
2101 
2102     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2103       report_fatal_error("failed to find register for SP");
2104   }
2105 
2106   // hasFP should be accurate for entry functions even before the frame is
2107   // finalized, because it does not rely on the known stack size, only
2108   // properties like whether variable sized objects are present.
2109   if (ST.getFrameLowering()->hasFP(MF)) {
2110     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2111   }
2112 }
2113 
2114 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2115   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2116   return !Info->isEntryFunction();
2117 }
2118 
2119 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2120 
2121 }
2122 
2123 void SITargetLowering::insertCopiesSplitCSR(
2124   MachineBasicBlock *Entry,
2125   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2126   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2127 
2128   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2129   if (!IStart)
2130     return;
2131 
2132   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2133   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2134   MachineBasicBlock::iterator MBBI = Entry->begin();
2135   for (const MCPhysReg *I = IStart; *I; ++I) {
2136     const TargetRegisterClass *RC = nullptr;
2137     if (AMDGPU::SReg_64RegClass.contains(*I))
2138       RC = &AMDGPU::SGPR_64RegClass;
2139     else if (AMDGPU::SReg_32RegClass.contains(*I))
2140       RC = &AMDGPU::SGPR_32RegClass;
2141     else
2142       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2143 
2144     Register NewVR = MRI->createVirtualRegister(RC);
2145     // Create copy from CSR to a virtual register.
2146     Entry->addLiveIn(*I);
2147     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2148       .addReg(*I);
2149 
2150     // Insert the copy-back instructions right before the terminator.
2151     for (auto *Exit : Exits)
2152       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2153               TII->get(TargetOpcode::COPY), *I)
2154         .addReg(NewVR);
2155   }
2156 }
2157 
2158 SDValue SITargetLowering::LowerFormalArguments(
2159     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2160     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2161     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2162   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2163 
2164   MachineFunction &MF = DAG.getMachineFunction();
2165   const Function &Fn = MF.getFunction();
2166   FunctionType *FType = MF.getFunction().getFunctionType();
2167   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2168 
2169   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2170     DiagnosticInfoUnsupported NoGraphicsHSA(
2171         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2172     DAG.getContext()->diagnose(NoGraphicsHSA);
2173     return DAG.getEntryNode();
2174   }
2175 
2176   SmallVector<ISD::InputArg, 16> Splits;
2177   SmallVector<CCValAssign, 16> ArgLocs;
2178   BitVector Skipped(Ins.size());
2179   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2180                  *DAG.getContext());
2181 
2182   bool IsShader = AMDGPU::isShader(CallConv);
2183   bool IsKernel = AMDGPU::isKernel(CallConv);
2184   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2185 
2186   if (IsShader) {
2187     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2188 
2189     // At least one interpolation mode must be enabled or else the GPU will
2190     // hang.
2191     //
2192     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2193     // set PSInputAddr, the user wants to enable some bits after the compilation
2194     // based on run-time states. Since we can't know what the final PSInputEna
2195     // will look like, so we shouldn't do anything here and the user should take
2196     // responsibility for the correct programming.
2197     //
2198     // Otherwise, the following restrictions apply:
2199     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2200     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2201     //   enabled too.
2202     if (CallConv == CallingConv::AMDGPU_PS) {
2203       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2204            ((Info->getPSInputAddr() & 0xF) == 0 &&
2205             Info->isPSInputAllocated(11))) {
2206         CCInfo.AllocateReg(AMDGPU::VGPR0);
2207         CCInfo.AllocateReg(AMDGPU::VGPR1);
2208         Info->markPSInputAllocated(0);
2209         Info->markPSInputEnabled(0);
2210       }
2211       if (Subtarget->isAmdPalOS()) {
2212         // For isAmdPalOS, the user does not enable some bits after compilation
2213         // based on run-time states; the register values being generated here are
2214         // the final ones set in hardware. Therefore we need to apply the
2215         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2216         // a bit is set in PSInputAddr but not PSInputEnable is where the
2217         // frontend set up an input arg for a particular interpolation mode, but
2218         // nothing uses that input arg. Really we should have an earlier pass
2219         // that removes such an arg.)
2220         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2221         if ((PsInputBits & 0x7F) == 0 ||
2222             ((PsInputBits & 0xF) == 0 &&
2223              (PsInputBits >> 11 & 1)))
2224           Info->markPSInputEnabled(
2225               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2226       }
2227     }
2228 
2229     assert(!Info->hasDispatchPtr() &&
2230            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2231            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2232            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2233            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2234            !Info->hasWorkItemIDZ());
2235   } else if (IsKernel) {
2236     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2237   } else {
2238     Splits.append(Ins.begin(), Ins.end());
2239   }
2240 
2241   if (IsEntryFunc) {
2242     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2243     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2244   } else {
2245     // For the fixed ABI, pass workitem IDs in the last argument register.
2246     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2247       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2248   }
2249 
2250   if (IsKernel) {
2251     analyzeFormalArgumentsCompute(CCInfo, Ins);
2252   } else {
2253     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2254     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2255   }
2256 
2257   SmallVector<SDValue, 16> Chains;
2258 
2259   // FIXME: This is the minimum kernel argument alignment. We should improve
2260   // this to the maximum alignment of the arguments.
2261   //
2262   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2263   // kern arg offset.
2264   const Align KernelArgBaseAlign = Align(16);
2265 
2266   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2267     const ISD::InputArg &Arg = Ins[i];
2268     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2269       InVals.push_back(DAG.getUNDEF(Arg.VT));
2270       continue;
2271     }
2272 
2273     CCValAssign &VA = ArgLocs[ArgIdx++];
2274     MVT VT = VA.getLocVT();
2275 
2276     if (IsEntryFunc && VA.isMemLoc()) {
2277       VT = Ins[i].VT;
2278       EVT MemVT = VA.getLocVT();
2279 
2280       const uint64_t Offset = VA.getLocMemOffset();
2281       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2282 
2283       if (Arg.Flags.isByRef()) {
2284         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2285 
2286         const GCNTargetMachine &TM =
2287             static_cast<const GCNTargetMachine &>(getTargetMachine());
2288         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2289                                     Arg.Flags.getPointerAddrSpace())) {
2290           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2291                                      Arg.Flags.getPointerAddrSpace());
2292         }
2293 
2294         InVals.push_back(Ptr);
2295         continue;
2296       }
2297 
2298       SDValue Arg = lowerKernargMemParameter(
2299         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2300       Chains.push_back(Arg.getValue(1));
2301 
2302       auto *ParamTy =
2303         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2304       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2305           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2306                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2307         // On SI local pointers are just offsets into LDS, so they are always
2308         // less than 16-bits.  On CI and newer they could potentially be
2309         // real pointers, so we can't guarantee their size.
2310         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2311                           DAG.getValueType(MVT::i16));
2312       }
2313 
2314       InVals.push_back(Arg);
2315       continue;
2316     } else if (!IsEntryFunc && VA.isMemLoc()) {
2317       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2318       InVals.push_back(Val);
2319       if (!Arg.Flags.isByVal())
2320         Chains.push_back(Val.getValue(1));
2321       continue;
2322     }
2323 
2324     assert(VA.isRegLoc() && "Parameter must be in a register!");
2325 
2326     Register Reg = VA.getLocReg();
2327     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2328     EVT ValVT = VA.getValVT();
2329 
2330     Reg = MF.addLiveIn(Reg, RC);
2331     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2332 
2333     if (Arg.Flags.isSRet()) {
2334       // The return object should be reasonably addressable.
2335 
2336       // FIXME: This helps when the return is a real sret. If it is a
2337       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2338       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2339       unsigned NumBits
2340         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2341       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2342         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2343     }
2344 
2345     // If this is an 8 or 16-bit value, it is really passed promoted
2346     // to 32 bits. Insert an assert[sz]ext to capture this, then
2347     // truncate to the right size.
2348     switch (VA.getLocInfo()) {
2349     case CCValAssign::Full:
2350       break;
2351     case CCValAssign::BCvt:
2352       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2353       break;
2354     case CCValAssign::SExt:
2355       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2356                         DAG.getValueType(ValVT));
2357       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2358       break;
2359     case CCValAssign::ZExt:
2360       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2361                         DAG.getValueType(ValVT));
2362       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2363       break;
2364     case CCValAssign::AExt:
2365       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2366       break;
2367     default:
2368       llvm_unreachable("Unknown loc info!");
2369     }
2370 
2371     InVals.push_back(Val);
2372   }
2373 
2374   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2375     // Special inputs come after user arguments.
2376     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2377   }
2378 
2379   // Start adding system SGPRs.
2380   if (IsEntryFunc) {
2381     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2382   } else {
2383     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2384     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2385   }
2386 
2387   auto &ArgUsageInfo =
2388     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2389   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2390 
2391   unsigned StackArgSize = CCInfo.getNextStackOffset();
2392   Info->setBytesInStackArgArea(StackArgSize);
2393 
2394   return Chains.empty() ? Chain :
2395     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2396 }
2397 
2398 // TODO: If return values can't fit in registers, we should return as many as
2399 // possible in registers before passing on stack.
2400 bool SITargetLowering::CanLowerReturn(
2401   CallingConv::ID CallConv,
2402   MachineFunction &MF, bool IsVarArg,
2403   const SmallVectorImpl<ISD::OutputArg> &Outs,
2404   LLVMContext &Context) const {
2405   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2406   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2407   // for shaders. Vector types should be explicitly handled by CC.
2408   if (AMDGPU::isEntryFunctionCC(CallConv))
2409     return true;
2410 
2411   SmallVector<CCValAssign, 16> RVLocs;
2412   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2413   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2414 }
2415 
2416 SDValue
2417 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2418                               bool isVarArg,
2419                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2420                               const SmallVectorImpl<SDValue> &OutVals,
2421                               const SDLoc &DL, SelectionDAG &DAG) const {
2422   MachineFunction &MF = DAG.getMachineFunction();
2423   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2424 
2425   if (AMDGPU::isKernel(CallConv)) {
2426     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2427                                              OutVals, DL, DAG);
2428   }
2429 
2430   bool IsShader = AMDGPU::isShader(CallConv);
2431 
2432   Info->setIfReturnsVoid(Outs.empty());
2433   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2434 
2435   // CCValAssign - represent the assignment of the return value to a location.
2436   SmallVector<CCValAssign, 48> RVLocs;
2437   SmallVector<ISD::OutputArg, 48> Splits;
2438 
2439   // CCState - Info about the registers and stack slots.
2440   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2441                  *DAG.getContext());
2442 
2443   // Analyze outgoing return values.
2444   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2445 
2446   SDValue Flag;
2447   SmallVector<SDValue, 48> RetOps;
2448   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2449 
2450   // Add return address for callable functions.
2451   if (!Info->isEntryFunction()) {
2452     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2453     SDValue ReturnAddrReg = CreateLiveInRegister(
2454       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2455 
2456     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2457         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2458         MVT::i64);
2459     Chain =
2460         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2461     Flag = Chain.getValue(1);
2462     RetOps.push_back(ReturnAddrVirtualReg);
2463   }
2464 
2465   // Copy the result values into the output registers.
2466   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2467        ++I, ++RealRVLocIdx) {
2468     CCValAssign &VA = RVLocs[I];
2469     assert(VA.isRegLoc() && "Can only return in registers!");
2470     // TODO: Partially return in registers if return values don't fit.
2471     SDValue Arg = OutVals[RealRVLocIdx];
2472 
2473     // Copied from other backends.
2474     switch (VA.getLocInfo()) {
2475     case CCValAssign::Full:
2476       break;
2477     case CCValAssign::BCvt:
2478       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2479       break;
2480     case CCValAssign::SExt:
2481       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2482       break;
2483     case CCValAssign::ZExt:
2484       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2485       break;
2486     case CCValAssign::AExt:
2487       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2488       break;
2489     default:
2490       llvm_unreachable("Unknown loc info!");
2491     }
2492 
2493     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2494     Flag = Chain.getValue(1);
2495     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2496   }
2497 
2498   // FIXME: Does sret work properly?
2499   if (!Info->isEntryFunction()) {
2500     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2501     const MCPhysReg *I =
2502       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2503     if (I) {
2504       for (; *I; ++I) {
2505         if (AMDGPU::SReg_64RegClass.contains(*I))
2506           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2507         else if (AMDGPU::SReg_32RegClass.contains(*I))
2508           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2509         else
2510           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2511       }
2512     }
2513   }
2514 
2515   // Update chain and glue.
2516   RetOps[0] = Chain;
2517   if (Flag.getNode())
2518     RetOps.push_back(Flag);
2519 
2520   unsigned Opc = AMDGPUISD::ENDPGM;
2521   if (!IsWaveEnd)
2522     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2523   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2524 }
2525 
2526 SDValue SITargetLowering::LowerCallResult(
2527     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2528     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2529     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2530     SDValue ThisVal) const {
2531   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2532 
2533   // Assign locations to each value returned by this call.
2534   SmallVector<CCValAssign, 16> RVLocs;
2535   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2536                  *DAG.getContext());
2537   CCInfo.AnalyzeCallResult(Ins, RetCC);
2538 
2539   // Copy all of the result registers out of their specified physreg.
2540   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2541     CCValAssign VA = RVLocs[i];
2542     SDValue Val;
2543 
2544     if (VA.isRegLoc()) {
2545       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2546       Chain = Val.getValue(1);
2547       InFlag = Val.getValue(2);
2548     } else if (VA.isMemLoc()) {
2549       report_fatal_error("TODO: return values in memory");
2550     } else
2551       llvm_unreachable("unknown argument location type");
2552 
2553     switch (VA.getLocInfo()) {
2554     case CCValAssign::Full:
2555       break;
2556     case CCValAssign::BCvt:
2557       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2558       break;
2559     case CCValAssign::ZExt:
2560       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2561                         DAG.getValueType(VA.getValVT()));
2562       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2563       break;
2564     case CCValAssign::SExt:
2565       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2566                         DAG.getValueType(VA.getValVT()));
2567       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2568       break;
2569     case CCValAssign::AExt:
2570       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2571       break;
2572     default:
2573       llvm_unreachable("Unknown loc info!");
2574     }
2575 
2576     InVals.push_back(Val);
2577   }
2578 
2579   return Chain;
2580 }
2581 
2582 // Add code to pass special inputs required depending on used features separate
2583 // from the explicit user arguments present in the IR.
2584 void SITargetLowering::passSpecialInputs(
2585     CallLoweringInfo &CLI,
2586     CCState &CCInfo,
2587     const SIMachineFunctionInfo &Info,
2588     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2589     SmallVectorImpl<SDValue> &MemOpChains,
2590     SDValue Chain) const {
2591   // If we don't have a call site, this was a call inserted by
2592   // legalization. These can never use special inputs.
2593   if (!CLI.CB)
2594     return;
2595 
2596   SelectionDAG &DAG = CLI.DAG;
2597   const SDLoc &DL = CLI.DL;
2598 
2599   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2600   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2601 
2602   const AMDGPUFunctionArgInfo *CalleeArgInfo
2603     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2604   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2605     auto &ArgUsageInfo =
2606       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2607     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2608   }
2609 
2610   // TODO: Unify with private memory register handling. This is complicated by
2611   // the fact that at least in kernels, the input argument is not necessarily
2612   // in the same location as the input.
2613   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2614     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2615     AMDGPUFunctionArgInfo::QUEUE_PTR,
2616     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2617     AMDGPUFunctionArgInfo::DISPATCH_ID,
2618     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2619     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2620     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2621   };
2622 
2623   for (auto InputID : InputRegs) {
2624     const ArgDescriptor *OutgoingArg;
2625     const TargetRegisterClass *ArgRC;
2626     LLT ArgTy;
2627 
2628     std::tie(OutgoingArg, ArgRC, ArgTy) =
2629         CalleeArgInfo->getPreloadedValue(InputID);
2630     if (!OutgoingArg)
2631       continue;
2632 
2633     const ArgDescriptor *IncomingArg;
2634     const TargetRegisterClass *IncomingArgRC;
2635     LLT Ty;
2636     std::tie(IncomingArg, IncomingArgRC, Ty) =
2637         CallerArgInfo.getPreloadedValue(InputID);
2638     assert(IncomingArgRC == ArgRC);
2639 
2640     // All special arguments are ints for now.
2641     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2642     SDValue InputReg;
2643 
2644     if (IncomingArg) {
2645       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2646     } else {
2647       // The implicit arg ptr is special because it doesn't have a corresponding
2648       // input for kernels, and is computed from the kernarg segment pointer.
2649       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2650       InputReg = getImplicitArgPtr(DAG, DL);
2651     }
2652 
2653     if (OutgoingArg->isRegister()) {
2654       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2655       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2656         report_fatal_error("failed to allocate implicit input argument");
2657     } else {
2658       unsigned SpecialArgOffset =
2659           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2660       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2661                                               SpecialArgOffset);
2662       MemOpChains.push_back(ArgStore);
2663     }
2664   }
2665 
2666   // Pack workitem IDs into a single register or pass it as is if already
2667   // packed.
2668   const ArgDescriptor *OutgoingArg;
2669   const TargetRegisterClass *ArgRC;
2670   LLT Ty;
2671 
2672   std::tie(OutgoingArg, ArgRC, Ty) =
2673       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2674   if (!OutgoingArg)
2675     std::tie(OutgoingArg, ArgRC, Ty) =
2676         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2677   if (!OutgoingArg)
2678     std::tie(OutgoingArg, ArgRC, Ty) =
2679         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2680   if (!OutgoingArg)
2681     return;
2682 
2683   const ArgDescriptor *IncomingArgX = std::get<0>(
2684       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2685   const ArgDescriptor *IncomingArgY = std::get<0>(
2686       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2687   const ArgDescriptor *IncomingArgZ = std::get<0>(
2688       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2689 
2690   SDValue InputReg;
2691   SDLoc SL;
2692 
2693   // If incoming ids are not packed we need to pack them.
2694   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2695     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2696 
2697   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2698     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2699     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2700                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2701     InputReg = InputReg.getNode() ?
2702                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2703   }
2704 
2705   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2706     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2707     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2708                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2709     InputReg = InputReg.getNode() ?
2710                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2711   }
2712 
2713   if (!InputReg.getNode()) {
2714     // Workitem ids are already packed, any of present incoming arguments
2715     // will carry all required fields.
2716     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2717       IncomingArgX ? *IncomingArgX :
2718       IncomingArgY ? *IncomingArgY :
2719                      *IncomingArgZ, ~0u);
2720     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2721   }
2722 
2723   if (OutgoingArg->isRegister()) {
2724     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2725     CCInfo.AllocateReg(OutgoingArg->getRegister());
2726   } else {
2727     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2728     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2729                                             SpecialArgOffset);
2730     MemOpChains.push_back(ArgStore);
2731   }
2732 }
2733 
2734 static bool canGuaranteeTCO(CallingConv::ID CC) {
2735   return CC == CallingConv::Fast;
2736 }
2737 
2738 /// Return true if we might ever do TCO for calls with this calling convention.
2739 static bool mayTailCallThisCC(CallingConv::ID CC) {
2740   switch (CC) {
2741   case CallingConv::C:
2742     return true;
2743   default:
2744     return canGuaranteeTCO(CC);
2745   }
2746 }
2747 
2748 bool SITargetLowering::isEligibleForTailCallOptimization(
2749     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2750     const SmallVectorImpl<ISD::OutputArg> &Outs,
2751     const SmallVectorImpl<SDValue> &OutVals,
2752     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2753   if (!mayTailCallThisCC(CalleeCC))
2754     return false;
2755 
2756   MachineFunction &MF = DAG.getMachineFunction();
2757   const Function &CallerF = MF.getFunction();
2758   CallingConv::ID CallerCC = CallerF.getCallingConv();
2759   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2760   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2761 
2762   // Kernels aren't callable, and don't have a live in return address so it
2763   // doesn't make sense to do a tail call with entry functions.
2764   if (!CallerPreserved)
2765     return false;
2766 
2767   bool CCMatch = CallerCC == CalleeCC;
2768 
2769   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2770     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2771       return true;
2772     return false;
2773   }
2774 
2775   // TODO: Can we handle var args?
2776   if (IsVarArg)
2777     return false;
2778 
2779   for (const Argument &Arg : CallerF.args()) {
2780     if (Arg.hasByValAttr())
2781       return false;
2782   }
2783 
2784   LLVMContext &Ctx = *DAG.getContext();
2785 
2786   // Check that the call results are passed in the same way.
2787   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2788                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2789                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2790     return false;
2791 
2792   // The callee has to preserve all registers the caller needs to preserve.
2793   if (!CCMatch) {
2794     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2795     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2796       return false;
2797   }
2798 
2799   // Nothing more to check if the callee is taking no arguments.
2800   if (Outs.empty())
2801     return true;
2802 
2803   SmallVector<CCValAssign, 16> ArgLocs;
2804   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2805 
2806   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2807 
2808   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2809   // If the stack arguments for this call do not fit into our own save area then
2810   // the call cannot be made tail.
2811   // TODO: Is this really necessary?
2812   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2813     return false;
2814 
2815   const MachineRegisterInfo &MRI = MF.getRegInfo();
2816   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2817 }
2818 
2819 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2820   if (!CI->isTailCall())
2821     return false;
2822 
2823   const Function *ParentFn = CI->getParent()->getParent();
2824   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2825     return false;
2826   return true;
2827 }
2828 
2829 // The wave scratch offset register is used as the global base pointer.
2830 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2831                                     SmallVectorImpl<SDValue> &InVals) const {
2832   SelectionDAG &DAG = CLI.DAG;
2833   const SDLoc &DL = CLI.DL;
2834   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2835   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2836   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2837   SDValue Chain = CLI.Chain;
2838   SDValue Callee = CLI.Callee;
2839   bool &IsTailCall = CLI.IsTailCall;
2840   CallingConv::ID CallConv = CLI.CallConv;
2841   bool IsVarArg = CLI.IsVarArg;
2842   bool IsSibCall = false;
2843   bool IsThisReturn = false;
2844   MachineFunction &MF = DAG.getMachineFunction();
2845 
2846   if (Callee.isUndef() || isNullConstant(Callee)) {
2847     if (!CLI.IsTailCall) {
2848       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2849         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2850     }
2851 
2852     return Chain;
2853   }
2854 
2855   if (IsVarArg) {
2856     return lowerUnhandledCall(CLI, InVals,
2857                               "unsupported call to variadic function ");
2858   }
2859 
2860   if (!CLI.CB)
2861     report_fatal_error("unsupported libcall legalization");
2862 
2863   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2864       !CLI.CB->getCalledFunction()) {
2865     return lowerUnhandledCall(CLI, InVals,
2866                               "unsupported indirect call to function ");
2867   }
2868 
2869   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2870     return lowerUnhandledCall(CLI, InVals,
2871                               "unsupported required tail call to function ");
2872   }
2873 
2874   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2875     // Note the issue is with the CC of the calling function, not of the call
2876     // itself.
2877     return lowerUnhandledCall(CLI, InVals,
2878                           "unsupported call from graphics shader of function ");
2879   }
2880 
2881   if (IsTailCall) {
2882     IsTailCall = isEligibleForTailCallOptimization(
2883       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2884     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2885       report_fatal_error("failed to perform tail call elimination on a call "
2886                          "site marked musttail");
2887     }
2888 
2889     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2890 
2891     // A sibling call is one where we're under the usual C ABI and not planning
2892     // to change that but can still do a tail call:
2893     if (!TailCallOpt && IsTailCall)
2894       IsSibCall = true;
2895 
2896     if (IsTailCall)
2897       ++NumTailCalls;
2898   }
2899 
2900   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2901   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2902   SmallVector<SDValue, 8> MemOpChains;
2903 
2904   // Analyze operands of the call, assigning locations to each operand.
2905   SmallVector<CCValAssign, 16> ArgLocs;
2906   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2907   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2908 
2909   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2910     // With a fixed ABI, allocate fixed registers before user arguments.
2911     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2912   }
2913 
2914   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2915 
2916   // Get a count of how many bytes are to be pushed on the stack.
2917   unsigned NumBytes = CCInfo.getNextStackOffset();
2918 
2919   if (IsSibCall) {
2920     // Since we're not changing the ABI to make this a tail call, the memory
2921     // operands are already available in the caller's incoming argument space.
2922     NumBytes = 0;
2923   }
2924 
2925   // FPDiff is the byte offset of the call's argument area from the callee's.
2926   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2927   // by this amount for a tail call. In a sibling call it must be 0 because the
2928   // caller will deallocate the entire stack and the callee still expects its
2929   // arguments to begin at SP+0. Completely unused for non-tail calls.
2930   int32_t FPDiff = 0;
2931   MachineFrameInfo &MFI = MF.getFrameInfo();
2932 
2933   // Adjust the stack pointer for the new arguments...
2934   // These operations are automatically eliminated by the prolog/epilog pass
2935   if (!IsSibCall) {
2936     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2937 
2938     SmallVector<SDValue, 4> CopyFromChains;
2939 
2940     // In the HSA case, this should be an identity copy.
2941     SDValue ScratchRSrcReg
2942       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2943     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2944     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2945     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2946   }
2947 
2948   MVT PtrVT = MVT::i32;
2949 
2950   // Walk the register/memloc assignments, inserting copies/loads.
2951   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2952     CCValAssign &VA = ArgLocs[i];
2953     SDValue Arg = OutVals[i];
2954 
2955     // Promote the value if needed.
2956     switch (VA.getLocInfo()) {
2957     case CCValAssign::Full:
2958       break;
2959     case CCValAssign::BCvt:
2960       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2961       break;
2962     case CCValAssign::ZExt:
2963       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2964       break;
2965     case CCValAssign::SExt:
2966       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2967       break;
2968     case CCValAssign::AExt:
2969       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2970       break;
2971     case CCValAssign::FPExt:
2972       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2973       break;
2974     default:
2975       llvm_unreachable("Unknown loc info!");
2976     }
2977 
2978     if (VA.isRegLoc()) {
2979       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2980     } else {
2981       assert(VA.isMemLoc());
2982 
2983       SDValue DstAddr;
2984       MachinePointerInfo DstInfo;
2985 
2986       unsigned LocMemOffset = VA.getLocMemOffset();
2987       int32_t Offset = LocMemOffset;
2988 
2989       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2990       MaybeAlign Alignment;
2991 
2992       if (IsTailCall) {
2993         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2994         unsigned OpSize = Flags.isByVal() ?
2995           Flags.getByValSize() : VA.getValVT().getStoreSize();
2996 
2997         // FIXME: We can have better than the minimum byval required alignment.
2998         Alignment =
2999             Flags.isByVal()
3000                 ? Flags.getNonZeroByValAlign()
3001                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3002 
3003         Offset = Offset + FPDiff;
3004         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3005 
3006         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3007         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3008 
3009         // Make sure any stack arguments overlapping with where we're storing
3010         // are loaded before this eventual operation. Otherwise they'll be
3011         // clobbered.
3012 
3013         // FIXME: Why is this really necessary? This seems to just result in a
3014         // lot of code to copy the stack and write them back to the same
3015         // locations, which are supposed to be immutable?
3016         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3017       } else {
3018         DstAddr = PtrOff;
3019         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3020         Alignment =
3021             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3022       }
3023 
3024       if (Outs[i].Flags.isByVal()) {
3025         SDValue SizeNode =
3026             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3027         SDValue Cpy =
3028             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3029                           Outs[i].Flags.getNonZeroByValAlign(),
3030                           /*isVol = */ false, /*AlwaysInline = */ true,
3031                           /*isTailCall = */ false, DstInfo,
3032                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3033 
3034         MemOpChains.push_back(Cpy);
3035       } else {
3036         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
3037                                      Alignment ? Alignment->value() : 0);
3038         MemOpChains.push_back(Store);
3039       }
3040     }
3041   }
3042 
3043   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
3044     // Copy special input registers after user input arguments.
3045     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3046   }
3047 
3048   if (!MemOpChains.empty())
3049     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3050 
3051   // Build a sequence of copy-to-reg nodes chained together with token chain
3052   // and flag operands which copy the outgoing args into the appropriate regs.
3053   SDValue InFlag;
3054   for (auto &RegToPass : RegsToPass) {
3055     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3056                              RegToPass.second, InFlag);
3057     InFlag = Chain.getValue(1);
3058   }
3059 
3060 
3061   SDValue PhysReturnAddrReg;
3062   if (IsTailCall) {
3063     // Since the return is being combined with the call, we need to pass on the
3064     // return address.
3065 
3066     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3067     SDValue ReturnAddrReg = CreateLiveInRegister(
3068       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3069 
3070     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3071                                         MVT::i64);
3072     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3073     InFlag = Chain.getValue(1);
3074   }
3075 
3076   // We don't usually want to end the call-sequence here because we would tidy
3077   // the frame up *after* the call, however in the ABI-changing tail-call case
3078   // we've carefully laid out the parameters so that when sp is reset they'll be
3079   // in the correct location.
3080   if (IsTailCall && !IsSibCall) {
3081     Chain = DAG.getCALLSEQ_END(Chain,
3082                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3083                                DAG.getTargetConstant(0, DL, MVT::i32),
3084                                InFlag, DL);
3085     InFlag = Chain.getValue(1);
3086   }
3087 
3088   std::vector<SDValue> Ops;
3089   Ops.push_back(Chain);
3090   Ops.push_back(Callee);
3091   // Add a redundant copy of the callee global which will not be legalized, as
3092   // we need direct access to the callee later.
3093   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3094     const GlobalValue *GV = GSD->getGlobal();
3095     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3096   } else {
3097     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3098   }
3099 
3100   if (IsTailCall) {
3101     // Each tail call may have to adjust the stack by a different amount, so
3102     // this information must travel along with the operation for eventual
3103     // consumption by emitEpilogue.
3104     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3105 
3106     Ops.push_back(PhysReturnAddrReg);
3107   }
3108 
3109   // Add argument registers to the end of the list so that they are known live
3110   // into the call.
3111   for (auto &RegToPass : RegsToPass) {
3112     Ops.push_back(DAG.getRegister(RegToPass.first,
3113                                   RegToPass.second.getValueType()));
3114   }
3115 
3116   // Add a register mask operand representing the call-preserved registers.
3117 
3118   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3119   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3120   assert(Mask && "Missing call preserved mask for calling convention");
3121   Ops.push_back(DAG.getRegisterMask(Mask));
3122 
3123   if (InFlag.getNode())
3124     Ops.push_back(InFlag);
3125 
3126   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3127 
3128   // If we're doing a tall call, use a TC_RETURN here rather than an
3129   // actual call instruction.
3130   if (IsTailCall) {
3131     MFI.setHasTailCall();
3132     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3133   }
3134 
3135   // Returns a chain and a flag for retval copy to use.
3136   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3137   Chain = Call.getValue(0);
3138   InFlag = Call.getValue(1);
3139 
3140   uint64_t CalleePopBytes = NumBytes;
3141   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3142                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3143                              InFlag, DL);
3144   if (!Ins.empty())
3145     InFlag = Chain.getValue(1);
3146 
3147   // Handle result values, copying them out of physregs into vregs that we
3148   // return.
3149   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3150                          InVals, IsThisReturn,
3151                          IsThisReturn ? OutVals[0] : SDValue());
3152 }
3153 
3154 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3155 // except for applying the wave size scale to the increment amount.
3156 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3157     SDValue Op, SelectionDAG &DAG) const {
3158   const MachineFunction &MF = DAG.getMachineFunction();
3159   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3160 
3161   SDLoc dl(Op);
3162   EVT VT = Op.getValueType();
3163   SDValue Tmp1 = Op;
3164   SDValue Tmp2 = Op.getValue(1);
3165   SDValue Tmp3 = Op.getOperand(2);
3166   SDValue Chain = Tmp1.getOperand(0);
3167 
3168   Register SPReg = Info->getStackPtrOffsetReg();
3169 
3170   // Chain the dynamic stack allocation so that it doesn't modify the stack
3171   // pointer when other instructions are using the stack.
3172   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3173 
3174   SDValue Size  = Tmp2.getOperand(1);
3175   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3176   Chain = SP.getValue(1);
3177   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3178   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3179   const TargetFrameLowering *TFL = ST.getFrameLowering();
3180   unsigned Opc =
3181     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3182     ISD::ADD : ISD::SUB;
3183 
3184   SDValue ScaledSize = DAG.getNode(
3185       ISD::SHL, dl, VT, Size,
3186       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3187 
3188   Align StackAlign = TFL->getStackAlign();
3189   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3190   if (Alignment && *Alignment > StackAlign) {
3191     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3192                        DAG.getConstant(-(uint64_t)Alignment->value()
3193                                            << ST.getWavefrontSizeLog2(),
3194                                        dl, VT));
3195   }
3196 
3197   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3198   Tmp2 = DAG.getCALLSEQ_END(
3199       Chain, DAG.getIntPtrConstant(0, dl, true),
3200       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3201 
3202   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3203 }
3204 
3205 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3206                                                   SelectionDAG &DAG) const {
3207   // We only handle constant sizes here to allow non-entry block, static sized
3208   // allocas. A truly dynamic value is more difficult to support because we
3209   // don't know if the size value is uniform or not. If the size isn't uniform,
3210   // we would need to do a wave reduction to get the maximum size to know how
3211   // much to increment the uniform stack pointer.
3212   SDValue Size = Op.getOperand(1);
3213   if (isa<ConstantSDNode>(Size))
3214       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3215 
3216   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3217 }
3218 
3219 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3220                                              const MachineFunction &MF) const {
3221   Register Reg = StringSwitch<Register>(RegName)
3222     .Case("m0", AMDGPU::M0)
3223     .Case("exec", AMDGPU::EXEC)
3224     .Case("exec_lo", AMDGPU::EXEC_LO)
3225     .Case("exec_hi", AMDGPU::EXEC_HI)
3226     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3227     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3228     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3229     .Default(Register());
3230 
3231   if (Reg == AMDGPU::NoRegister) {
3232     report_fatal_error(Twine("invalid register name \""
3233                              + StringRef(RegName)  + "\"."));
3234 
3235   }
3236 
3237   if (!Subtarget->hasFlatScrRegister() &&
3238        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3239     report_fatal_error(Twine("invalid register \""
3240                              + StringRef(RegName)  + "\" for subtarget."));
3241   }
3242 
3243   switch (Reg) {
3244   case AMDGPU::M0:
3245   case AMDGPU::EXEC_LO:
3246   case AMDGPU::EXEC_HI:
3247   case AMDGPU::FLAT_SCR_LO:
3248   case AMDGPU::FLAT_SCR_HI:
3249     if (VT.getSizeInBits() == 32)
3250       return Reg;
3251     break;
3252   case AMDGPU::EXEC:
3253   case AMDGPU::FLAT_SCR:
3254     if (VT.getSizeInBits() == 64)
3255       return Reg;
3256     break;
3257   default:
3258     llvm_unreachable("missing register type checking");
3259   }
3260 
3261   report_fatal_error(Twine("invalid type for register \""
3262                            + StringRef(RegName) + "\"."));
3263 }
3264 
3265 // If kill is not the last instruction, split the block so kill is always a
3266 // proper terminator.
3267 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3268                                                     MachineBasicBlock *BB) const {
3269   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3270 
3271   MachineBasicBlock::iterator SplitPoint(&MI);
3272   ++SplitPoint;
3273 
3274   if (SplitPoint == BB->end()) {
3275     // Don't bother with a new block.
3276     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3277     return BB;
3278   }
3279 
3280   MachineFunction *MF = BB->getParent();
3281   MachineBasicBlock *SplitBB
3282     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3283 
3284   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3285   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3286 
3287   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3288   BB->addSuccessor(SplitBB);
3289 
3290   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3291   return SplitBB;
3292 }
3293 
3294 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3295 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3296 // be the first instruction in the remainder block.
3297 //
3298 /// \returns { LoopBody, Remainder }
3299 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3300 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3301   MachineFunction *MF = MBB.getParent();
3302   MachineBasicBlock::iterator I(&MI);
3303 
3304   // To insert the loop we need to split the block. Move everything after this
3305   // point to a new block, and insert a new empty block between the two.
3306   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3307   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3308   MachineFunction::iterator MBBI(MBB);
3309   ++MBBI;
3310 
3311   MF->insert(MBBI, LoopBB);
3312   MF->insert(MBBI, RemainderBB);
3313 
3314   LoopBB->addSuccessor(LoopBB);
3315   LoopBB->addSuccessor(RemainderBB);
3316 
3317   // Move the rest of the block into a new block.
3318   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3319 
3320   if (InstInLoop) {
3321     auto Next = std::next(I);
3322 
3323     // Move instruction to loop body.
3324     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3325 
3326     // Move the rest of the block.
3327     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3328   } else {
3329     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3330   }
3331 
3332   MBB.addSuccessor(LoopBB);
3333 
3334   return std::make_pair(LoopBB, RemainderBB);
3335 }
3336 
3337 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3338 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3339   MachineBasicBlock *MBB = MI.getParent();
3340   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3341   auto I = MI.getIterator();
3342   auto E = std::next(I);
3343 
3344   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3345     .addImm(0);
3346 
3347   MIBundleBuilder Bundler(*MBB, I, E);
3348   finalizeBundle(*MBB, Bundler.begin());
3349 }
3350 
3351 MachineBasicBlock *
3352 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3353                                          MachineBasicBlock *BB) const {
3354   const DebugLoc &DL = MI.getDebugLoc();
3355 
3356   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3357 
3358   MachineBasicBlock *LoopBB;
3359   MachineBasicBlock *RemainderBB;
3360   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3361 
3362   // Apparently kill flags are only valid if the def is in the same block?
3363   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3364     Src->setIsKill(false);
3365 
3366   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3367 
3368   MachineBasicBlock::iterator I = LoopBB->end();
3369 
3370   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3371     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3372 
3373   // Clear TRAP_STS.MEM_VIOL
3374   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3375     .addImm(0)
3376     .addImm(EncodedReg);
3377 
3378   bundleInstWithWaitcnt(MI);
3379 
3380   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3381 
3382   // Load and check TRAP_STS.MEM_VIOL
3383   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3384     .addImm(EncodedReg);
3385 
3386   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3387   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3388     .addReg(Reg, RegState::Kill)
3389     .addImm(0);
3390   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3391     .addMBB(LoopBB);
3392 
3393   return RemainderBB;
3394 }
3395 
3396 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3397 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3398 // will only do one iteration. In the worst case, this will loop 64 times.
3399 //
3400 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3401 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3402   const SIInstrInfo *TII,
3403   MachineRegisterInfo &MRI,
3404   MachineBasicBlock &OrigBB,
3405   MachineBasicBlock &LoopBB,
3406   const DebugLoc &DL,
3407   const MachineOperand &IdxReg,
3408   unsigned InitReg,
3409   unsigned ResultReg,
3410   unsigned PhiReg,
3411   unsigned InitSaveExecReg,
3412   int Offset,
3413   bool UseGPRIdxMode,
3414   bool IsIndirectSrc) {
3415   MachineFunction *MF = OrigBB.getParent();
3416   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3417   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3418   MachineBasicBlock::iterator I = LoopBB.begin();
3419 
3420   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3421   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3422   Register NewExec = MRI.createVirtualRegister(BoolRC);
3423   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3424   Register CondReg = MRI.createVirtualRegister(BoolRC);
3425 
3426   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3427     .addReg(InitReg)
3428     .addMBB(&OrigBB)
3429     .addReg(ResultReg)
3430     .addMBB(&LoopBB);
3431 
3432   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3433     .addReg(InitSaveExecReg)
3434     .addMBB(&OrigBB)
3435     .addReg(NewExec)
3436     .addMBB(&LoopBB);
3437 
3438   // Read the next variant <- also loop target.
3439   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3440     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3441 
3442   // Compare the just read M0 value to all possible Idx values.
3443   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3444     .addReg(CurrentIdxReg)
3445     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3446 
3447   // Update EXEC, save the original EXEC value to VCC.
3448   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3449                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3450           NewExec)
3451     .addReg(CondReg, RegState::Kill);
3452 
3453   MRI.setSimpleHint(NewExec, CondReg);
3454 
3455   if (UseGPRIdxMode) {
3456     unsigned IdxReg;
3457     if (Offset == 0) {
3458       IdxReg = CurrentIdxReg;
3459     } else {
3460       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3461       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3462         .addReg(CurrentIdxReg, RegState::Kill)
3463         .addImm(Offset);
3464     }
3465     unsigned IdxMode = IsIndirectSrc ?
3466       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3467     MachineInstr *SetOn =
3468       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3469       .addReg(IdxReg, RegState::Kill)
3470       .addImm(IdxMode);
3471     SetOn->getOperand(3).setIsUndef();
3472   } else {
3473     // Move index from VCC into M0
3474     if (Offset == 0) {
3475       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3476         .addReg(CurrentIdxReg, RegState::Kill);
3477     } else {
3478       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3479         .addReg(CurrentIdxReg, RegState::Kill)
3480         .addImm(Offset);
3481     }
3482   }
3483 
3484   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3485   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3486   MachineInstr *InsertPt =
3487     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3488                                                   : AMDGPU::S_XOR_B64_term), Exec)
3489       .addReg(Exec)
3490       .addReg(NewExec);
3491 
3492   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3493   // s_cbranch_scc0?
3494 
3495   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3496   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3497     .addMBB(&LoopBB);
3498 
3499   return InsertPt->getIterator();
3500 }
3501 
3502 // This has slightly sub-optimal regalloc when the source vector is killed by
3503 // the read. The register allocator does not understand that the kill is
3504 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3505 // subregister from it, using 1 more VGPR than necessary. This was saved when
3506 // this was expanded after register allocation.
3507 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3508                                                   MachineBasicBlock &MBB,
3509                                                   MachineInstr &MI,
3510                                                   unsigned InitResultReg,
3511                                                   unsigned PhiReg,
3512                                                   int Offset,
3513                                                   bool UseGPRIdxMode,
3514                                                   bool IsIndirectSrc) {
3515   MachineFunction *MF = MBB.getParent();
3516   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3517   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3518   MachineRegisterInfo &MRI = MF->getRegInfo();
3519   const DebugLoc &DL = MI.getDebugLoc();
3520   MachineBasicBlock::iterator I(&MI);
3521 
3522   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3523   Register DstReg = MI.getOperand(0).getReg();
3524   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3525   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3526   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3527   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3528 
3529   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3530 
3531   // Save the EXEC mask
3532   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3533     .addReg(Exec);
3534 
3535   MachineBasicBlock *LoopBB;
3536   MachineBasicBlock *RemainderBB;
3537   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3538 
3539   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3540 
3541   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3542                                       InitResultReg, DstReg, PhiReg, TmpExec,
3543                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3544   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3545   MachineFunction::iterator MBBI(LoopBB);
3546   ++MBBI;
3547   MF->insert(MBBI, LandingPad);
3548   LoopBB->removeSuccessor(RemainderBB);
3549   LandingPad->addSuccessor(RemainderBB);
3550   LoopBB->addSuccessor(LandingPad);
3551   MachineBasicBlock::iterator First = LandingPad->begin();
3552   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3553     .addReg(SaveExec);
3554 
3555   return InsPt;
3556 }
3557 
3558 // Returns subreg index, offset
3559 static std::pair<unsigned, int>
3560 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3561                             const TargetRegisterClass *SuperRC,
3562                             unsigned VecReg,
3563                             int Offset) {
3564   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3565 
3566   // Skip out of bounds offsets, or else we would end up using an undefined
3567   // register.
3568   if (Offset >= NumElts || Offset < 0)
3569     return std::make_pair(AMDGPU::sub0, Offset);
3570 
3571   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3572 }
3573 
3574 // Return true if the index is an SGPR and was set.
3575 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3576                                  MachineRegisterInfo &MRI,
3577                                  MachineInstr &MI,
3578                                  int Offset,
3579                                  bool UseGPRIdxMode,
3580                                  bool IsIndirectSrc) {
3581   MachineBasicBlock *MBB = MI.getParent();
3582   const DebugLoc &DL = MI.getDebugLoc();
3583   MachineBasicBlock::iterator I(&MI);
3584 
3585   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3586   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3587 
3588   assert(Idx->getReg() != AMDGPU::NoRegister);
3589 
3590   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3591     return false;
3592 
3593   if (UseGPRIdxMode) {
3594     unsigned IdxMode = IsIndirectSrc ?
3595       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3596     if (Offset == 0) {
3597       MachineInstr *SetOn =
3598           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3599               .add(*Idx)
3600               .addImm(IdxMode);
3601 
3602       SetOn->getOperand(3).setIsUndef();
3603     } else {
3604       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3605       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3606           .add(*Idx)
3607           .addImm(Offset);
3608       MachineInstr *SetOn =
3609         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3610         .addReg(Tmp, RegState::Kill)
3611         .addImm(IdxMode);
3612 
3613       SetOn->getOperand(3).setIsUndef();
3614     }
3615 
3616     return true;
3617   }
3618 
3619   if (Offset == 0) {
3620     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3621       .add(*Idx);
3622   } else {
3623     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3624       .add(*Idx)
3625       .addImm(Offset);
3626   }
3627 
3628   return true;
3629 }
3630 
3631 // Control flow needs to be inserted if indexing with a VGPR.
3632 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3633                                           MachineBasicBlock &MBB,
3634                                           const GCNSubtarget &ST) {
3635   const SIInstrInfo *TII = ST.getInstrInfo();
3636   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3637   MachineFunction *MF = MBB.getParent();
3638   MachineRegisterInfo &MRI = MF->getRegInfo();
3639 
3640   Register Dst = MI.getOperand(0).getReg();
3641   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3642   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3643 
3644   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3645 
3646   unsigned SubReg;
3647   std::tie(SubReg, Offset)
3648     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3649 
3650   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3651 
3652   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3653     MachineBasicBlock::iterator I(&MI);
3654     const DebugLoc &DL = MI.getDebugLoc();
3655 
3656     if (UseGPRIdxMode) {
3657       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3658       // to avoid interfering with other uses, so probably requires a new
3659       // optimization pass.
3660       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3661         .addReg(SrcReg, 0, SubReg)
3662         .addReg(SrcReg, RegState::Implicit)
3663         .addReg(AMDGPU::M0, RegState::Implicit);
3664       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3665     } else {
3666       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3667         .addReg(SrcReg, 0, SubReg)
3668         .addReg(SrcReg, RegState::Implicit);
3669     }
3670 
3671     MI.eraseFromParent();
3672 
3673     return &MBB;
3674   }
3675 
3676   const DebugLoc &DL = MI.getDebugLoc();
3677   MachineBasicBlock::iterator I(&MI);
3678 
3679   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3680   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3681 
3682   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3683 
3684   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3685                               Offset, UseGPRIdxMode, true);
3686   MachineBasicBlock *LoopBB = InsPt->getParent();
3687 
3688   if (UseGPRIdxMode) {
3689     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3690       .addReg(SrcReg, 0, SubReg)
3691       .addReg(SrcReg, RegState::Implicit)
3692       .addReg(AMDGPU::M0, RegState::Implicit);
3693     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3694   } else {
3695     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3696       .addReg(SrcReg, 0, SubReg)
3697       .addReg(SrcReg, RegState::Implicit);
3698   }
3699 
3700   MI.eraseFromParent();
3701 
3702   return LoopBB;
3703 }
3704 
3705 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3706                                           MachineBasicBlock &MBB,
3707                                           const GCNSubtarget &ST) {
3708   const SIInstrInfo *TII = ST.getInstrInfo();
3709   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3710   MachineFunction *MF = MBB.getParent();
3711   MachineRegisterInfo &MRI = MF->getRegInfo();
3712 
3713   Register Dst = MI.getOperand(0).getReg();
3714   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3715   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3716   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3717   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3718   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3719 
3720   // This can be an immediate, but will be folded later.
3721   assert(Val->getReg());
3722 
3723   unsigned SubReg;
3724   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3725                                                          SrcVec->getReg(),
3726                                                          Offset);
3727   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3728 
3729   if (Idx->getReg() == AMDGPU::NoRegister) {
3730     MachineBasicBlock::iterator I(&MI);
3731     const DebugLoc &DL = MI.getDebugLoc();
3732 
3733     assert(Offset == 0);
3734 
3735     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3736         .add(*SrcVec)
3737         .add(*Val)
3738         .addImm(SubReg);
3739 
3740     MI.eraseFromParent();
3741     return &MBB;
3742   }
3743 
3744   const MCInstrDesc &MovRelDesc
3745     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3746 
3747   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3748     MachineBasicBlock::iterator I(&MI);
3749     const DebugLoc &DL = MI.getDebugLoc();
3750     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3751       .addReg(SrcVec->getReg())
3752       .add(*Val)
3753       .addImm(SubReg);
3754     if (UseGPRIdxMode)
3755       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3756 
3757     MI.eraseFromParent();
3758     return &MBB;
3759   }
3760 
3761   if (Val->isReg())
3762     MRI.clearKillFlags(Val->getReg());
3763 
3764   const DebugLoc &DL = MI.getDebugLoc();
3765 
3766   Register PhiReg = MRI.createVirtualRegister(VecRC);
3767 
3768   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3769                               Offset, UseGPRIdxMode, false);
3770   MachineBasicBlock *LoopBB = InsPt->getParent();
3771 
3772   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3773     .addReg(PhiReg)
3774     .add(*Val)
3775     .addImm(AMDGPU::sub0);
3776   if (UseGPRIdxMode)
3777     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3778 
3779   MI.eraseFromParent();
3780   return LoopBB;
3781 }
3782 
3783 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3784   MachineInstr &MI, MachineBasicBlock *BB) const {
3785 
3786   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3787   MachineFunction *MF = BB->getParent();
3788   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3789 
3790   switch (MI.getOpcode()) {
3791   case AMDGPU::S_UADDO_PSEUDO:
3792   case AMDGPU::S_USUBO_PSEUDO: {
3793     const DebugLoc &DL = MI.getDebugLoc();
3794     MachineOperand &Dest0 = MI.getOperand(0);
3795     MachineOperand &Dest1 = MI.getOperand(1);
3796     MachineOperand &Src0 = MI.getOperand(2);
3797     MachineOperand &Src1 = MI.getOperand(3);
3798 
3799     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3800                        ? AMDGPU::S_ADD_I32
3801                        : AMDGPU::S_SUB_I32;
3802     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3803 
3804     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3805         .addImm(1)
3806         .addImm(0);
3807 
3808     MI.eraseFromParent();
3809     return BB;
3810   }
3811   case AMDGPU::S_ADD_U64_PSEUDO:
3812   case AMDGPU::S_SUB_U64_PSEUDO: {
3813     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3814     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3815     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3816     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3817     const DebugLoc &DL = MI.getDebugLoc();
3818 
3819     MachineOperand &Dest = MI.getOperand(0);
3820     MachineOperand &Src0 = MI.getOperand(1);
3821     MachineOperand &Src1 = MI.getOperand(2);
3822 
3823     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3824     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3825 
3826     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3827         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3828     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3829         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3830 
3831     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3832         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3833     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3834         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3835 
3836     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3837 
3838     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3839     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3840     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3841     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3842     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3843         .addReg(DestSub0)
3844         .addImm(AMDGPU::sub0)
3845         .addReg(DestSub1)
3846         .addImm(AMDGPU::sub1);
3847     MI.eraseFromParent();
3848     return BB;
3849   }
3850   case AMDGPU::V_ADD_U64_PSEUDO:
3851   case AMDGPU::V_SUB_U64_PSEUDO: {
3852     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3853     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3854     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3855     const DebugLoc &DL = MI.getDebugLoc();
3856 
3857     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3858 
3859     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3860 
3861     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3862     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3863 
3864     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3865     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3866 
3867     MachineOperand &Dest = MI.getOperand(0);
3868     MachineOperand &Src0 = MI.getOperand(1);
3869     MachineOperand &Src1 = MI.getOperand(2);
3870 
3871     const TargetRegisterClass *Src0RC = Src0.isReg()
3872                                             ? MRI.getRegClass(Src0.getReg())
3873                                             : &AMDGPU::VReg_64RegClass;
3874     const TargetRegisterClass *Src1RC = Src1.isReg()
3875                                             ? MRI.getRegClass(Src1.getReg())
3876                                             : &AMDGPU::VReg_64RegClass;
3877 
3878     const TargetRegisterClass *Src0SubRC =
3879         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3880     const TargetRegisterClass *Src1SubRC =
3881         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3882 
3883     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3884         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3885     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3886         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3887 
3888     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3889         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3890     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3891         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3892 
3893     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3894     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3895                                .addReg(CarryReg, RegState::Define)
3896                                .add(SrcReg0Sub0)
3897                                .add(SrcReg1Sub0)
3898                                .addImm(0); // clamp bit
3899 
3900     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3901     MachineInstr *HiHalf =
3902         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3903             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3904             .add(SrcReg0Sub1)
3905             .add(SrcReg1Sub1)
3906             .addReg(CarryReg, RegState::Kill)
3907             .addImm(0); // clamp bit
3908 
3909     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3910         .addReg(DestSub0)
3911         .addImm(AMDGPU::sub0)
3912         .addReg(DestSub1)
3913         .addImm(AMDGPU::sub1);
3914     TII->legalizeOperands(*LoHalf);
3915     TII->legalizeOperands(*HiHalf);
3916     MI.eraseFromParent();
3917     return BB;
3918   }
3919   case AMDGPU::S_ADD_CO_PSEUDO:
3920   case AMDGPU::S_SUB_CO_PSEUDO: {
3921     // This pseudo has a chance to be selected
3922     // only from uniform add/subcarry node. All the VGPR operands
3923     // therefore assumed to be splat vectors.
3924     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3925     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3926     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3927     MachineBasicBlock::iterator MII = MI;
3928     const DebugLoc &DL = MI.getDebugLoc();
3929     MachineOperand &Dest = MI.getOperand(0);
3930     MachineOperand &CarryDest = MI.getOperand(1);
3931     MachineOperand &Src0 = MI.getOperand(2);
3932     MachineOperand &Src1 = MI.getOperand(3);
3933     MachineOperand &Src2 = MI.getOperand(4);
3934     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3935                        ? AMDGPU::S_ADDC_U32
3936                        : AMDGPU::S_SUBB_U32;
3937     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3938       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3939       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3940           .addReg(Src0.getReg());
3941       Src0.setReg(RegOp0);
3942     }
3943     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3944       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3945       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3946           .addReg(Src1.getReg());
3947       Src1.setReg(RegOp1);
3948     }
3949     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3950     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3951       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3952           .addReg(Src2.getReg());
3953       Src2.setReg(RegOp2);
3954     }
3955 
3956     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
3957       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3958           .addReg(Src2.getReg())
3959           .addImm(0);
3960     } else {
3961       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
3962           .addReg(Src2.getReg())
3963           .addImm(0);
3964     }
3965 
3966     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
3967 
3968     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
3969       .addReg(AMDGPU::SCC);
3970     MI.eraseFromParent();
3971     return BB;
3972   }
3973   case AMDGPU::SI_INIT_M0: {
3974     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3975             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3976         .add(MI.getOperand(0));
3977     MI.eraseFromParent();
3978     return BB;
3979   }
3980   case AMDGPU::SI_INIT_EXEC:
3981     // This should be before all vector instructions.
3982     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3983             AMDGPU::EXEC)
3984         .addImm(MI.getOperand(0).getImm());
3985     MI.eraseFromParent();
3986     return BB;
3987 
3988   case AMDGPU::SI_INIT_EXEC_LO:
3989     // This should be before all vector instructions.
3990     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3991             AMDGPU::EXEC_LO)
3992         .addImm(MI.getOperand(0).getImm());
3993     MI.eraseFromParent();
3994     return BB;
3995 
3996   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3997     // Extract the thread count from an SGPR input and set EXEC accordingly.
3998     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3999     //
4000     // S_BFE_U32 count, input, {shift, 7}
4001     // S_BFM_B64 exec, count, 0
4002     // S_CMP_EQ_U32 count, 64
4003     // S_CMOV_B64 exec, -1
4004     MachineInstr *FirstMI = &*BB->begin();
4005     MachineRegisterInfo &MRI = MF->getRegInfo();
4006     Register InputReg = MI.getOperand(0).getReg();
4007     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4008     bool Found = false;
4009 
4010     // Move the COPY of the input reg to the beginning, so that we can use it.
4011     for (auto I = BB->begin(); I != &MI; I++) {
4012       if (I->getOpcode() != TargetOpcode::COPY ||
4013           I->getOperand(0).getReg() != InputReg)
4014         continue;
4015 
4016       if (I == FirstMI) {
4017         FirstMI = &*++BB->begin();
4018       } else {
4019         I->removeFromParent();
4020         BB->insert(FirstMI, &*I);
4021       }
4022       Found = true;
4023       break;
4024     }
4025     assert(Found);
4026     (void)Found;
4027 
4028     // This should be before all vector instructions.
4029     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
4030     bool isWave32 = getSubtarget()->isWave32();
4031     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4032     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
4033         .addReg(InputReg)
4034         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
4035     BuildMI(*BB, FirstMI, DebugLoc(),
4036             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
4037             Exec)
4038         .addReg(CountReg)
4039         .addImm(0);
4040     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
4041         .addReg(CountReg, RegState::Kill)
4042         .addImm(getSubtarget()->getWavefrontSize());
4043     BuildMI(*BB, FirstMI, DebugLoc(),
4044             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
4045             Exec)
4046         .addImm(-1);
4047     MI.eraseFromParent();
4048     return BB;
4049   }
4050 
4051   case AMDGPU::GET_GROUPSTATICSIZE: {
4052     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4053            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4054     DebugLoc DL = MI.getDebugLoc();
4055     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4056         .add(MI.getOperand(0))
4057         .addImm(MFI->getLDSSize());
4058     MI.eraseFromParent();
4059     return BB;
4060   }
4061   case AMDGPU::SI_INDIRECT_SRC_V1:
4062   case AMDGPU::SI_INDIRECT_SRC_V2:
4063   case AMDGPU::SI_INDIRECT_SRC_V4:
4064   case AMDGPU::SI_INDIRECT_SRC_V8:
4065   case AMDGPU::SI_INDIRECT_SRC_V16:
4066   case AMDGPU::SI_INDIRECT_SRC_V32:
4067     return emitIndirectSrc(MI, *BB, *getSubtarget());
4068   case AMDGPU::SI_INDIRECT_DST_V1:
4069   case AMDGPU::SI_INDIRECT_DST_V2:
4070   case AMDGPU::SI_INDIRECT_DST_V4:
4071   case AMDGPU::SI_INDIRECT_DST_V8:
4072   case AMDGPU::SI_INDIRECT_DST_V16:
4073   case AMDGPU::SI_INDIRECT_DST_V32:
4074     return emitIndirectDst(MI, *BB, *getSubtarget());
4075   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4076   case AMDGPU::SI_KILL_I1_PSEUDO:
4077     return splitKillBlock(MI, BB);
4078   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4079     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4080     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4081     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4082 
4083     Register Dst = MI.getOperand(0).getReg();
4084     Register Src0 = MI.getOperand(1).getReg();
4085     Register Src1 = MI.getOperand(2).getReg();
4086     const DebugLoc &DL = MI.getDebugLoc();
4087     Register SrcCond = MI.getOperand(3).getReg();
4088 
4089     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4090     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4091     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4092     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4093 
4094     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4095       .addReg(SrcCond);
4096     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4097       .addImm(0)
4098       .addReg(Src0, 0, AMDGPU::sub0)
4099       .addImm(0)
4100       .addReg(Src1, 0, AMDGPU::sub0)
4101       .addReg(SrcCondCopy);
4102     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4103       .addImm(0)
4104       .addReg(Src0, 0, AMDGPU::sub1)
4105       .addImm(0)
4106       .addReg(Src1, 0, AMDGPU::sub1)
4107       .addReg(SrcCondCopy);
4108 
4109     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4110       .addReg(DstLo)
4111       .addImm(AMDGPU::sub0)
4112       .addReg(DstHi)
4113       .addImm(AMDGPU::sub1);
4114     MI.eraseFromParent();
4115     return BB;
4116   }
4117   case AMDGPU::SI_BR_UNDEF: {
4118     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4119     const DebugLoc &DL = MI.getDebugLoc();
4120     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4121                            .add(MI.getOperand(0));
4122     Br->getOperand(1).setIsUndef(true); // read undef SCC
4123     MI.eraseFromParent();
4124     return BB;
4125   }
4126   case AMDGPU::ADJCALLSTACKUP:
4127   case AMDGPU::ADJCALLSTACKDOWN: {
4128     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4129     MachineInstrBuilder MIB(*MF, &MI);
4130 
4131     // Add an implicit use of the frame offset reg to prevent the restore copy
4132     // inserted after the call from being reorderd after stack operations in the
4133     // the caller's frame.
4134     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4135         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
4136         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
4137     return BB;
4138   }
4139   case AMDGPU::SI_CALL_ISEL: {
4140     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4141     const DebugLoc &DL = MI.getDebugLoc();
4142 
4143     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4144 
4145     MachineInstrBuilder MIB;
4146     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4147 
4148     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4149       MIB.add(MI.getOperand(I));
4150 
4151     MIB.cloneMemRefs(MI);
4152     MI.eraseFromParent();
4153     return BB;
4154   }
4155   case AMDGPU::V_ADD_CO_U32_e32:
4156   case AMDGPU::V_SUB_CO_U32_e32:
4157   case AMDGPU::V_SUBREV_CO_U32_e32: {
4158     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4159     const DebugLoc &DL = MI.getDebugLoc();
4160     unsigned Opc = MI.getOpcode();
4161 
4162     bool NeedClampOperand = false;
4163     if (TII->pseudoToMCOpcode(Opc) == -1) {
4164       Opc = AMDGPU::getVOPe64(Opc);
4165       NeedClampOperand = true;
4166     }
4167 
4168     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4169     if (TII->isVOP3(*I)) {
4170       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4171       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4172       I.addReg(TRI->getVCC(), RegState::Define);
4173     }
4174     I.add(MI.getOperand(1))
4175      .add(MI.getOperand(2));
4176     if (NeedClampOperand)
4177       I.addImm(0); // clamp bit for e64 encoding
4178 
4179     TII->legalizeOperands(*I);
4180 
4181     MI.eraseFromParent();
4182     return BB;
4183   }
4184   case AMDGPU::DS_GWS_INIT:
4185   case AMDGPU::DS_GWS_SEMA_V:
4186   case AMDGPU::DS_GWS_SEMA_BR:
4187   case AMDGPU::DS_GWS_SEMA_P:
4188   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4189   case AMDGPU::DS_GWS_BARRIER:
4190     // A s_waitcnt 0 is required to be the instruction immediately following.
4191     if (getSubtarget()->hasGWSAutoReplay()) {
4192       bundleInstWithWaitcnt(MI);
4193       return BB;
4194     }
4195 
4196     return emitGWSMemViolTestLoop(MI, BB);
4197   case AMDGPU::S_SETREG_B32: {
4198     if (!getSubtarget()->hasDenormModeInst())
4199       return BB;
4200 
4201     // Try to optimize cases that only set the denormal mode or rounding mode.
4202     //
4203     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4204     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4205     // instead.
4206     //
4207     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4208     // allow you to have a no side effect instruction in the output of a
4209     // sideeffecting pattern.
4210 
4211     // TODO: Should also emit a no side effects pseudo if only FP bits are
4212     // touched, even if not all of them or to a variable.
4213     unsigned ID, Offset, Width;
4214     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4215     if (ID != AMDGPU::Hwreg::ID_MODE)
4216       return BB;
4217 
4218     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4219     const unsigned SetMask = WidthMask << Offset;
4220     unsigned SetDenormOp = 0;
4221     unsigned SetRoundOp = 0;
4222 
4223     // The dedicated instructions can only set the whole denorm or round mode at
4224     // once, not a subset of bits in either.
4225     if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4226                                   AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) {
4227       // If this fully sets both the round and denorm mode, emit the two
4228       // dedicated instructions for these.
4229       assert(Offset == 0);
4230       SetRoundOp = AMDGPU::S_ROUND_MODE;
4231       SetDenormOp = AMDGPU::S_DENORM_MODE;
4232     } else if (Width == 4) {
4233       if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) {
4234         SetRoundOp = AMDGPU::S_ROUND_MODE;
4235         assert(Offset == 0);
4236       } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) {
4237         SetDenormOp = AMDGPU::S_DENORM_MODE;
4238         assert(Offset == 4);
4239       }
4240     }
4241 
4242     if (SetRoundOp || SetDenormOp) {
4243       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4244       MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4245       if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4246         unsigned ImmVal = Def->getOperand(1).getImm();
4247         if (SetRoundOp) {
4248           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4249             .addImm(ImmVal & 0xf);
4250 
4251           // If we also have the denorm mode, get just the denorm mode bits.
4252           ImmVal >>= 4;
4253         }
4254 
4255         if (SetDenormOp) {
4256           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4257             .addImm(ImmVal & 0xf);
4258         }
4259 
4260         MI.eraseFromParent();
4261       }
4262     }
4263 
4264     return BB;
4265   }
4266   default:
4267     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4268   }
4269 }
4270 
4271 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4272   return isTypeLegal(VT.getScalarType());
4273 }
4274 
4275 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4276   // This currently forces unfolding various combinations of fsub into fma with
4277   // free fneg'd operands. As long as we have fast FMA (controlled by
4278   // isFMAFasterThanFMulAndFAdd), we should perform these.
4279 
4280   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4281   // most of these combines appear to be cycle neutral but save on instruction
4282   // count / code size.
4283   return true;
4284 }
4285 
4286 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4287                                          EVT VT) const {
4288   if (!VT.isVector()) {
4289     return MVT::i1;
4290   }
4291   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4292 }
4293 
4294 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4295   // TODO: Should i16 be used always if legal? For now it would force VALU
4296   // shifts.
4297   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4298 }
4299 
4300 // Answering this is somewhat tricky and depends on the specific device which
4301 // have different rates for fma or all f64 operations.
4302 //
4303 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4304 // regardless of which device (although the number of cycles differs between
4305 // devices), so it is always profitable for f64.
4306 //
4307 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4308 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4309 // which we can always do even without fused FP ops since it returns the same
4310 // result as the separate operations and since it is always full
4311 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4312 // however does not support denormals, so we do report fma as faster if we have
4313 // a fast fma device and require denormals.
4314 //
4315 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4316                                                   EVT VT) const {
4317   VT = VT.getScalarType();
4318 
4319   switch (VT.getSimpleVT().SimpleTy) {
4320   case MVT::f32: {
4321     // If mad is not available this depends only on if f32 fma is full rate.
4322     if (!Subtarget->hasMadMacF32Insts())
4323       return Subtarget->hasFastFMAF32();
4324 
4325     // Otherwise f32 mad is always full rate and returns the same result as
4326     // the separate operations so should be preferred over fma.
4327     // However does not support denomals.
4328     if (hasFP32Denormals(MF))
4329       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4330 
4331     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4332     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4333   }
4334   case MVT::f64:
4335     return true;
4336   case MVT::f16:
4337     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4338   default:
4339     break;
4340   }
4341 
4342   return false;
4343 }
4344 
4345 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4346                                    const SDNode *N) const {
4347   // TODO: Check future ftz flag
4348   // v_mad_f32/v_mac_f32 do not support denormals.
4349   EVT VT = N->getValueType(0);
4350   if (VT == MVT::f32)
4351     return Subtarget->hasMadMacF32Insts() &&
4352            !hasFP32Denormals(DAG.getMachineFunction());
4353   if (VT == MVT::f16) {
4354     return Subtarget->hasMadF16() &&
4355            !hasFP64FP16Denormals(DAG.getMachineFunction());
4356   }
4357 
4358   return false;
4359 }
4360 
4361 //===----------------------------------------------------------------------===//
4362 // Custom DAG Lowering Operations
4363 //===----------------------------------------------------------------------===//
4364 
4365 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4366 // wider vector type is legal.
4367 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4368                                              SelectionDAG &DAG) const {
4369   unsigned Opc = Op.getOpcode();
4370   EVT VT = Op.getValueType();
4371   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4372 
4373   SDValue Lo, Hi;
4374   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4375 
4376   SDLoc SL(Op);
4377   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4378                              Op->getFlags());
4379   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4380                              Op->getFlags());
4381 
4382   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4383 }
4384 
4385 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4386 // wider vector type is legal.
4387 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4388                                               SelectionDAG &DAG) const {
4389   unsigned Opc = Op.getOpcode();
4390   EVT VT = Op.getValueType();
4391   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4392 
4393   SDValue Lo0, Hi0;
4394   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4395   SDValue Lo1, Hi1;
4396   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4397 
4398   SDLoc SL(Op);
4399 
4400   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4401                              Op->getFlags());
4402   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4403                              Op->getFlags());
4404 
4405   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4406 }
4407 
4408 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4409                                               SelectionDAG &DAG) const {
4410   unsigned Opc = Op.getOpcode();
4411   EVT VT = Op.getValueType();
4412   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4413 
4414   SDValue Lo0, Hi0;
4415   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4416   SDValue Lo1, Hi1;
4417   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4418   SDValue Lo2, Hi2;
4419   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4420 
4421   SDLoc SL(Op);
4422 
4423   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4424                              Op->getFlags());
4425   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4426                              Op->getFlags());
4427 
4428   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4429 }
4430 
4431 
4432 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4433   switch (Op.getOpcode()) {
4434   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4435   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4436   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4437   case ISD::LOAD: {
4438     SDValue Result = LowerLOAD(Op, DAG);
4439     assert((!Result.getNode() ||
4440             Result.getNode()->getNumValues() == 2) &&
4441            "Load should return a value and a chain");
4442     return Result;
4443   }
4444 
4445   case ISD::FSIN:
4446   case ISD::FCOS:
4447     return LowerTrig(Op, DAG);
4448   case ISD::SELECT: return LowerSELECT(Op, DAG);
4449   case ISD::FDIV: return LowerFDIV(Op, DAG);
4450   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4451   case ISD::STORE: return LowerSTORE(Op, DAG);
4452   case ISD::GlobalAddress: {
4453     MachineFunction &MF = DAG.getMachineFunction();
4454     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4455     return LowerGlobalAddress(MFI, Op, DAG);
4456   }
4457   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4458   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4459   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4460   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4461   case ISD::INSERT_SUBVECTOR:
4462     return lowerINSERT_SUBVECTOR(Op, DAG);
4463   case ISD::INSERT_VECTOR_ELT:
4464     return lowerINSERT_VECTOR_ELT(Op, DAG);
4465   case ISD::EXTRACT_VECTOR_ELT:
4466     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4467   case ISD::VECTOR_SHUFFLE:
4468     return lowerVECTOR_SHUFFLE(Op, DAG);
4469   case ISD::BUILD_VECTOR:
4470     return lowerBUILD_VECTOR(Op, DAG);
4471   case ISD::FP_ROUND:
4472     return lowerFP_ROUND(Op, DAG);
4473   case ISD::TRAP:
4474     return lowerTRAP(Op, DAG);
4475   case ISD::DEBUGTRAP:
4476     return lowerDEBUGTRAP(Op, DAG);
4477   case ISD::FABS:
4478   case ISD::FNEG:
4479   case ISD::FCANONICALIZE:
4480   case ISD::BSWAP:
4481     return splitUnaryVectorOp(Op, DAG);
4482   case ISD::FMINNUM:
4483   case ISD::FMAXNUM:
4484     return lowerFMINNUM_FMAXNUM(Op, DAG);
4485   case ISD::FMA:
4486     return splitTernaryVectorOp(Op, DAG);
4487   case ISD::SHL:
4488   case ISD::SRA:
4489   case ISD::SRL:
4490   case ISD::ADD:
4491   case ISD::SUB:
4492   case ISD::MUL:
4493   case ISD::SMIN:
4494   case ISD::SMAX:
4495   case ISD::UMIN:
4496   case ISD::UMAX:
4497   case ISD::FADD:
4498   case ISD::FMUL:
4499   case ISD::FMINNUM_IEEE:
4500   case ISD::FMAXNUM_IEEE:
4501   case ISD::UADDSAT:
4502   case ISD::USUBSAT:
4503   case ISD::SADDSAT:
4504   case ISD::SSUBSAT:
4505     return splitBinaryVectorOp(Op, DAG);
4506   case ISD::SMULO:
4507   case ISD::UMULO:
4508     return lowerXMULO(Op, DAG);
4509   case ISD::DYNAMIC_STACKALLOC:
4510     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4511   }
4512   return SDValue();
4513 }
4514 
4515 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4516                                        const SDLoc &DL,
4517                                        SelectionDAG &DAG, bool Unpacked) {
4518   if (!LoadVT.isVector())
4519     return Result;
4520 
4521   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4522     // Truncate to v2i16/v4i16.
4523     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4524 
4525     // Workaround legalizer not scalarizing truncate after vector op
4526     // legalization but not creating intermediate vector trunc.
4527     SmallVector<SDValue, 4> Elts;
4528     DAG.ExtractVectorElements(Result, Elts);
4529     for (SDValue &Elt : Elts)
4530       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4531 
4532     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4533 
4534     // Bitcast to original type (v2f16/v4f16).
4535     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4536   }
4537 
4538   // Cast back to the original packed type.
4539   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4540 }
4541 
4542 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4543                                               MemSDNode *M,
4544                                               SelectionDAG &DAG,
4545                                               ArrayRef<SDValue> Ops,
4546                                               bool IsIntrinsic) const {
4547   SDLoc DL(M);
4548 
4549   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4550   EVT LoadVT = M->getValueType(0);
4551 
4552   EVT EquivLoadVT = LoadVT;
4553   if (Unpacked && LoadVT.isVector()) {
4554     EquivLoadVT = LoadVT.isVector() ?
4555       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4556                        LoadVT.getVectorNumElements()) : LoadVT;
4557   }
4558 
4559   // Change from v4f16/v2f16 to EquivLoadVT.
4560   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4561 
4562   SDValue Load
4563     = DAG.getMemIntrinsicNode(
4564       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4565       VTList, Ops, M->getMemoryVT(),
4566       M->getMemOperand());
4567   if (!Unpacked) // Just adjusted the opcode.
4568     return Load;
4569 
4570   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4571 
4572   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4573 }
4574 
4575 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4576                                              SelectionDAG &DAG,
4577                                              ArrayRef<SDValue> Ops) const {
4578   SDLoc DL(M);
4579   EVT LoadVT = M->getValueType(0);
4580   EVT EltType = LoadVT.getScalarType();
4581   EVT IntVT = LoadVT.changeTypeToInteger();
4582 
4583   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4584 
4585   unsigned Opc =
4586       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4587 
4588   if (IsD16) {
4589     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4590   }
4591 
4592   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4593   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4594     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4595 
4596   if (isTypeLegal(LoadVT)) {
4597     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4598                                M->getMemOperand(), DAG);
4599   }
4600 
4601   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4602   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4603   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4604                                         M->getMemOperand(), DAG);
4605   return DAG.getMergeValues(
4606       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4607       DL);
4608 }
4609 
4610 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4611                                   SDNode *N, SelectionDAG &DAG) {
4612   EVT VT = N->getValueType(0);
4613   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4614   unsigned CondCode = CD->getZExtValue();
4615   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4616     return DAG.getUNDEF(VT);
4617 
4618   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4619 
4620   SDValue LHS = N->getOperand(1);
4621   SDValue RHS = N->getOperand(2);
4622 
4623   SDLoc DL(N);
4624 
4625   EVT CmpVT = LHS.getValueType();
4626   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4627     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4628       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4629     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4630     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4631   }
4632 
4633   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4634 
4635   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4636   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4637 
4638   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4639                               DAG.getCondCode(CCOpcode));
4640   if (VT.bitsEq(CCVT))
4641     return SetCC;
4642   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4643 }
4644 
4645 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4646                                   SDNode *N, SelectionDAG &DAG) {
4647   EVT VT = N->getValueType(0);
4648   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4649 
4650   unsigned CondCode = CD->getZExtValue();
4651   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4652     return DAG.getUNDEF(VT);
4653 
4654   SDValue Src0 = N->getOperand(1);
4655   SDValue Src1 = N->getOperand(2);
4656   EVT CmpVT = Src0.getValueType();
4657   SDLoc SL(N);
4658 
4659   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4660     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4661     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4662   }
4663 
4664   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4665   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4666   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4667   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4668   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4669                               Src1, DAG.getCondCode(CCOpcode));
4670   if (VT.bitsEq(CCVT))
4671     return SetCC;
4672   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4673 }
4674 
4675 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4676                                     SelectionDAG &DAG) {
4677   EVT VT = N->getValueType(0);
4678   SDValue Src = N->getOperand(1);
4679   SDLoc SL(N);
4680 
4681   if (Src.getOpcode() == ISD::SETCC) {
4682     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4683     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4684                        Src.getOperand(1), Src.getOperand(2));
4685   }
4686   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4687     // (ballot 0) -> 0
4688     if (Arg->isNullValue())
4689       return DAG.getConstant(0, SL, VT);
4690 
4691     // (ballot 1) -> EXEC/EXEC_LO
4692     if (Arg->isOne()) {
4693       Register Exec;
4694       if (VT.getScalarSizeInBits() == 32)
4695         Exec = AMDGPU::EXEC_LO;
4696       else if (VT.getScalarSizeInBits() == 64)
4697         Exec = AMDGPU::EXEC;
4698       else
4699         return SDValue();
4700 
4701       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4702     }
4703   }
4704 
4705   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4706   // ISD::SETNE)
4707   return DAG.getNode(
4708       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4709       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4710 }
4711 
4712 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4713                                           SmallVectorImpl<SDValue> &Results,
4714                                           SelectionDAG &DAG) const {
4715   switch (N->getOpcode()) {
4716   case ISD::INSERT_VECTOR_ELT: {
4717     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4718       Results.push_back(Res);
4719     return;
4720   }
4721   case ISD::EXTRACT_VECTOR_ELT: {
4722     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4723       Results.push_back(Res);
4724     return;
4725   }
4726   case ISD::INTRINSIC_WO_CHAIN: {
4727     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4728     switch (IID) {
4729     case Intrinsic::amdgcn_cvt_pkrtz: {
4730       SDValue Src0 = N->getOperand(1);
4731       SDValue Src1 = N->getOperand(2);
4732       SDLoc SL(N);
4733       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4734                                 Src0, Src1);
4735       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4736       return;
4737     }
4738     case Intrinsic::amdgcn_cvt_pknorm_i16:
4739     case Intrinsic::amdgcn_cvt_pknorm_u16:
4740     case Intrinsic::amdgcn_cvt_pk_i16:
4741     case Intrinsic::amdgcn_cvt_pk_u16: {
4742       SDValue Src0 = N->getOperand(1);
4743       SDValue Src1 = N->getOperand(2);
4744       SDLoc SL(N);
4745       unsigned Opcode;
4746 
4747       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4748         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4749       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4750         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4751       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4752         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4753       else
4754         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4755 
4756       EVT VT = N->getValueType(0);
4757       if (isTypeLegal(VT))
4758         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4759       else {
4760         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4761         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4762       }
4763       return;
4764     }
4765     }
4766     break;
4767   }
4768   case ISD::INTRINSIC_W_CHAIN: {
4769     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4770       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4771         // FIXME: Hacky
4772         Results.push_back(Res.getOperand(0));
4773         Results.push_back(Res.getOperand(1));
4774       } else {
4775         Results.push_back(Res);
4776         Results.push_back(Res.getValue(1));
4777       }
4778       return;
4779     }
4780 
4781     break;
4782   }
4783   case ISD::SELECT: {
4784     SDLoc SL(N);
4785     EVT VT = N->getValueType(0);
4786     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4787     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4788     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4789 
4790     EVT SelectVT = NewVT;
4791     if (NewVT.bitsLT(MVT::i32)) {
4792       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4793       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4794       SelectVT = MVT::i32;
4795     }
4796 
4797     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4798                                     N->getOperand(0), LHS, RHS);
4799 
4800     if (NewVT != SelectVT)
4801       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4802     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4803     return;
4804   }
4805   case ISD::FNEG: {
4806     if (N->getValueType(0) != MVT::v2f16)
4807       break;
4808 
4809     SDLoc SL(N);
4810     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4811 
4812     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4813                              BC,
4814                              DAG.getConstant(0x80008000, SL, MVT::i32));
4815     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4816     return;
4817   }
4818   case ISD::FABS: {
4819     if (N->getValueType(0) != MVT::v2f16)
4820       break;
4821 
4822     SDLoc SL(N);
4823     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4824 
4825     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4826                              BC,
4827                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4828     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4829     return;
4830   }
4831   default:
4832     break;
4833   }
4834 }
4835 
4836 /// Helper function for LowerBRCOND
4837 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4838 
4839   SDNode *Parent = Value.getNode();
4840   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4841        I != E; ++I) {
4842 
4843     if (I.getUse().get() != Value)
4844       continue;
4845 
4846     if (I->getOpcode() == Opcode)
4847       return *I;
4848   }
4849   return nullptr;
4850 }
4851 
4852 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4853   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4854     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4855     case Intrinsic::amdgcn_if:
4856       return AMDGPUISD::IF;
4857     case Intrinsic::amdgcn_else:
4858       return AMDGPUISD::ELSE;
4859     case Intrinsic::amdgcn_loop:
4860       return AMDGPUISD::LOOP;
4861     case Intrinsic::amdgcn_end_cf:
4862       llvm_unreachable("should not occur");
4863     default:
4864       return 0;
4865     }
4866   }
4867 
4868   // break, if_break, else_break are all only used as inputs to loop, not
4869   // directly as branch conditions.
4870   return 0;
4871 }
4872 
4873 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4874   const Triple &TT = getTargetMachine().getTargetTriple();
4875   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4876           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4877          AMDGPU::shouldEmitConstantsToTextSection(TT);
4878 }
4879 
4880 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4881   // FIXME: Either avoid relying on address space here or change the default
4882   // address space for functions to avoid the explicit check.
4883   return (GV->getValueType()->isFunctionTy() ||
4884           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4885          !shouldEmitFixup(GV) &&
4886          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4887 }
4888 
4889 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4890   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4891 }
4892 
4893 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4894   if (!GV->hasExternalLinkage())
4895     return true;
4896 
4897   const auto OS = getTargetMachine().getTargetTriple().getOS();
4898   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4899 }
4900 
4901 /// This transforms the control flow intrinsics to get the branch destination as
4902 /// last parameter, also switches branch target with BR if the need arise
4903 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4904                                       SelectionDAG &DAG) const {
4905   SDLoc DL(BRCOND);
4906 
4907   SDNode *Intr = BRCOND.getOperand(1).getNode();
4908   SDValue Target = BRCOND.getOperand(2);
4909   SDNode *BR = nullptr;
4910   SDNode *SetCC = nullptr;
4911 
4912   if (Intr->getOpcode() == ISD::SETCC) {
4913     // As long as we negate the condition everything is fine
4914     SetCC = Intr;
4915     Intr = SetCC->getOperand(0).getNode();
4916 
4917   } else {
4918     // Get the target from BR if we don't negate the condition
4919     BR = findUser(BRCOND, ISD::BR);
4920     assert(BR && "brcond missing unconditional branch user");
4921     Target = BR->getOperand(1);
4922   }
4923 
4924   unsigned CFNode = isCFIntrinsic(Intr);
4925   if (CFNode == 0) {
4926     // This is a uniform branch so we don't need to legalize.
4927     return BRCOND;
4928   }
4929 
4930   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4931                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4932 
4933   assert(!SetCC ||
4934         (SetCC->getConstantOperandVal(1) == 1 &&
4935          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4936                                                              ISD::SETNE));
4937 
4938   // operands of the new intrinsic call
4939   SmallVector<SDValue, 4> Ops;
4940   if (HaveChain)
4941     Ops.push_back(BRCOND.getOperand(0));
4942 
4943   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4944   Ops.push_back(Target);
4945 
4946   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4947 
4948   // build the new intrinsic call
4949   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4950 
4951   if (!HaveChain) {
4952     SDValue Ops[] =  {
4953       SDValue(Result, 0),
4954       BRCOND.getOperand(0)
4955     };
4956 
4957     Result = DAG.getMergeValues(Ops, DL).getNode();
4958   }
4959 
4960   if (BR) {
4961     // Give the branch instruction our target
4962     SDValue Ops[] = {
4963       BR->getOperand(0),
4964       BRCOND.getOperand(2)
4965     };
4966     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4967     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4968   }
4969 
4970   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4971 
4972   // Copy the intrinsic results to registers
4973   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4974     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4975     if (!CopyToReg)
4976       continue;
4977 
4978     Chain = DAG.getCopyToReg(
4979       Chain, DL,
4980       CopyToReg->getOperand(1),
4981       SDValue(Result, i - 1),
4982       SDValue());
4983 
4984     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4985   }
4986 
4987   // Remove the old intrinsic from the chain
4988   DAG.ReplaceAllUsesOfValueWith(
4989     SDValue(Intr, Intr->getNumValues() - 1),
4990     Intr->getOperand(0));
4991 
4992   return Chain;
4993 }
4994 
4995 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4996                                           SelectionDAG &DAG) const {
4997   MVT VT = Op.getSimpleValueType();
4998   SDLoc DL(Op);
4999   // Checking the depth
5000   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5001     return DAG.getConstant(0, DL, VT);
5002 
5003   MachineFunction &MF = DAG.getMachineFunction();
5004   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5005   // Check for kernel and shader functions
5006   if (Info->isEntryFunction())
5007     return DAG.getConstant(0, DL, VT);
5008 
5009   MachineFrameInfo &MFI = MF.getFrameInfo();
5010   // There is a call to @llvm.returnaddress in this function
5011   MFI.setReturnAddressIsTaken(true);
5012 
5013   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5014   // Get the return address reg and mark it as an implicit live-in
5015   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5016 
5017   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5018 }
5019 
5020 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5021                                             SDValue Op,
5022                                             const SDLoc &DL,
5023                                             EVT VT) const {
5024   return Op.getValueType().bitsLE(VT) ?
5025       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5026     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5027                 DAG.getTargetConstant(0, DL, MVT::i32));
5028 }
5029 
5030 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5031   assert(Op.getValueType() == MVT::f16 &&
5032          "Do not know how to custom lower FP_ROUND for non-f16 type");
5033 
5034   SDValue Src = Op.getOperand(0);
5035   EVT SrcVT = Src.getValueType();
5036   if (SrcVT != MVT::f64)
5037     return Op;
5038 
5039   SDLoc DL(Op);
5040 
5041   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5042   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5043   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5044 }
5045 
5046 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5047                                                SelectionDAG &DAG) const {
5048   EVT VT = Op.getValueType();
5049   const MachineFunction &MF = DAG.getMachineFunction();
5050   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5051   bool IsIEEEMode = Info->getMode().IEEE;
5052 
5053   // FIXME: Assert during selection that this is only selected for
5054   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5055   // mode functions, but this happens to be OK since it's only done in cases
5056   // where there is known no sNaN.
5057   if (IsIEEEMode)
5058     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5059 
5060   if (VT == MVT::v4f16)
5061     return splitBinaryVectorOp(Op, DAG);
5062   return Op;
5063 }
5064 
5065 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5066   EVT VT = Op.getValueType();
5067   SDLoc SL(Op);
5068   SDValue LHS = Op.getOperand(0);
5069   SDValue RHS = Op.getOperand(1);
5070   bool isSigned = Op.getOpcode() == ISD::SMULO;
5071 
5072   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5073     const APInt &C = RHSC->getAPIntValue();
5074     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5075     if (C.isPowerOf2()) {
5076       // smulo(x, signed_min) is same as umulo(x, signed_min).
5077       bool UseArithShift = isSigned && !C.isMinSignedValue();
5078       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5079       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5080       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5081           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5082                       SL, VT, Result, ShiftAmt),
5083           LHS, ISD::SETNE);
5084       return DAG.getMergeValues({ Result, Overflow }, SL);
5085     }
5086   }
5087 
5088   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5089   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5090                             SL, VT, LHS, RHS);
5091 
5092   SDValue Sign = isSigned
5093     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5094                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5095     : DAG.getConstant(0, SL, VT);
5096   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5097 
5098   return DAG.getMergeValues({ Result, Overflow }, SL);
5099 }
5100 
5101 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5102   SDLoc SL(Op);
5103   SDValue Chain = Op.getOperand(0);
5104 
5105   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5106       !Subtarget->isTrapHandlerEnabled())
5107     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5108 
5109   MachineFunction &MF = DAG.getMachineFunction();
5110   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5111   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
5112   assert(UserSGPR != AMDGPU::NoRegister);
5113   SDValue QueuePtr = CreateLiveInRegister(
5114     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5115   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5116   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5117                                    QueuePtr, SDValue());
5118   SDValue Ops[] = {
5119     ToReg,
5120     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5121     SGPR01,
5122     ToReg.getValue(1)
5123   };
5124   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5125 }
5126 
5127 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5128   SDLoc SL(Op);
5129   SDValue Chain = Op.getOperand(0);
5130   MachineFunction &MF = DAG.getMachineFunction();
5131 
5132   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5133       !Subtarget->isTrapHandlerEnabled()) {
5134     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5135                                      "debugtrap handler not supported",
5136                                      Op.getDebugLoc(),
5137                                      DS_Warning);
5138     LLVMContext &Ctx = MF.getFunction().getContext();
5139     Ctx.diagnose(NoTrap);
5140     return Chain;
5141   }
5142 
5143   SDValue Ops[] = {
5144     Chain,
5145     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5146   };
5147   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5148 }
5149 
5150 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5151                                              SelectionDAG &DAG) const {
5152   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5153   if (Subtarget->hasApertureRegs()) {
5154     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5155         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5156         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5157     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5158         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5159         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5160     unsigned Encoding =
5161         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5162         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5163         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5164 
5165     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5166     SDValue ApertureReg = SDValue(
5167         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5168     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5169     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5170   }
5171 
5172   MachineFunction &MF = DAG.getMachineFunction();
5173   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5174   Register UserSGPR = Info->getQueuePtrUserSGPR();
5175   assert(UserSGPR != AMDGPU::NoRegister);
5176 
5177   SDValue QueuePtr = CreateLiveInRegister(
5178     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5179 
5180   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5181   // private_segment_aperture_base_hi.
5182   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5183 
5184   SDValue Ptr =
5185       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5186 
5187   // TODO: Use custom target PseudoSourceValue.
5188   // TODO: We should use the value from the IR intrinsic call, but it might not
5189   // be available and how do we get it?
5190   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5191   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5192                      MinAlign(64, StructOffset),
5193                      MachineMemOperand::MODereferenceable |
5194                          MachineMemOperand::MOInvariant);
5195 }
5196 
5197 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5198                                              SelectionDAG &DAG) const {
5199   SDLoc SL(Op);
5200   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5201 
5202   SDValue Src = ASC->getOperand(0);
5203   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5204 
5205   const AMDGPUTargetMachine &TM =
5206     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5207 
5208   // flat -> local/private
5209   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5210     unsigned DestAS = ASC->getDestAddressSpace();
5211 
5212     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5213         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5214       unsigned NullVal = TM.getNullPointerValue(DestAS);
5215       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5216       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5217       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5218 
5219       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5220                          NonNull, Ptr, SegmentNullPtr);
5221     }
5222   }
5223 
5224   // local/private -> flat
5225   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5226     unsigned SrcAS = ASC->getSrcAddressSpace();
5227 
5228     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5229         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5230       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5231       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5232 
5233       SDValue NonNull
5234         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5235 
5236       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5237       SDValue CvtPtr
5238         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5239 
5240       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5241                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5242                          FlatNullPtr);
5243     }
5244   }
5245 
5246   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5247       Src.getValueType() == MVT::i64)
5248     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5249 
5250   // global <-> flat are no-ops and never emitted.
5251 
5252   const MachineFunction &MF = DAG.getMachineFunction();
5253   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5254     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5255   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5256 
5257   return DAG.getUNDEF(ASC->getValueType(0));
5258 }
5259 
5260 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5261 // the small vector and inserting them into the big vector. That is better than
5262 // the default expansion of doing it via a stack slot. Even though the use of
5263 // the stack slot would be optimized away afterwards, the stack slot itself
5264 // remains.
5265 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5266                                                 SelectionDAG &DAG) const {
5267   SDValue Vec = Op.getOperand(0);
5268   SDValue Ins = Op.getOperand(1);
5269   SDValue Idx = Op.getOperand(2);
5270   EVT VecVT = Vec.getValueType();
5271   EVT InsVT = Ins.getValueType();
5272   EVT EltVT = VecVT.getVectorElementType();
5273   unsigned InsNumElts = InsVT.getVectorNumElements();
5274   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5275   SDLoc SL(Op);
5276 
5277   for (unsigned I = 0; I != InsNumElts; ++I) {
5278     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5279                               DAG.getConstant(I, SL, MVT::i32));
5280     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5281                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5282   }
5283   return Vec;
5284 }
5285 
5286 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5287                                                  SelectionDAG &DAG) const {
5288   SDValue Vec = Op.getOperand(0);
5289   SDValue InsVal = Op.getOperand(1);
5290   SDValue Idx = Op.getOperand(2);
5291   EVT VecVT = Vec.getValueType();
5292   EVT EltVT = VecVT.getVectorElementType();
5293   unsigned VecSize = VecVT.getSizeInBits();
5294   unsigned EltSize = EltVT.getSizeInBits();
5295 
5296 
5297   assert(VecSize <= 64);
5298 
5299   unsigned NumElts = VecVT.getVectorNumElements();
5300   SDLoc SL(Op);
5301   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5302 
5303   if (NumElts == 4 && EltSize == 16 && KIdx) {
5304     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5305 
5306     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5307                                  DAG.getConstant(0, SL, MVT::i32));
5308     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5309                                  DAG.getConstant(1, SL, MVT::i32));
5310 
5311     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5312     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5313 
5314     unsigned Idx = KIdx->getZExtValue();
5315     bool InsertLo = Idx < 2;
5316     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5317       InsertLo ? LoVec : HiVec,
5318       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5319       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5320 
5321     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5322 
5323     SDValue Concat = InsertLo ?
5324       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5325       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5326 
5327     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5328   }
5329 
5330   if (isa<ConstantSDNode>(Idx))
5331     return SDValue();
5332 
5333   MVT IntVT = MVT::getIntegerVT(VecSize);
5334 
5335   // Avoid stack access for dynamic indexing.
5336   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5337 
5338   // Create a congruent vector with the target value in each element so that
5339   // the required element can be masked and ORed into the target vector.
5340   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5341                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5342 
5343   assert(isPowerOf2_32(EltSize));
5344   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5345 
5346   // Convert vector index to bit-index.
5347   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5348 
5349   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5350   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5351                             DAG.getConstant(0xffff, SL, IntVT),
5352                             ScaledIdx);
5353 
5354   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5355   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5356                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5357 
5358   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5359   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5360 }
5361 
5362 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5363                                                   SelectionDAG &DAG) const {
5364   SDLoc SL(Op);
5365 
5366   EVT ResultVT = Op.getValueType();
5367   SDValue Vec = Op.getOperand(0);
5368   SDValue Idx = Op.getOperand(1);
5369   EVT VecVT = Vec.getValueType();
5370   unsigned VecSize = VecVT.getSizeInBits();
5371   EVT EltVT = VecVT.getVectorElementType();
5372   assert(VecSize <= 64);
5373 
5374   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5375 
5376   // Make sure we do any optimizations that will make it easier to fold
5377   // source modifiers before obscuring it with bit operations.
5378 
5379   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5380   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5381     return Combined;
5382 
5383   unsigned EltSize = EltVT.getSizeInBits();
5384   assert(isPowerOf2_32(EltSize));
5385 
5386   MVT IntVT = MVT::getIntegerVT(VecSize);
5387   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5388 
5389   // Convert vector index to bit-index (* EltSize)
5390   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5391 
5392   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5393   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5394 
5395   if (ResultVT == MVT::f16) {
5396     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5397     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5398   }
5399 
5400   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5401 }
5402 
5403 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5404   assert(Elt % 2 == 0);
5405   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5406 }
5407 
5408 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5409                                               SelectionDAG &DAG) const {
5410   SDLoc SL(Op);
5411   EVT ResultVT = Op.getValueType();
5412   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5413 
5414   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5415   EVT EltVT = PackVT.getVectorElementType();
5416   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5417 
5418   // vector_shuffle <0,1,6,7> lhs, rhs
5419   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5420   //
5421   // vector_shuffle <6,7,2,3> lhs, rhs
5422   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5423   //
5424   // vector_shuffle <6,7,0,1> lhs, rhs
5425   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5426 
5427   // Avoid scalarizing when both halves are reading from consecutive elements.
5428   SmallVector<SDValue, 4> Pieces;
5429   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5430     if (elementPairIsContiguous(SVN->getMask(), I)) {
5431       const int Idx = SVN->getMaskElt(I);
5432       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5433       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5434       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5435                                     PackVT, SVN->getOperand(VecIdx),
5436                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5437       Pieces.push_back(SubVec);
5438     } else {
5439       const int Idx0 = SVN->getMaskElt(I);
5440       const int Idx1 = SVN->getMaskElt(I + 1);
5441       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5442       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5443       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5444       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5445 
5446       SDValue Vec0 = SVN->getOperand(VecIdx0);
5447       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5448                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5449 
5450       SDValue Vec1 = SVN->getOperand(VecIdx1);
5451       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5452                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5453       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5454     }
5455   }
5456 
5457   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5458 }
5459 
5460 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5461                                             SelectionDAG &DAG) const {
5462   SDLoc SL(Op);
5463   EVT VT = Op.getValueType();
5464 
5465   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5466     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5467 
5468     // Turn into pair of packed build_vectors.
5469     // TODO: Special case for constants that can be materialized with s_mov_b64.
5470     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5471                                     { Op.getOperand(0), Op.getOperand(1) });
5472     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5473                                     { Op.getOperand(2), Op.getOperand(3) });
5474 
5475     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5476     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5477 
5478     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5479     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5480   }
5481 
5482   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5483   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5484 
5485   SDValue Lo = Op.getOperand(0);
5486   SDValue Hi = Op.getOperand(1);
5487 
5488   // Avoid adding defined bits with the zero_extend.
5489   if (Hi.isUndef()) {
5490     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5491     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5492     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5493   }
5494 
5495   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5496   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5497 
5498   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5499                               DAG.getConstant(16, SL, MVT::i32));
5500   if (Lo.isUndef())
5501     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5502 
5503   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5504   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5505 
5506   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5507   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5508 }
5509 
5510 bool
5511 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5512   // We can fold offsets for anything that doesn't require a GOT relocation.
5513   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5514           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5515           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5516          !shouldEmitGOTReloc(GA->getGlobal());
5517 }
5518 
5519 static SDValue
5520 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5521                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5522                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5523   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5524   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5525   // lowered to the following code sequence:
5526   //
5527   // For constant address space:
5528   //   s_getpc_b64 s[0:1]
5529   //   s_add_u32 s0, s0, $symbol
5530   //   s_addc_u32 s1, s1, 0
5531   //
5532   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5533   //   a fixup or relocation is emitted to replace $symbol with a literal
5534   //   constant, which is a pc-relative offset from the encoding of the $symbol
5535   //   operand to the global variable.
5536   //
5537   // For global address space:
5538   //   s_getpc_b64 s[0:1]
5539   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5540   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5541   //
5542   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5543   //   fixups or relocations are emitted to replace $symbol@*@lo and
5544   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5545   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5546   //   operand to the global variable.
5547   //
5548   // What we want here is an offset from the value returned by s_getpc
5549   // (which is the address of the s_add_u32 instruction) to the global
5550   // variable, but since the encoding of $symbol starts 4 bytes after the start
5551   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5552   // small. This requires us to add 4 to the global variable offset in order to
5553   // compute the correct address.
5554   SDValue PtrLo =
5555       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5556   SDValue PtrHi;
5557   if (GAFlags == SIInstrInfo::MO_NONE) {
5558     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5559   } else {
5560     PtrHi =
5561         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5562   }
5563   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5564 }
5565 
5566 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5567                                              SDValue Op,
5568                                              SelectionDAG &DAG) const {
5569   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5570   const GlobalValue *GV = GSD->getGlobal();
5571   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5572        shouldUseLDSConstAddress(GV)) ||
5573       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5574       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5575     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5576 
5577   SDLoc DL(GSD);
5578   EVT PtrVT = Op.getValueType();
5579 
5580   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5581     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5582                                             SIInstrInfo::MO_ABS32_LO);
5583     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5584   }
5585 
5586   if (shouldEmitFixup(GV))
5587     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5588   else if (shouldEmitPCReloc(GV))
5589     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5590                                    SIInstrInfo::MO_REL32);
5591 
5592   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5593                                             SIInstrInfo::MO_GOTPCREL32);
5594 
5595   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5596   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5597   const DataLayout &DataLayout = DAG.getDataLayout();
5598   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5599   MachinePointerInfo PtrInfo
5600     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5601 
5602   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5603                      MachineMemOperand::MODereferenceable |
5604                          MachineMemOperand::MOInvariant);
5605 }
5606 
5607 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5608                                    const SDLoc &DL, SDValue V) const {
5609   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5610   // the destination register.
5611   //
5612   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5613   // so we will end up with redundant moves to m0.
5614   //
5615   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5616 
5617   // A Null SDValue creates a glue result.
5618   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5619                                   V, Chain);
5620   return SDValue(M0, 0);
5621 }
5622 
5623 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5624                                                  SDValue Op,
5625                                                  MVT VT,
5626                                                  unsigned Offset) const {
5627   SDLoc SL(Op);
5628   SDValue Param = lowerKernargMemParameter(
5629       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5630   // The local size values will have the hi 16-bits as zero.
5631   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5632                      DAG.getValueType(VT));
5633 }
5634 
5635 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5636                                         EVT VT) {
5637   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5638                                       "non-hsa intrinsic with hsa target",
5639                                       DL.getDebugLoc());
5640   DAG.getContext()->diagnose(BadIntrin);
5641   return DAG.getUNDEF(VT);
5642 }
5643 
5644 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5645                                          EVT VT) {
5646   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5647                                       "intrinsic not supported on subtarget",
5648                                       DL.getDebugLoc());
5649   DAG.getContext()->diagnose(BadIntrin);
5650   return DAG.getUNDEF(VT);
5651 }
5652 
5653 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5654                                     ArrayRef<SDValue> Elts) {
5655   assert(!Elts.empty());
5656   MVT Type;
5657   unsigned NumElts;
5658 
5659   if (Elts.size() == 1) {
5660     Type = MVT::f32;
5661     NumElts = 1;
5662   } else if (Elts.size() == 2) {
5663     Type = MVT::v2f32;
5664     NumElts = 2;
5665   } else if (Elts.size() == 3) {
5666     Type = MVT::v3f32;
5667     NumElts = 3;
5668   } else if (Elts.size() <= 4) {
5669     Type = MVT::v4f32;
5670     NumElts = 4;
5671   } else if (Elts.size() <= 8) {
5672     Type = MVT::v8f32;
5673     NumElts = 8;
5674   } else {
5675     assert(Elts.size() <= 16);
5676     Type = MVT::v16f32;
5677     NumElts = 16;
5678   }
5679 
5680   SmallVector<SDValue, 16> VecElts(NumElts);
5681   for (unsigned i = 0; i < Elts.size(); ++i) {
5682     SDValue Elt = Elts[i];
5683     if (Elt.getValueType() != MVT::f32)
5684       Elt = DAG.getBitcast(MVT::f32, Elt);
5685     VecElts[i] = Elt;
5686   }
5687   for (unsigned i = Elts.size(); i < NumElts; ++i)
5688     VecElts[i] = DAG.getUNDEF(MVT::f32);
5689 
5690   if (NumElts == 1)
5691     return VecElts[0];
5692   return DAG.getBuildVector(Type, DL, VecElts);
5693 }
5694 
5695 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5696                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5697   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5698 
5699   uint64_t Value = CachePolicyConst->getZExtValue();
5700   SDLoc DL(CachePolicy);
5701   if (GLC) {
5702     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5703     Value &= ~(uint64_t)0x1;
5704   }
5705   if (SLC) {
5706     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5707     Value &= ~(uint64_t)0x2;
5708   }
5709   if (DLC) {
5710     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5711     Value &= ~(uint64_t)0x4;
5712   }
5713 
5714   return Value == 0;
5715 }
5716 
5717 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5718                               SDValue Src, int ExtraElts) {
5719   EVT SrcVT = Src.getValueType();
5720 
5721   SmallVector<SDValue, 8> Elts;
5722 
5723   if (SrcVT.isVector())
5724     DAG.ExtractVectorElements(Src, Elts);
5725   else
5726     Elts.push_back(Src);
5727 
5728   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5729   while (ExtraElts--)
5730     Elts.push_back(Undef);
5731 
5732   return DAG.getBuildVector(CastVT, DL, Elts);
5733 }
5734 
5735 // Re-construct the required return value for a image load intrinsic.
5736 // This is more complicated due to the optional use TexFailCtrl which means the required
5737 // return type is an aggregate
5738 static SDValue constructRetValue(SelectionDAG &DAG,
5739                                  MachineSDNode *Result,
5740                                  ArrayRef<EVT> ResultTypes,
5741                                  bool IsTexFail, bool Unpacked, bool IsD16,
5742                                  int DMaskPop, int NumVDataDwords,
5743                                  const SDLoc &DL, LLVMContext &Context) {
5744   // Determine the required return type. This is the same regardless of IsTexFail flag
5745   EVT ReqRetVT = ResultTypes[0];
5746   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5747   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5748     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5749 
5750   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5751     DMaskPop : (DMaskPop + 1) / 2;
5752 
5753   MVT DataDwordVT = NumDataDwords == 1 ?
5754     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5755 
5756   MVT MaskPopVT = MaskPopDwords == 1 ?
5757     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5758 
5759   SDValue Data(Result, 0);
5760   SDValue TexFail;
5761 
5762   if (IsTexFail) {
5763     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5764     if (MaskPopVT.isVector()) {
5765       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5766                          SDValue(Result, 0), ZeroIdx);
5767     } else {
5768       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5769                          SDValue(Result, 0), ZeroIdx);
5770     }
5771 
5772     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5773                           SDValue(Result, 0),
5774                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5775   }
5776 
5777   if (DataDwordVT.isVector())
5778     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5779                           NumDataDwords - MaskPopDwords);
5780 
5781   if (IsD16)
5782     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5783 
5784   if (!ReqRetVT.isVector())
5785     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5786 
5787   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5788 
5789   if (TexFail)
5790     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5791 
5792   if (Result->getNumValues() == 1)
5793     return Data;
5794 
5795   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5796 }
5797 
5798 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5799                          SDValue *LWE, bool &IsTexFail) {
5800   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5801 
5802   uint64_t Value = TexFailCtrlConst->getZExtValue();
5803   if (Value) {
5804     IsTexFail = true;
5805   }
5806 
5807   SDLoc DL(TexFailCtrlConst);
5808   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5809   Value &= ~(uint64_t)0x1;
5810   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5811   Value &= ~(uint64_t)0x2;
5812 
5813   return Value == 0;
5814 }
5815 
5816 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5817                                         MVT PackVectorVT,
5818                                         SmallVectorImpl<SDValue> &PackedAddrs,
5819                                         unsigned DimIdx, unsigned EndIdx,
5820                                         unsigned NumGradients) {
5821   SDLoc DL(Op);
5822   for (unsigned I = DimIdx; I < EndIdx; I++) {
5823     SDValue Addr = Op.getOperand(I);
5824 
5825     // Gradients are packed with undef for each coordinate.
5826     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5827     // 1D: undef,dx/dh; undef,dx/dv
5828     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5829     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5830     if (((I + 1) >= EndIdx) ||
5831         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5832                                          I == DimIdx + NumGradients - 1))) {
5833       if (Addr.getValueType() != MVT::i16)
5834         Addr = DAG.getBitcast(MVT::i16, Addr);
5835       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5836     } else {
5837       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5838       I++;
5839     }
5840     Addr = DAG.getBitcast(MVT::f32, Addr);
5841     PackedAddrs.push_back(Addr);
5842   }
5843 }
5844 
5845 SDValue SITargetLowering::lowerImage(SDValue Op,
5846                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5847                                      SelectionDAG &DAG) const {
5848   SDLoc DL(Op);
5849   MachineFunction &MF = DAG.getMachineFunction();
5850   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5851   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5852       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5853   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5854   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5855       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5856   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5857       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5858   unsigned IntrOpcode = Intr->BaseOpcode;
5859   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5860 
5861   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5862   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5863   bool IsD16 = false;
5864   bool IsG16 = false;
5865   bool IsA16 = false;
5866   SDValue VData;
5867   int NumVDataDwords;
5868   bool AdjustRetType = false;
5869 
5870   unsigned AddrIdx; // Index of first address argument
5871   unsigned DMask;
5872   unsigned DMaskLanes = 0;
5873 
5874   if (BaseOpcode->Atomic) {
5875     VData = Op.getOperand(2);
5876 
5877     bool Is64Bit = VData.getValueType() == MVT::i64;
5878     if (BaseOpcode->AtomicX2) {
5879       SDValue VData2 = Op.getOperand(3);
5880       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5881                                  {VData, VData2});
5882       if (Is64Bit)
5883         VData = DAG.getBitcast(MVT::v4i32, VData);
5884 
5885       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5886       DMask = Is64Bit ? 0xf : 0x3;
5887       NumVDataDwords = Is64Bit ? 4 : 2;
5888       AddrIdx = 4;
5889     } else {
5890       DMask = Is64Bit ? 0x3 : 0x1;
5891       NumVDataDwords = Is64Bit ? 2 : 1;
5892       AddrIdx = 3;
5893     }
5894   } else {
5895     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5896     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5897     DMask = DMaskConst->getZExtValue();
5898     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5899 
5900     if (BaseOpcode->Store) {
5901       VData = Op.getOperand(2);
5902 
5903       MVT StoreVT = VData.getSimpleValueType();
5904       if (StoreVT.getScalarType() == MVT::f16) {
5905         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5906           return Op; // D16 is unsupported for this instruction
5907 
5908         IsD16 = true;
5909         VData = handleD16VData(VData, DAG);
5910       }
5911 
5912       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5913     } else {
5914       // Work out the num dwords based on the dmask popcount and underlying type
5915       // and whether packing is supported.
5916       MVT LoadVT = ResultTypes[0].getSimpleVT();
5917       if (LoadVT.getScalarType() == MVT::f16) {
5918         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5919           return Op; // D16 is unsupported for this instruction
5920 
5921         IsD16 = true;
5922       }
5923 
5924       // Confirm that the return type is large enough for the dmask specified
5925       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5926           (!LoadVT.isVector() && DMaskLanes > 1))
5927           return Op;
5928 
5929       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5930         NumVDataDwords = (DMaskLanes + 1) / 2;
5931       else
5932         NumVDataDwords = DMaskLanes;
5933 
5934       AdjustRetType = true;
5935     }
5936 
5937     AddrIdx = DMaskIdx + 1;
5938   }
5939 
5940   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5941   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5942   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5943   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5944                        NumCoords + NumLCM;
5945   unsigned NumMIVAddrs = NumVAddrs;
5946 
5947   SmallVector<SDValue, 4> VAddrs;
5948 
5949   // Optimize _L to _LZ when _L is zero
5950   if (LZMappingInfo) {
5951     if (auto ConstantLod =
5952          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5953       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5954         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5955         NumMIVAddrs--;               // remove 'lod'
5956       }
5957     }
5958   }
5959 
5960   // Optimize _mip away, when 'lod' is zero
5961   if (MIPMappingInfo) {
5962     if (auto ConstantLod =
5963          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5964       if (ConstantLod->isNullValue()) {
5965         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5966         NumMIVAddrs--;               // remove 'lod'
5967       }
5968     }
5969   }
5970 
5971   // Push back extra arguments.
5972   for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++)
5973     VAddrs.push_back(Op.getOperand(AddrIdx + I));
5974 
5975   // Check for 16 bit addresses or derivatives and pack if true.
5976   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5977   unsigned CoordIdx = DimIdx + NumGradients;
5978   unsigned CoordsEnd = AddrIdx + NumMIVAddrs;
5979 
5980   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5981   MVT VAddrScalarVT = VAddrVT.getScalarType();
5982   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5983   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
5984 
5985   VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType();
5986   VAddrScalarVT = VAddrVT.getScalarType();
5987   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
5988   if (IsA16 || IsG16) {
5989     if (IsA16) {
5990       if (!ST->hasA16()) {
5991         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
5992                              "support 16 bit addresses\n");
5993         return Op;
5994       }
5995       if (!IsG16) {
5996         LLVM_DEBUG(
5997             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
5998                       "need 16 bit derivatives but got 32 bit derivatives\n");
5999         return Op;
6000       }
6001     } else if (!ST->hasG16()) {
6002       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6003                            "support 16 bit derivatives\n");
6004       return Op;
6005     }
6006 
6007     if (BaseOpcode->Gradients && !IsA16) {
6008       if (!ST->hasG16()) {
6009         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6010                              "support 16 bit derivatives\n");
6011         return Op;
6012       }
6013       // Activate g16
6014       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6015           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6016       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6017     }
6018 
6019     // Don't compress addresses for G16
6020     const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx;
6021     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx,
6022                                 PackEndIdx, NumGradients);
6023 
6024     if (!IsA16) {
6025       // Add uncompressed address
6026       for (unsigned I = CoordIdx; I < CoordsEnd; I++)
6027         VAddrs.push_back(Op.getOperand(I));
6028     }
6029   } else {
6030     for (unsigned I = DimIdx; I < CoordsEnd; I++)
6031       VAddrs.push_back(Op.getOperand(I));
6032   }
6033 
6034   // If the register allocator cannot place the address registers contiguously
6035   // without introducing moves, then using the non-sequential address encoding
6036   // is always preferable, since it saves VALU instructions and is usually a
6037   // wash in terms of code size or even better.
6038   //
6039   // However, we currently have no way of hinting to the register allocator that
6040   // MIMG addresses should be placed contiguously when it is possible to do so,
6041   // so force non-NSA for the common 2-address case as a heuristic.
6042   //
6043   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6044   // allocation when possible.
6045   bool UseNSA =
6046       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6047   SDValue VAddr;
6048   if (!UseNSA)
6049     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6050 
6051   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6052   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6053   unsigned CtrlIdx; // Index of texfailctrl argument
6054   SDValue Unorm;
6055   if (!BaseOpcode->Sampler) {
6056     Unorm = True;
6057     CtrlIdx = AddrIdx + NumVAddrs + 1;
6058   } else {
6059     auto UnormConst =
6060         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
6061 
6062     Unorm = UnormConst->getZExtValue() ? True : False;
6063     CtrlIdx = AddrIdx + NumVAddrs + 3;
6064   }
6065 
6066   SDValue TFE;
6067   SDValue LWE;
6068   SDValue TexFail = Op.getOperand(CtrlIdx);
6069   bool IsTexFail = false;
6070   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6071     return Op;
6072 
6073   if (IsTexFail) {
6074     if (!DMaskLanes) {
6075       // Expecting to get an error flag since TFC is on - and dmask is 0
6076       // Force dmask to be at least 1 otherwise the instruction will fail
6077       DMask = 0x1;
6078       DMaskLanes = 1;
6079       NumVDataDwords = 1;
6080     }
6081     NumVDataDwords += 1;
6082     AdjustRetType = true;
6083   }
6084 
6085   // Has something earlier tagged that the return type needs adjusting
6086   // This happens if the instruction is a load or has set TexFailCtrl flags
6087   if (AdjustRetType) {
6088     // NumVDataDwords reflects the true number of dwords required in the return type
6089     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6090       // This is a no-op load. This can be eliminated
6091       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6092       if (isa<MemSDNode>(Op))
6093         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6094       return Undef;
6095     }
6096 
6097     EVT NewVT = NumVDataDwords > 1 ?
6098                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6099                 : MVT::i32;
6100 
6101     ResultTypes[0] = NewVT;
6102     if (ResultTypes.size() == 3) {
6103       // Original result was aggregate type used for TexFailCtrl results
6104       // The actual instruction returns as a vector type which has now been
6105       // created. Remove the aggregate result.
6106       ResultTypes.erase(&ResultTypes[1]);
6107     }
6108   }
6109 
6110   SDValue GLC;
6111   SDValue SLC;
6112   SDValue DLC;
6113   if (BaseOpcode->Atomic) {
6114     GLC = True; // TODO no-return optimization
6115     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
6116                           IsGFX10 ? &DLC : nullptr))
6117       return Op;
6118   } else {
6119     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
6120                           IsGFX10 ? &DLC : nullptr))
6121       return Op;
6122   }
6123 
6124   SmallVector<SDValue, 26> Ops;
6125   if (BaseOpcode->Store || BaseOpcode->Atomic)
6126     Ops.push_back(VData); // vdata
6127   if (UseNSA) {
6128     for (const SDValue &Addr : VAddrs)
6129       Ops.push_back(Addr);
6130   } else {
6131     Ops.push_back(VAddr);
6132   }
6133   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
6134   if (BaseOpcode->Sampler)
6135     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
6136   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6137   if (IsGFX10)
6138     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6139   Ops.push_back(Unorm);
6140   if (IsGFX10)
6141     Ops.push_back(DLC);
6142   Ops.push_back(GLC);
6143   Ops.push_back(SLC);
6144   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6145                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6146   if (IsGFX10)
6147     Ops.push_back(IsA16 ? True : False);
6148   Ops.push_back(TFE);
6149   Ops.push_back(LWE);
6150   if (!IsGFX10)
6151     Ops.push_back(DimInfo->DA ? True : False);
6152   if (BaseOpcode->HasD16)
6153     Ops.push_back(IsD16 ? True : False);
6154   if (isa<MemSDNode>(Op))
6155     Ops.push_back(Op.getOperand(0)); // chain
6156 
6157   int NumVAddrDwords =
6158       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6159   int Opcode = -1;
6160 
6161   if (IsGFX10) {
6162     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6163                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6164                                           : AMDGPU::MIMGEncGfx10Default,
6165                                    NumVDataDwords, NumVAddrDwords);
6166   } else {
6167     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6168       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6169                                      NumVDataDwords, NumVAddrDwords);
6170     if (Opcode == -1)
6171       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6172                                      NumVDataDwords, NumVAddrDwords);
6173   }
6174   assert(Opcode != -1);
6175 
6176   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6177   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6178     MachineMemOperand *MemRef = MemOp->getMemOperand();
6179     DAG.setNodeMemRefs(NewNode, {MemRef});
6180   }
6181 
6182   if (BaseOpcode->AtomicX2) {
6183     SmallVector<SDValue, 1> Elt;
6184     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6185     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6186   } else if (!BaseOpcode->Store) {
6187     return constructRetValue(DAG, NewNode,
6188                              OrigResultTypes, IsTexFail,
6189                              Subtarget->hasUnpackedD16VMem(), IsD16,
6190                              DMaskLanes, NumVDataDwords, DL,
6191                              *DAG.getContext());
6192   }
6193 
6194   return SDValue(NewNode, 0);
6195 }
6196 
6197 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6198                                        SDValue Offset, SDValue CachePolicy,
6199                                        SelectionDAG &DAG) const {
6200   MachineFunction &MF = DAG.getMachineFunction();
6201 
6202   const DataLayout &DataLayout = DAG.getDataLayout();
6203   Align Alignment =
6204       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6205 
6206   MachineMemOperand *MMO = MF.getMachineMemOperand(
6207       MachinePointerInfo(),
6208       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6209           MachineMemOperand::MOInvariant,
6210       VT.getStoreSize(), Alignment);
6211 
6212   if (!Offset->isDivergent()) {
6213     SDValue Ops[] = {
6214         Rsrc,
6215         Offset, // Offset
6216         CachePolicy
6217     };
6218 
6219     // Widen vec3 load to vec4.
6220     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6221       EVT WidenedVT =
6222           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6223       auto WidenedOp = DAG.getMemIntrinsicNode(
6224           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6225           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6226       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6227                                    DAG.getVectorIdxConstant(0, DL));
6228       return Subvector;
6229     }
6230 
6231     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6232                                    DAG.getVTList(VT), Ops, VT, MMO);
6233   }
6234 
6235   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6236   // assume that the buffer is unswizzled.
6237   SmallVector<SDValue, 4> Loads;
6238   unsigned NumLoads = 1;
6239   MVT LoadVT = VT.getSimpleVT();
6240   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6241   assert((LoadVT.getScalarType() == MVT::i32 ||
6242           LoadVT.getScalarType() == MVT::f32));
6243 
6244   if (NumElts == 8 || NumElts == 16) {
6245     NumLoads = NumElts / 4;
6246     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6247   }
6248 
6249   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6250   SDValue Ops[] = {
6251       DAG.getEntryNode(),                               // Chain
6252       Rsrc,                                             // rsrc
6253       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6254       {},                                               // voffset
6255       {},                                               // soffset
6256       {},                                               // offset
6257       CachePolicy,                                      // cachepolicy
6258       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6259   };
6260 
6261   // Use the alignment to ensure that the required offsets will fit into the
6262   // immediate offsets.
6263   setBufferOffsets(Offset, DAG, &Ops[3],
6264                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6265 
6266   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6267   for (unsigned i = 0; i < NumLoads; ++i) {
6268     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6269     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6270                                         LoadVT, MMO, DAG));
6271   }
6272 
6273   if (NumElts == 8 || NumElts == 16)
6274     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6275 
6276   return Loads[0];
6277 }
6278 
6279 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6280                                                   SelectionDAG &DAG) const {
6281   MachineFunction &MF = DAG.getMachineFunction();
6282   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6283 
6284   EVT VT = Op.getValueType();
6285   SDLoc DL(Op);
6286   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6287 
6288   // TODO: Should this propagate fast-math-flags?
6289 
6290   switch (IntrinsicID) {
6291   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6292     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6293       return emitNonHSAIntrinsicError(DAG, DL, VT);
6294     return getPreloadedValue(DAG, *MFI, VT,
6295                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6296   }
6297   case Intrinsic::amdgcn_dispatch_ptr:
6298   case Intrinsic::amdgcn_queue_ptr: {
6299     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6300       DiagnosticInfoUnsupported BadIntrin(
6301           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6302           DL.getDebugLoc());
6303       DAG.getContext()->diagnose(BadIntrin);
6304       return DAG.getUNDEF(VT);
6305     }
6306 
6307     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6308       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6309     return getPreloadedValue(DAG, *MFI, VT, RegID);
6310   }
6311   case Intrinsic::amdgcn_implicitarg_ptr: {
6312     if (MFI->isEntryFunction())
6313       return getImplicitArgPtr(DAG, DL);
6314     return getPreloadedValue(DAG, *MFI, VT,
6315                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6316   }
6317   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6318     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6319       // This only makes sense to call in a kernel, so just lower to null.
6320       return DAG.getConstant(0, DL, VT);
6321     }
6322 
6323     return getPreloadedValue(DAG, *MFI, VT,
6324                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6325   }
6326   case Intrinsic::amdgcn_dispatch_id: {
6327     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6328   }
6329   case Intrinsic::amdgcn_rcp:
6330     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6331   case Intrinsic::amdgcn_rsq:
6332     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6333   case Intrinsic::amdgcn_rsq_legacy:
6334     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6335       return emitRemovedIntrinsicError(DAG, DL, VT);
6336     return SDValue();
6337   case Intrinsic::amdgcn_rcp_legacy:
6338     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6339       return emitRemovedIntrinsicError(DAG, DL, VT);
6340     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6341   case Intrinsic::amdgcn_rsq_clamp: {
6342     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6343       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6344 
6345     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6346     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6347     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6348 
6349     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6350     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6351                               DAG.getConstantFP(Max, DL, VT));
6352     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6353                        DAG.getConstantFP(Min, DL, VT));
6354   }
6355   case Intrinsic::r600_read_ngroups_x:
6356     if (Subtarget->isAmdHsaOS())
6357       return emitNonHSAIntrinsicError(DAG, DL, VT);
6358 
6359     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6360                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6361                                     false);
6362   case Intrinsic::r600_read_ngroups_y:
6363     if (Subtarget->isAmdHsaOS())
6364       return emitNonHSAIntrinsicError(DAG, DL, VT);
6365 
6366     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6367                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6368                                     false);
6369   case Intrinsic::r600_read_ngroups_z:
6370     if (Subtarget->isAmdHsaOS())
6371       return emitNonHSAIntrinsicError(DAG, DL, VT);
6372 
6373     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6374                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6375                                     false);
6376   case Intrinsic::r600_read_global_size_x:
6377     if (Subtarget->isAmdHsaOS())
6378       return emitNonHSAIntrinsicError(DAG, DL, VT);
6379 
6380     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6381                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6382                                     Align(4), false);
6383   case Intrinsic::r600_read_global_size_y:
6384     if (Subtarget->isAmdHsaOS())
6385       return emitNonHSAIntrinsicError(DAG, DL, VT);
6386 
6387     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6388                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6389                                     Align(4), false);
6390   case Intrinsic::r600_read_global_size_z:
6391     if (Subtarget->isAmdHsaOS())
6392       return emitNonHSAIntrinsicError(DAG, DL, VT);
6393 
6394     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6395                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6396                                     Align(4), false);
6397   case Intrinsic::r600_read_local_size_x:
6398     if (Subtarget->isAmdHsaOS())
6399       return emitNonHSAIntrinsicError(DAG, DL, VT);
6400 
6401     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6402                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6403   case Intrinsic::r600_read_local_size_y:
6404     if (Subtarget->isAmdHsaOS())
6405       return emitNonHSAIntrinsicError(DAG, DL, VT);
6406 
6407     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6408                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6409   case Intrinsic::r600_read_local_size_z:
6410     if (Subtarget->isAmdHsaOS())
6411       return emitNonHSAIntrinsicError(DAG, DL, VT);
6412 
6413     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6414                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6415   case Intrinsic::amdgcn_workgroup_id_x:
6416     return getPreloadedValue(DAG, *MFI, VT,
6417                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6418   case Intrinsic::amdgcn_workgroup_id_y:
6419     return getPreloadedValue(DAG, *MFI, VT,
6420                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6421   case Intrinsic::amdgcn_workgroup_id_z:
6422     return getPreloadedValue(DAG, *MFI, VT,
6423                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6424   case Intrinsic::amdgcn_workitem_id_x:
6425     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6426                           SDLoc(DAG.getEntryNode()),
6427                           MFI->getArgInfo().WorkItemIDX);
6428   case Intrinsic::amdgcn_workitem_id_y:
6429     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6430                           SDLoc(DAG.getEntryNode()),
6431                           MFI->getArgInfo().WorkItemIDY);
6432   case Intrinsic::amdgcn_workitem_id_z:
6433     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6434                           SDLoc(DAG.getEntryNode()),
6435                           MFI->getArgInfo().WorkItemIDZ);
6436   case Intrinsic::amdgcn_wavefrontsize:
6437     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6438                            SDLoc(Op), MVT::i32);
6439   case Intrinsic::amdgcn_s_buffer_load: {
6440     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6441     SDValue GLC;
6442     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6443     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6444                           IsGFX10 ? &DLC : nullptr))
6445       return Op;
6446     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6447                         DAG);
6448   }
6449   case Intrinsic::amdgcn_fdiv_fast:
6450     return lowerFDIV_FAST(Op, DAG);
6451   case Intrinsic::amdgcn_sin:
6452     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6453 
6454   case Intrinsic::amdgcn_cos:
6455     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6456 
6457   case Intrinsic::amdgcn_mul_u24:
6458     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6459   case Intrinsic::amdgcn_mul_i24:
6460     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6461 
6462   case Intrinsic::amdgcn_log_clamp: {
6463     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6464       return SDValue();
6465 
6466     DiagnosticInfoUnsupported BadIntrin(
6467       MF.getFunction(), "intrinsic not supported on subtarget",
6468       DL.getDebugLoc());
6469       DAG.getContext()->diagnose(BadIntrin);
6470       return DAG.getUNDEF(VT);
6471   }
6472   case Intrinsic::amdgcn_ldexp:
6473     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6474                        Op.getOperand(1), Op.getOperand(2));
6475 
6476   case Intrinsic::amdgcn_fract:
6477     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6478 
6479   case Intrinsic::amdgcn_class:
6480     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6481                        Op.getOperand(1), Op.getOperand(2));
6482   case Intrinsic::amdgcn_div_fmas:
6483     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6484                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6485                        Op.getOperand(4));
6486 
6487   case Intrinsic::amdgcn_div_fixup:
6488     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6489                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6490 
6491   case Intrinsic::amdgcn_div_scale: {
6492     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6493 
6494     // Translate to the operands expected by the machine instruction. The
6495     // first parameter must be the same as the first instruction.
6496     SDValue Numerator = Op.getOperand(1);
6497     SDValue Denominator = Op.getOperand(2);
6498 
6499     // Note this order is opposite of the machine instruction's operations,
6500     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6501     // intrinsic has the numerator as the first operand to match a normal
6502     // division operation.
6503 
6504     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6505 
6506     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6507                        Denominator, Numerator);
6508   }
6509   case Intrinsic::amdgcn_icmp: {
6510     // There is a Pat that handles this variant, so return it as-is.
6511     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6512         Op.getConstantOperandVal(2) == 0 &&
6513         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6514       return Op;
6515     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6516   }
6517   case Intrinsic::amdgcn_fcmp: {
6518     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6519   }
6520   case Intrinsic::amdgcn_ballot:
6521     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6522   case Intrinsic::amdgcn_fmed3:
6523     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6524                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6525   case Intrinsic::amdgcn_fdot2:
6526     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6527                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6528                        Op.getOperand(4));
6529   case Intrinsic::amdgcn_fmul_legacy:
6530     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6531                        Op.getOperand(1), Op.getOperand(2));
6532   case Intrinsic::amdgcn_sffbh:
6533     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6534   case Intrinsic::amdgcn_sbfe:
6535     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6536                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6537   case Intrinsic::amdgcn_ubfe:
6538     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6539                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6540   case Intrinsic::amdgcn_cvt_pkrtz:
6541   case Intrinsic::amdgcn_cvt_pknorm_i16:
6542   case Intrinsic::amdgcn_cvt_pknorm_u16:
6543   case Intrinsic::amdgcn_cvt_pk_i16:
6544   case Intrinsic::amdgcn_cvt_pk_u16: {
6545     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6546     EVT VT = Op.getValueType();
6547     unsigned Opcode;
6548 
6549     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6550       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6551     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6552       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6553     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6554       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6555     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6556       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6557     else
6558       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6559 
6560     if (isTypeLegal(VT))
6561       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6562 
6563     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6564                                Op.getOperand(1), Op.getOperand(2));
6565     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6566   }
6567   case Intrinsic::amdgcn_fmad_ftz:
6568     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6569                        Op.getOperand(2), Op.getOperand(3));
6570 
6571   case Intrinsic::amdgcn_if_break:
6572     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6573                                       Op->getOperand(1), Op->getOperand(2)), 0);
6574 
6575   case Intrinsic::amdgcn_groupstaticsize: {
6576     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6577     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6578       return Op;
6579 
6580     const Module *M = MF.getFunction().getParent();
6581     const GlobalValue *GV =
6582         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6583     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6584                                             SIInstrInfo::MO_ABS32_LO);
6585     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6586   }
6587   case Intrinsic::amdgcn_is_shared:
6588   case Intrinsic::amdgcn_is_private: {
6589     SDLoc SL(Op);
6590     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6591       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6592     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6593     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6594                                  Op.getOperand(1));
6595 
6596     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6597                                 DAG.getConstant(1, SL, MVT::i32));
6598     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6599   }
6600   case Intrinsic::amdgcn_alignbit:
6601     return DAG.getNode(ISD::FSHR, DL, VT,
6602                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6603   case Intrinsic::amdgcn_reloc_constant: {
6604     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6605     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6606     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6607     auto RelocSymbol = cast<GlobalVariable>(
6608         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6609     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6610                                             SIInstrInfo::MO_ABS32_LO);
6611     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6612   }
6613   default:
6614     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6615             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6616       return lowerImage(Op, ImageDimIntr, DAG);
6617 
6618     return Op;
6619   }
6620 }
6621 
6622 // This function computes an appropriate offset to pass to
6623 // MachineMemOperand::setOffset() based on the offset inputs to
6624 // an intrinsic.  If any of the offsets are non-contstant or
6625 // if VIndex is non-zero then this function returns 0.  Otherwise,
6626 // it returns the sum of VOffset, SOffset, and Offset.
6627 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6628                                       SDValue SOffset,
6629                                       SDValue Offset,
6630                                       SDValue VIndex = SDValue()) {
6631 
6632   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6633       !isa<ConstantSDNode>(Offset))
6634     return 0;
6635 
6636   if (VIndex) {
6637     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6638       return 0;
6639   }
6640 
6641   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6642          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6643          cast<ConstantSDNode>(Offset)->getSExtValue();
6644 }
6645 
6646 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6647                                                      SelectionDAG &DAG,
6648                                                      unsigned NewOpcode) const {
6649   SDLoc DL(Op);
6650 
6651   SDValue VData = Op.getOperand(2);
6652   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6653   SDValue Ops[] = {
6654     Op.getOperand(0), // Chain
6655     VData,            // vdata
6656     Op.getOperand(3), // rsrc
6657     DAG.getConstant(0, DL, MVT::i32), // vindex
6658     Offsets.first,    // voffset
6659     Op.getOperand(5), // soffset
6660     Offsets.second,   // offset
6661     Op.getOperand(6), // cachepolicy
6662     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6663   };
6664 
6665   auto *M = cast<MemSDNode>(Op);
6666   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6667 
6668   EVT MemVT = VData.getValueType();
6669   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6670                                  M->getMemOperand());
6671 }
6672 
6673 SDValue
6674 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6675                                                 unsigned NewOpcode) const {
6676   SDLoc DL(Op);
6677 
6678   SDValue VData = Op.getOperand(2);
6679   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6680   SDValue Ops[] = {
6681     Op.getOperand(0), // Chain
6682     VData,            // vdata
6683     Op.getOperand(3), // rsrc
6684     Op.getOperand(4), // vindex
6685     Offsets.first,    // voffset
6686     Op.getOperand(6), // soffset
6687     Offsets.second,   // offset
6688     Op.getOperand(7), // cachepolicy
6689     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6690   };
6691 
6692   auto *M = cast<MemSDNode>(Op);
6693   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6694                                                       Ops[3]));
6695 
6696   EVT MemVT = VData.getValueType();
6697   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6698                                  M->getMemOperand());
6699 }
6700 
6701 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6702                                                  SelectionDAG &DAG) const {
6703   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6704   SDLoc DL(Op);
6705 
6706   switch (IntrID) {
6707   case Intrinsic::amdgcn_ds_ordered_add:
6708   case Intrinsic::amdgcn_ds_ordered_swap: {
6709     MemSDNode *M = cast<MemSDNode>(Op);
6710     SDValue Chain = M->getOperand(0);
6711     SDValue M0 = M->getOperand(2);
6712     SDValue Value = M->getOperand(3);
6713     unsigned IndexOperand = M->getConstantOperandVal(7);
6714     unsigned WaveRelease = M->getConstantOperandVal(8);
6715     unsigned WaveDone = M->getConstantOperandVal(9);
6716 
6717     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6718     IndexOperand &= ~0x3f;
6719     unsigned CountDw = 0;
6720 
6721     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6722       CountDw = (IndexOperand >> 24) & 0xf;
6723       IndexOperand &= ~(0xf << 24);
6724 
6725       if (CountDw < 1 || CountDw > 4) {
6726         report_fatal_error(
6727             "ds_ordered_count: dword count must be between 1 and 4");
6728       }
6729     }
6730 
6731     if (IndexOperand)
6732       report_fatal_error("ds_ordered_count: bad index operand");
6733 
6734     if (WaveDone && !WaveRelease)
6735       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6736 
6737     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6738     unsigned ShaderType =
6739         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6740     unsigned Offset0 = OrderedCountIndex << 2;
6741     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6742                        (Instruction << 4);
6743 
6744     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6745       Offset1 |= (CountDw - 1) << 6;
6746 
6747     unsigned Offset = Offset0 | (Offset1 << 8);
6748 
6749     SDValue Ops[] = {
6750       Chain,
6751       Value,
6752       DAG.getTargetConstant(Offset, DL, MVT::i16),
6753       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6754     };
6755     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6756                                    M->getVTList(), Ops, M->getMemoryVT(),
6757                                    M->getMemOperand());
6758   }
6759   case Intrinsic::amdgcn_ds_fadd: {
6760     MemSDNode *M = cast<MemSDNode>(Op);
6761     unsigned Opc;
6762     switch (IntrID) {
6763     case Intrinsic::amdgcn_ds_fadd:
6764       Opc = ISD::ATOMIC_LOAD_FADD;
6765       break;
6766     }
6767 
6768     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6769                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6770                          M->getMemOperand());
6771   }
6772   case Intrinsic::amdgcn_atomic_inc:
6773   case Intrinsic::amdgcn_atomic_dec:
6774   case Intrinsic::amdgcn_ds_fmin:
6775   case Intrinsic::amdgcn_ds_fmax: {
6776     MemSDNode *M = cast<MemSDNode>(Op);
6777     unsigned Opc;
6778     switch (IntrID) {
6779     case Intrinsic::amdgcn_atomic_inc:
6780       Opc = AMDGPUISD::ATOMIC_INC;
6781       break;
6782     case Intrinsic::amdgcn_atomic_dec:
6783       Opc = AMDGPUISD::ATOMIC_DEC;
6784       break;
6785     case Intrinsic::amdgcn_ds_fmin:
6786       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6787       break;
6788     case Intrinsic::amdgcn_ds_fmax:
6789       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6790       break;
6791     default:
6792       llvm_unreachable("Unknown intrinsic!");
6793     }
6794     SDValue Ops[] = {
6795       M->getOperand(0), // Chain
6796       M->getOperand(2), // Ptr
6797       M->getOperand(3)  // Value
6798     };
6799 
6800     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6801                                    M->getMemoryVT(), M->getMemOperand());
6802   }
6803   case Intrinsic::amdgcn_buffer_load:
6804   case Intrinsic::amdgcn_buffer_load_format: {
6805     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6806     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6807     unsigned IdxEn = 1;
6808     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6809       IdxEn = Idx->getZExtValue() != 0;
6810     SDValue Ops[] = {
6811       Op.getOperand(0), // Chain
6812       Op.getOperand(2), // rsrc
6813       Op.getOperand(3), // vindex
6814       SDValue(),        // voffset -- will be set by setBufferOffsets
6815       SDValue(),        // soffset -- will be set by setBufferOffsets
6816       SDValue(),        // offset -- will be set by setBufferOffsets
6817       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6818       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6819     };
6820 
6821     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6822     // We don't know the offset if vindex is non-zero, so clear it.
6823     if (IdxEn)
6824       Offset = 0;
6825 
6826     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6827         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6828 
6829     EVT VT = Op.getValueType();
6830     EVT IntVT = VT.changeTypeToInteger();
6831     auto *M = cast<MemSDNode>(Op);
6832     M->getMemOperand()->setOffset(Offset);
6833     EVT LoadVT = Op.getValueType();
6834 
6835     if (LoadVT.getScalarType() == MVT::f16)
6836       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6837                                  M, DAG, Ops);
6838 
6839     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6840     if (LoadVT.getScalarType() == MVT::i8 ||
6841         LoadVT.getScalarType() == MVT::i16)
6842       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6843 
6844     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6845                                M->getMemOperand(), DAG);
6846   }
6847   case Intrinsic::amdgcn_raw_buffer_load:
6848   case Intrinsic::amdgcn_raw_buffer_load_format: {
6849     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6850 
6851     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6852     SDValue Ops[] = {
6853       Op.getOperand(0), // Chain
6854       Op.getOperand(2), // rsrc
6855       DAG.getConstant(0, DL, MVT::i32), // vindex
6856       Offsets.first,    // voffset
6857       Op.getOperand(4), // soffset
6858       Offsets.second,   // offset
6859       Op.getOperand(5), // cachepolicy, swizzled buffer
6860       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6861     };
6862 
6863     auto *M = cast<MemSDNode>(Op);
6864     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6865     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6866   }
6867   case Intrinsic::amdgcn_struct_buffer_load:
6868   case Intrinsic::amdgcn_struct_buffer_load_format: {
6869     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6870 
6871     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6872     SDValue Ops[] = {
6873       Op.getOperand(0), // Chain
6874       Op.getOperand(2), // rsrc
6875       Op.getOperand(3), // vindex
6876       Offsets.first,    // voffset
6877       Op.getOperand(5), // soffset
6878       Offsets.second,   // offset
6879       Op.getOperand(6), // cachepolicy, swizzled buffer
6880       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6881     };
6882 
6883     auto *M = cast<MemSDNode>(Op);
6884     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6885                                                         Ops[2]));
6886     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6887   }
6888   case Intrinsic::amdgcn_tbuffer_load: {
6889     MemSDNode *M = cast<MemSDNode>(Op);
6890     EVT LoadVT = Op.getValueType();
6891 
6892     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6893     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6894     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6895     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6896     unsigned IdxEn = 1;
6897     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6898       IdxEn = Idx->getZExtValue() != 0;
6899     SDValue Ops[] = {
6900       Op.getOperand(0),  // Chain
6901       Op.getOperand(2),  // rsrc
6902       Op.getOperand(3),  // vindex
6903       Op.getOperand(4),  // voffset
6904       Op.getOperand(5),  // soffset
6905       Op.getOperand(6),  // offset
6906       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6907       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6908       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6909     };
6910 
6911     if (LoadVT.getScalarType() == MVT::f16)
6912       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6913                                  M, DAG, Ops);
6914     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6915                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6916                                DAG);
6917   }
6918   case Intrinsic::amdgcn_raw_tbuffer_load: {
6919     MemSDNode *M = cast<MemSDNode>(Op);
6920     EVT LoadVT = Op.getValueType();
6921     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6922 
6923     SDValue Ops[] = {
6924       Op.getOperand(0),  // Chain
6925       Op.getOperand(2),  // rsrc
6926       DAG.getConstant(0, DL, MVT::i32), // vindex
6927       Offsets.first,     // voffset
6928       Op.getOperand(4),  // soffset
6929       Offsets.second,    // offset
6930       Op.getOperand(5),  // format
6931       Op.getOperand(6),  // cachepolicy, swizzled buffer
6932       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6933     };
6934 
6935     if (LoadVT.getScalarType() == MVT::f16)
6936       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6937                                  M, DAG, Ops);
6938     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6939                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6940                                DAG);
6941   }
6942   case Intrinsic::amdgcn_struct_tbuffer_load: {
6943     MemSDNode *M = cast<MemSDNode>(Op);
6944     EVT LoadVT = Op.getValueType();
6945     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6946 
6947     SDValue Ops[] = {
6948       Op.getOperand(0),  // Chain
6949       Op.getOperand(2),  // rsrc
6950       Op.getOperand(3),  // vindex
6951       Offsets.first,     // voffset
6952       Op.getOperand(5),  // soffset
6953       Offsets.second,    // offset
6954       Op.getOperand(6),  // format
6955       Op.getOperand(7),  // cachepolicy, swizzled buffer
6956       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6957     };
6958 
6959     if (LoadVT.getScalarType() == MVT::f16)
6960       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6961                                  M, DAG, Ops);
6962     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6963                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6964                                DAG);
6965   }
6966   case Intrinsic::amdgcn_buffer_atomic_swap:
6967   case Intrinsic::amdgcn_buffer_atomic_add:
6968   case Intrinsic::amdgcn_buffer_atomic_sub:
6969   case Intrinsic::amdgcn_buffer_atomic_csub:
6970   case Intrinsic::amdgcn_buffer_atomic_smin:
6971   case Intrinsic::amdgcn_buffer_atomic_umin:
6972   case Intrinsic::amdgcn_buffer_atomic_smax:
6973   case Intrinsic::amdgcn_buffer_atomic_umax:
6974   case Intrinsic::amdgcn_buffer_atomic_and:
6975   case Intrinsic::amdgcn_buffer_atomic_or:
6976   case Intrinsic::amdgcn_buffer_atomic_xor: {
6977     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6978     unsigned IdxEn = 1;
6979     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6980       IdxEn = Idx->getZExtValue() != 0;
6981     SDValue Ops[] = {
6982       Op.getOperand(0), // Chain
6983       Op.getOperand(2), // vdata
6984       Op.getOperand(3), // rsrc
6985       Op.getOperand(4), // vindex
6986       SDValue(),        // voffset -- will be set by setBufferOffsets
6987       SDValue(),        // soffset -- will be set by setBufferOffsets
6988       SDValue(),        // offset -- will be set by setBufferOffsets
6989       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6990       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6991     };
6992     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6993     // We don't know the offset if vindex is non-zero, so clear it.
6994     if (IdxEn)
6995       Offset = 0;
6996     EVT VT = Op.getValueType();
6997 
6998     auto *M = cast<MemSDNode>(Op);
6999     M->getMemOperand()->setOffset(Offset);
7000     unsigned Opcode = 0;
7001 
7002     switch (IntrID) {
7003     case Intrinsic::amdgcn_buffer_atomic_swap:
7004       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7005       break;
7006     case Intrinsic::amdgcn_buffer_atomic_add:
7007       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7008       break;
7009     case Intrinsic::amdgcn_buffer_atomic_sub:
7010       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7011       break;
7012     case Intrinsic::amdgcn_buffer_atomic_csub:
7013       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7014       break;
7015     case Intrinsic::amdgcn_buffer_atomic_smin:
7016       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7017       break;
7018     case Intrinsic::amdgcn_buffer_atomic_umin:
7019       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7020       break;
7021     case Intrinsic::amdgcn_buffer_atomic_smax:
7022       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7023       break;
7024     case Intrinsic::amdgcn_buffer_atomic_umax:
7025       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7026       break;
7027     case Intrinsic::amdgcn_buffer_atomic_and:
7028       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7029       break;
7030     case Intrinsic::amdgcn_buffer_atomic_or:
7031       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7032       break;
7033     case Intrinsic::amdgcn_buffer_atomic_xor:
7034       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7035       break;
7036     default:
7037       llvm_unreachable("unhandled atomic opcode");
7038     }
7039 
7040     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7041                                    M->getMemOperand());
7042   }
7043   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7044     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7045   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7046     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7047   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7048     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7049   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7050     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7051   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7052     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7053   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7054     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7055   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7056     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7057   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7058     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7059   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7060     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7061   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7062     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7063   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7064     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7065   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7066     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7067   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7068     return lowerStructBufferAtomicIntrin(Op, DAG,
7069                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7070   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7071     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7072   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7073     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7074   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7075     return lowerStructBufferAtomicIntrin(Op, DAG,
7076                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7077   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7078     return lowerStructBufferAtomicIntrin(Op, DAG,
7079                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7080   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7081     return lowerStructBufferAtomicIntrin(Op, DAG,
7082                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7083   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7084     return lowerStructBufferAtomicIntrin(Op, DAG,
7085                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7086   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7087     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7088   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7089     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7090   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7091     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7092   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7093     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7094   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7095     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7096 
7097   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7098     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7099     unsigned IdxEn = 1;
7100     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7101       IdxEn = Idx->getZExtValue() != 0;
7102     SDValue Ops[] = {
7103       Op.getOperand(0), // Chain
7104       Op.getOperand(2), // src
7105       Op.getOperand(3), // cmp
7106       Op.getOperand(4), // rsrc
7107       Op.getOperand(5), // vindex
7108       SDValue(),        // voffset -- will be set by setBufferOffsets
7109       SDValue(),        // soffset -- will be set by setBufferOffsets
7110       SDValue(),        // offset -- will be set by setBufferOffsets
7111       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7112       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7113     };
7114     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7115     // We don't know the offset if vindex is non-zero, so clear it.
7116     if (IdxEn)
7117       Offset = 0;
7118     EVT VT = Op.getValueType();
7119     auto *M = cast<MemSDNode>(Op);
7120     M->getMemOperand()->setOffset(Offset);
7121 
7122     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7123                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7124   }
7125   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7126     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7127     SDValue Ops[] = {
7128       Op.getOperand(0), // Chain
7129       Op.getOperand(2), // src
7130       Op.getOperand(3), // cmp
7131       Op.getOperand(4), // rsrc
7132       DAG.getConstant(0, DL, MVT::i32), // vindex
7133       Offsets.first,    // voffset
7134       Op.getOperand(6), // soffset
7135       Offsets.second,   // offset
7136       Op.getOperand(7), // cachepolicy
7137       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7138     };
7139     EVT VT = Op.getValueType();
7140     auto *M = cast<MemSDNode>(Op);
7141     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7142 
7143     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7144                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7145   }
7146   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7147     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7148     SDValue Ops[] = {
7149       Op.getOperand(0), // Chain
7150       Op.getOperand(2), // src
7151       Op.getOperand(3), // cmp
7152       Op.getOperand(4), // rsrc
7153       Op.getOperand(5), // vindex
7154       Offsets.first,    // voffset
7155       Op.getOperand(7), // soffset
7156       Offsets.second,   // offset
7157       Op.getOperand(8), // cachepolicy
7158       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7159     };
7160     EVT VT = Op.getValueType();
7161     auto *M = cast<MemSDNode>(Op);
7162     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7163                                                         Ops[4]));
7164 
7165     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7166                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7167   }
7168   default:
7169     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7170             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7171       return lowerImage(Op, ImageDimIntr, DAG);
7172 
7173     return SDValue();
7174   }
7175 }
7176 
7177 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7178 // dwordx4 if on SI.
7179 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7180                                               SDVTList VTList,
7181                                               ArrayRef<SDValue> Ops, EVT MemVT,
7182                                               MachineMemOperand *MMO,
7183                                               SelectionDAG &DAG) const {
7184   EVT VT = VTList.VTs[0];
7185   EVT WidenedVT = VT;
7186   EVT WidenedMemVT = MemVT;
7187   if (!Subtarget->hasDwordx3LoadStores() &&
7188       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7189     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7190                                  WidenedVT.getVectorElementType(), 4);
7191     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7192                                     WidenedMemVT.getVectorElementType(), 4);
7193     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7194   }
7195 
7196   assert(VTList.NumVTs == 2);
7197   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7198 
7199   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7200                                        WidenedMemVT, MMO);
7201   if (WidenedVT != VT) {
7202     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7203                                DAG.getVectorIdxConstant(0, DL));
7204     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7205   }
7206   return NewOp;
7207 }
7208 
7209 SDValue SITargetLowering::handleD16VData(SDValue VData,
7210                                          SelectionDAG &DAG) const {
7211   EVT StoreVT = VData.getValueType();
7212 
7213   // No change for f16 and legal vector D16 types.
7214   if (!StoreVT.isVector())
7215     return VData;
7216 
7217   SDLoc DL(VData);
7218   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
7219 
7220   if (Subtarget->hasUnpackedD16VMem()) {
7221     // We need to unpack the packed data to store.
7222     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7223     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7224 
7225     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
7226                                         StoreVT.getVectorNumElements());
7227     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7228     return DAG.UnrollVectorOp(ZExt.getNode());
7229   }
7230 
7231   assert(isTypeLegal(StoreVT));
7232   return VData;
7233 }
7234 
7235 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7236                                               SelectionDAG &DAG) const {
7237   SDLoc DL(Op);
7238   SDValue Chain = Op.getOperand(0);
7239   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7240   MachineFunction &MF = DAG.getMachineFunction();
7241 
7242   switch (IntrinsicID) {
7243   case Intrinsic::amdgcn_exp_compr: {
7244     SDValue Src0 = Op.getOperand(4);
7245     SDValue Src1 = Op.getOperand(5);
7246     // Hack around illegal type on SI by directly selecting it.
7247     if (isTypeLegal(Src0.getValueType()))
7248       return SDValue();
7249 
7250     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7251     SDValue Undef = DAG.getUNDEF(MVT::f32);
7252     const SDValue Ops[] = {
7253       Op.getOperand(2), // tgt
7254       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7255       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7256       Undef, // src2
7257       Undef, // src3
7258       Op.getOperand(7), // vm
7259       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7260       Op.getOperand(3), // en
7261       Op.getOperand(0) // Chain
7262     };
7263 
7264     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7265     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7266   }
7267   case Intrinsic::amdgcn_s_barrier: {
7268     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7269       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7270       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7271       if (WGSize <= ST.getWavefrontSize())
7272         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7273                                           Op.getOperand(0)), 0);
7274     }
7275     return SDValue();
7276   };
7277   case Intrinsic::amdgcn_tbuffer_store: {
7278     SDValue VData = Op.getOperand(2);
7279     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7280     if (IsD16)
7281       VData = handleD16VData(VData, DAG);
7282     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7283     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7284     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7285     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7286     unsigned IdxEn = 1;
7287     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7288       IdxEn = Idx->getZExtValue() != 0;
7289     SDValue Ops[] = {
7290       Chain,
7291       VData,             // vdata
7292       Op.getOperand(3),  // rsrc
7293       Op.getOperand(4),  // vindex
7294       Op.getOperand(5),  // voffset
7295       Op.getOperand(6),  // soffset
7296       Op.getOperand(7),  // offset
7297       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7298       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7299       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7300     };
7301     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7302                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7303     MemSDNode *M = cast<MemSDNode>(Op);
7304     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7305                                    M->getMemoryVT(), M->getMemOperand());
7306   }
7307 
7308   case Intrinsic::amdgcn_struct_tbuffer_store: {
7309     SDValue VData = Op.getOperand(2);
7310     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7311     if (IsD16)
7312       VData = handleD16VData(VData, DAG);
7313     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7314     SDValue Ops[] = {
7315       Chain,
7316       VData,             // vdata
7317       Op.getOperand(3),  // rsrc
7318       Op.getOperand(4),  // vindex
7319       Offsets.first,     // voffset
7320       Op.getOperand(6),  // soffset
7321       Offsets.second,    // offset
7322       Op.getOperand(7),  // format
7323       Op.getOperand(8),  // cachepolicy, swizzled buffer
7324       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7325     };
7326     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7327                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7328     MemSDNode *M = cast<MemSDNode>(Op);
7329     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7330                                    M->getMemoryVT(), M->getMemOperand());
7331   }
7332 
7333   case Intrinsic::amdgcn_raw_tbuffer_store: {
7334     SDValue VData = Op.getOperand(2);
7335     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7336     if (IsD16)
7337       VData = handleD16VData(VData, DAG);
7338     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7339     SDValue Ops[] = {
7340       Chain,
7341       VData,             // vdata
7342       Op.getOperand(3),  // rsrc
7343       DAG.getConstant(0, DL, MVT::i32), // vindex
7344       Offsets.first,     // voffset
7345       Op.getOperand(5),  // soffset
7346       Offsets.second,    // offset
7347       Op.getOperand(6),  // format
7348       Op.getOperand(7),  // cachepolicy, swizzled buffer
7349       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7350     };
7351     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7352                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7353     MemSDNode *M = cast<MemSDNode>(Op);
7354     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7355                                    M->getMemoryVT(), M->getMemOperand());
7356   }
7357 
7358   case Intrinsic::amdgcn_buffer_store:
7359   case Intrinsic::amdgcn_buffer_store_format: {
7360     SDValue VData = Op.getOperand(2);
7361     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7362     if (IsD16)
7363       VData = handleD16VData(VData, DAG);
7364     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7365     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7366     unsigned IdxEn = 1;
7367     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7368       IdxEn = Idx->getZExtValue() != 0;
7369     SDValue Ops[] = {
7370       Chain,
7371       VData,
7372       Op.getOperand(3), // rsrc
7373       Op.getOperand(4), // vindex
7374       SDValue(), // voffset -- will be set by setBufferOffsets
7375       SDValue(), // soffset -- will be set by setBufferOffsets
7376       SDValue(), // offset -- will be set by setBufferOffsets
7377       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7378       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7379     };
7380     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7381     // We don't know the offset if vindex is non-zero, so clear it.
7382     if (IdxEn)
7383       Offset = 0;
7384     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7385                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7386     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7387     MemSDNode *M = cast<MemSDNode>(Op);
7388     M->getMemOperand()->setOffset(Offset);
7389 
7390     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7391     EVT VDataType = VData.getValueType().getScalarType();
7392     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7393       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7394 
7395     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7396                                    M->getMemoryVT(), M->getMemOperand());
7397   }
7398 
7399   case Intrinsic::amdgcn_raw_buffer_store:
7400   case Intrinsic::amdgcn_raw_buffer_store_format: {
7401     const bool IsFormat =
7402         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7403 
7404     SDValue VData = Op.getOperand(2);
7405     EVT VDataVT = VData.getValueType();
7406     EVT EltType = VDataVT.getScalarType();
7407     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7408     if (IsD16)
7409       VData = handleD16VData(VData, DAG);
7410 
7411     if (!isTypeLegal(VDataVT)) {
7412       VData =
7413           DAG.getNode(ISD::BITCAST, DL,
7414                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7415     }
7416 
7417     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7418     SDValue Ops[] = {
7419       Chain,
7420       VData,
7421       Op.getOperand(3), // rsrc
7422       DAG.getConstant(0, DL, MVT::i32), // vindex
7423       Offsets.first,    // voffset
7424       Op.getOperand(5), // soffset
7425       Offsets.second,   // offset
7426       Op.getOperand(6), // cachepolicy, swizzled buffer
7427       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7428     };
7429     unsigned Opc =
7430         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7431     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7432     MemSDNode *M = cast<MemSDNode>(Op);
7433     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7434 
7435     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7436     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7437       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7438 
7439     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7440                                    M->getMemoryVT(), M->getMemOperand());
7441   }
7442 
7443   case Intrinsic::amdgcn_struct_buffer_store:
7444   case Intrinsic::amdgcn_struct_buffer_store_format: {
7445     const bool IsFormat =
7446         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7447 
7448     SDValue VData = Op.getOperand(2);
7449     EVT VDataVT = VData.getValueType();
7450     EVT EltType = VDataVT.getScalarType();
7451     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7452 
7453     if (IsD16)
7454       VData = handleD16VData(VData, DAG);
7455 
7456     if (!isTypeLegal(VDataVT)) {
7457       VData =
7458           DAG.getNode(ISD::BITCAST, DL,
7459                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7460     }
7461 
7462     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7463     SDValue Ops[] = {
7464       Chain,
7465       VData,
7466       Op.getOperand(3), // rsrc
7467       Op.getOperand(4), // vindex
7468       Offsets.first,    // voffset
7469       Op.getOperand(6), // soffset
7470       Offsets.second,   // offset
7471       Op.getOperand(7), // cachepolicy, swizzled buffer
7472       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7473     };
7474     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7475                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7476     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7477     MemSDNode *M = cast<MemSDNode>(Op);
7478     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7479                                                         Ops[3]));
7480 
7481     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7482     EVT VDataType = VData.getValueType().getScalarType();
7483     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7484       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7485 
7486     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7487                                    M->getMemoryVT(), M->getMemOperand());
7488   }
7489   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7490     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7491   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7492     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7493   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7494     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7495     unsigned IdxEn = 1;
7496     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7497       IdxEn = Idx->getZExtValue() != 0;
7498     SDValue Ops[] = {
7499       Chain,
7500       Op.getOperand(2), // vdata
7501       Op.getOperand(3), // rsrc
7502       Op.getOperand(4), // vindex
7503       SDValue(),        // voffset -- will be set by setBufferOffsets
7504       SDValue(),        // soffset -- will be set by setBufferOffsets
7505       SDValue(),        // offset -- will be set by setBufferOffsets
7506       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7507       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7508     };
7509     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7510     // We don't know the offset if vindex is non-zero, so clear it.
7511     if (IdxEn)
7512       Offset = 0;
7513     EVT VT = Op.getOperand(2).getValueType();
7514 
7515     auto *M = cast<MemSDNode>(Op);
7516     M->getMemOperand()->setOffset(Offset);
7517 
7518     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_FADD, DL,
7519                                    Op->getVTList(), Ops, VT,
7520                                    M->getMemOperand());
7521   }
7522 
7523   case Intrinsic::amdgcn_global_atomic_fadd: {
7524     SDValue Ops[] = {
7525       Chain,
7526       Op.getOperand(2), // ptr
7527       Op.getOperand(3)  // vdata
7528     };
7529 
7530     EVT VT = Op.getOperand(3).getValueType();
7531     auto *M = cast<MemSDNode>(Op);
7532 
7533     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7534                          DAG.getVTList(VT, MVT::Other), Ops,
7535                          M->getMemOperand()).getValue(1);
7536   }
7537   case Intrinsic::amdgcn_end_cf:
7538     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7539                                       Op->getOperand(2), Chain), 0);
7540 
7541   default: {
7542     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7543             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7544       return lowerImage(Op, ImageDimIntr, DAG);
7545 
7546     return Op;
7547   }
7548   }
7549 }
7550 
7551 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7552 // offset (the offset that is included in bounds checking and swizzling, to be
7553 // split between the instruction's voffset and immoffset fields) and soffset
7554 // (the offset that is excluded from bounds checking and swizzling, to go in
7555 // the instruction's soffset field).  This function takes the first kind of
7556 // offset and figures out how to split it between voffset and immoffset.
7557 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7558     SDValue Offset, SelectionDAG &DAG) const {
7559   SDLoc DL(Offset);
7560   const unsigned MaxImm = 4095;
7561   SDValue N0 = Offset;
7562   ConstantSDNode *C1 = nullptr;
7563 
7564   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7565     N0 = SDValue();
7566   else if (DAG.isBaseWithConstantOffset(N0)) {
7567     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7568     N0 = N0.getOperand(0);
7569   }
7570 
7571   if (C1) {
7572     unsigned ImmOffset = C1->getZExtValue();
7573     // If the immediate value is too big for the immoffset field, put the value
7574     // and -4096 into the immoffset field so that the value that is copied/added
7575     // for the voffset field is a multiple of 4096, and it stands more chance
7576     // of being CSEd with the copy/add for another similar load/store.
7577     // However, do not do that rounding down to a multiple of 4096 if that is a
7578     // negative number, as it appears to be illegal to have a negative offset
7579     // in the vgpr, even if adding the immediate offset makes it positive.
7580     unsigned Overflow = ImmOffset & ~MaxImm;
7581     ImmOffset -= Overflow;
7582     if ((int32_t)Overflow < 0) {
7583       Overflow += ImmOffset;
7584       ImmOffset = 0;
7585     }
7586     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7587     if (Overflow) {
7588       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7589       if (!N0)
7590         N0 = OverflowVal;
7591       else {
7592         SDValue Ops[] = { N0, OverflowVal };
7593         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7594       }
7595     }
7596   }
7597   if (!N0)
7598     N0 = DAG.getConstant(0, DL, MVT::i32);
7599   if (!C1)
7600     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7601   return {N0, SDValue(C1, 0)};
7602 }
7603 
7604 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7605 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7606 // pointed to by Offsets.
7607 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7608                                             SelectionDAG &DAG, SDValue *Offsets,
7609                                             Align Alignment) const {
7610   SDLoc DL(CombinedOffset);
7611   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7612     uint32_t Imm = C->getZExtValue();
7613     uint32_t SOffset, ImmOffset;
7614     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7615                                  Alignment)) {
7616       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7617       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7618       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7619       return SOffset + ImmOffset;
7620     }
7621   }
7622   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7623     SDValue N0 = CombinedOffset.getOperand(0);
7624     SDValue N1 = CombinedOffset.getOperand(1);
7625     uint32_t SOffset, ImmOffset;
7626     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7627     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7628                                                 Subtarget, Alignment)) {
7629       Offsets[0] = N0;
7630       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7631       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7632       return 0;
7633     }
7634   }
7635   Offsets[0] = CombinedOffset;
7636   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7637   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7638   return 0;
7639 }
7640 
7641 // Handle 8 bit and 16 bit buffer loads
7642 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7643                                                      EVT LoadVT, SDLoc DL,
7644                                                      ArrayRef<SDValue> Ops,
7645                                                      MemSDNode *M) const {
7646   EVT IntVT = LoadVT.changeTypeToInteger();
7647   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7648          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7649 
7650   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7651   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7652                                                Ops, IntVT,
7653                                                M->getMemOperand());
7654   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7655   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7656 
7657   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7658 }
7659 
7660 // Handle 8 bit and 16 bit buffer stores
7661 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7662                                                       EVT VDataType, SDLoc DL,
7663                                                       SDValue Ops[],
7664                                                       MemSDNode *M) const {
7665   if (VDataType == MVT::f16)
7666     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7667 
7668   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7669   Ops[1] = BufferStoreExt;
7670   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7671                                  AMDGPUISD::BUFFER_STORE_SHORT;
7672   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7673   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7674                                      M->getMemOperand());
7675 }
7676 
7677 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7678                                  ISD::LoadExtType ExtType, SDValue Op,
7679                                  const SDLoc &SL, EVT VT) {
7680   if (VT.bitsLT(Op.getValueType()))
7681     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7682 
7683   switch (ExtType) {
7684   case ISD::SEXTLOAD:
7685     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7686   case ISD::ZEXTLOAD:
7687     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7688   case ISD::EXTLOAD:
7689     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7690   case ISD::NON_EXTLOAD:
7691     return Op;
7692   }
7693 
7694   llvm_unreachable("invalid ext type");
7695 }
7696 
7697 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7698   SelectionDAG &DAG = DCI.DAG;
7699   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7700     return SDValue();
7701 
7702   // FIXME: Constant loads should all be marked invariant.
7703   unsigned AS = Ld->getAddressSpace();
7704   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7705       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7706       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7707     return SDValue();
7708 
7709   // Don't do this early, since it may interfere with adjacent load merging for
7710   // illegal types. We can avoid losing alignment information for exotic types
7711   // pre-legalize.
7712   EVT MemVT = Ld->getMemoryVT();
7713   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7714       MemVT.getSizeInBits() >= 32)
7715     return SDValue();
7716 
7717   SDLoc SL(Ld);
7718 
7719   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7720          "unexpected vector extload");
7721 
7722   // TODO: Drop only high part of range.
7723   SDValue Ptr = Ld->getBasePtr();
7724   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7725                                 MVT::i32, SL, Ld->getChain(), Ptr,
7726                                 Ld->getOffset(),
7727                                 Ld->getPointerInfo(), MVT::i32,
7728                                 Ld->getAlignment(),
7729                                 Ld->getMemOperand()->getFlags(),
7730                                 Ld->getAAInfo(),
7731                                 nullptr); // Drop ranges
7732 
7733   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7734   if (MemVT.isFloatingPoint()) {
7735     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7736            "unexpected fp extload");
7737     TruncVT = MemVT.changeTypeToInteger();
7738   }
7739 
7740   SDValue Cvt = NewLoad;
7741   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7742     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7743                       DAG.getValueType(TruncVT));
7744   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7745              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7746     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7747   } else {
7748     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7749   }
7750 
7751   EVT VT = Ld->getValueType(0);
7752   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7753 
7754   DCI.AddToWorklist(Cvt.getNode());
7755 
7756   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7757   // the appropriate extension from the 32-bit load.
7758   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7759   DCI.AddToWorklist(Cvt.getNode());
7760 
7761   // Handle conversion back to floating point if necessary.
7762   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7763 
7764   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7765 }
7766 
7767 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7768   SDLoc DL(Op);
7769   LoadSDNode *Load = cast<LoadSDNode>(Op);
7770   ISD::LoadExtType ExtType = Load->getExtensionType();
7771   EVT MemVT = Load->getMemoryVT();
7772 
7773   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7774     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7775       return SDValue();
7776 
7777     // FIXME: Copied from PPC
7778     // First, load into 32 bits, then truncate to 1 bit.
7779 
7780     SDValue Chain = Load->getChain();
7781     SDValue BasePtr = Load->getBasePtr();
7782     MachineMemOperand *MMO = Load->getMemOperand();
7783 
7784     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7785 
7786     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7787                                    BasePtr, RealMemVT, MMO);
7788 
7789     if (!MemVT.isVector()) {
7790       SDValue Ops[] = {
7791         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7792         NewLD.getValue(1)
7793       };
7794 
7795       return DAG.getMergeValues(Ops, DL);
7796     }
7797 
7798     SmallVector<SDValue, 3> Elts;
7799     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7800       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7801                                 DAG.getConstant(I, DL, MVT::i32));
7802 
7803       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7804     }
7805 
7806     SDValue Ops[] = {
7807       DAG.getBuildVector(MemVT, DL, Elts),
7808       NewLD.getValue(1)
7809     };
7810 
7811     return DAG.getMergeValues(Ops, DL);
7812   }
7813 
7814   if (!MemVT.isVector())
7815     return SDValue();
7816 
7817   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7818          "Custom lowering for non-i32 vectors hasn't been implemented.");
7819 
7820   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7821                                       MemVT, *Load->getMemOperand())) {
7822     SDValue Ops[2];
7823     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7824     return DAG.getMergeValues(Ops, DL);
7825   }
7826 
7827   unsigned Alignment = Load->getAlignment();
7828   unsigned AS = Load->getAddressSpace();
7829   if (Subtarget->hasLDSMisalignedBug() &&
7830       AS == AMDGPUAS::FLAT_ADDRESS &&
7831       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7832     return SplitVectorLoad(Op, DAG);
7833   }
7834 
7835   MachineFunction &MF = DAG.getMachineFunction();
7836   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7837   // If there is a possibilty that flat instruction access scratch memory
7838   // then we need to use the same legalization rules we use for private.
7839   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7840       !Subtarget->hasMultiDwordFlatScratchAddressing())
7841     AS = MFI->hasFlatScratchInit() ?
7842          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7843 
7844   unsigned NumElements = MemVT.getVectorNumElements();
7845 
7846   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7847       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7848     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7849       if (MemVT.isPow2VectorType())
7850         return SDValue();
7851       if (NumElements == 3)
7852         return WidenVectorLoad(Op, DAG);
7853       return SplitVectorLoad(Op, DAG);
7854     }
7855     // Non-uniform loads will be selected to MUBUF instructions, so they
7856     // have the same legalization requirements as global and private
7857     // loads.
7858     //
7859   }
7860 
7861   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7862       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7863       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7864     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7865         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
7866         Alignment >= 4 && NumElements < 32) {
7867       if (MemVT.isPow2VectorType())
7868         return SDValue();
7869       if (NumElements == 3)
7870         return WidenVectorLoad(Op, DAG);
7871       return SplitVectorLoad(Op, DAG);
7872     }
7873     // Non-uniform loads will be selected to MUBUF instructions, so they
7874     // have the same legalization requirements as global and private
7875     // loads.
7876     //
7877   }
7878   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7879       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7880       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7881       AS == AMDGPUAS::FLAT_ADDRESS) {
7882     if (NumElements > 4)
7883       return SplitVectorLoad(Op, DAG);
7884     // v3 loads not supported on SI.
7885     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7886       return WidenVectorLoad(Op, DAG);
7887     // v3 and v4 loads are supported for private and global memory.
7888     return SDValue();
7889   }
7890   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7891     // Depending on the setting of the private_element_size field in the
7892     // resource descriptor, we can only make private accesses up to a certain
7893     // size.
7894     switch (Subtarget->getMaxPrivateElementSize()) {
7895     case 4: {
7896       SDValue Ops[2];
7897       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7898       return DAG.getMergeValues(Ops, DL);
7899     }
7900     case 8:
7901       if (NumElements > 2)
7902         return SplitVectorLoad(Op, DAG);
7903       return SDValue();
7904     case 16:
7905       // Same as global/flat
7906       if (NumElements > 4)
7907         return SplitVectorLoad(Op, DAG);
7908       // v3 loads not supported on SI.
7909       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7910         return WidenVectorLoad(Op, DAG);
7911       return SDValue();
7912     default:
7913       llvm_unreachable("unsupported private_element_size");
7914     }
7915   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7916     // Use ds_read_b128 if possible.
7917     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7918         MemVT.getStoreSize() == 16)
7919       return SDValue();
7920 
7921     if (NumElements > 2)
7922       return SplitVectorLoad(Op, DAG);
7923 
7924     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7925     // address is negative, then the instruction is incorrectly treated as
7926     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7927     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7928     // load later in the SILoadStoreOptimizer.
7929     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7930         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7931         Load->getAlignment() < 8) {
7932       return SplitVectorLoad(Op, DAG);
7933     }
7934   }
7935   return SDValue();
7936 }
7937 
7938 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7939   EVT VT = Op.getValueType();
7940   assert(VT.getSizeInBits() == 64);
7941 
7942   SDLoc DL(Op);
7943   SDValue Cond = Op.getOperand(0);
7944 
7945   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7946   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7947 
7948   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7949   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7950 
7951   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7952   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7953 
7954   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7955 
7956   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7957   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7958 
7959   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7960 
7961   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7962   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7963 }
7964 
7965 // Catch division cases where we can use shortcuts with rcp and rsq
7966 // instructions.
7967 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7968                                               SelectionDAG &DAG) const {
7969   SDLoc SL(Op);
7970   SDValue LHS = Op.getOperand(0);
7971   SDValue RHS = Op.getOperand(1);
7972   EVT VT = Op.getValueType();
7973   const SDNodeFlags Flags = Op->getFlags();
7974 
7975   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7976                             Flags.hasApproximateFuncs();
7977 
7978   // Without !fpmath accuracy information, we can't do more because we don't
7979   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7980   if (!AllowInaccurateRcp)
7981     return SDValue();
7982 
7983   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7984     if (CLHS->isExactlyValue(1.0)) {
7985       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7986       // the CI documentation has a worst case error of 1 ulp.
7987       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7988       // use it as long as we aren't trying to use denormals.
7989       //
7990       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7991 
7992       // 1.0 / sqrt(x) -> rsq(x)
7993 
7994       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7995       // error seems really high at 2^29 ULP.
7996       if (RHS.getOpcode() == ISD::FSQRT)
7997         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7998 
7999       // 1.0 / x -> rcp(x)
8000       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8001     }
8002 
8003     // Same as for 1.0, but expand the sign out of the constant.
8004     if (CLHS->isExactlyValue(-1.0)) {
8005       // -1.0 / x -> rcp (fneg x)
8006       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8007       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8008     }
8009   }
8010 
8011   // Turn into multiply by the reciprocal.
8012   // x / y -> x * (1.0 / y)
8013   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8014   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8015 }
8016 
8017 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8018                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8019                           SDNodeFlags Flags) {
8020   if (GlueChain->getNumValues() <= 1) {
8021     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8022   }
8023 
8024   assert(GlueChain->getNumValues() == 3);
8025 
8026   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8027   switch (Opcode) {
8028   default: llvm_unreachable("no chain equivalent for opcode");
8029   case ISD::FMUL:
8030     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8031     break;
8032   }
8033 
8034   return DAG.getNode(Opcode, SL, VTList,
8035                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8036                      Flags);
8037 }
8038 
8039 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8040                            EVT VT, SDValue A, SDValue B, SDValue C,
8041                            SDValue GlueChain, SDNodeFlags Flags) {
8042   if (GlueChain->getNumValues() <= 1) {
8043     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8044   }
8045 
8046   assert(GlueChain->getNumValues() == 3);
8047 
8048   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8049   switch (Opcode) {
8050   default: llvm_unreachable("no chain equivalent for opcode");
8051   case ISD::FMA:
8052     Opcode = AMDGPUISD::FMA_W_CHAIN;
8053     break;
8054   }
8055 
8056   return DAG.getNode(Opcode, SL, VTList,
8057                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8058                      Flags);
8059 }
8060 
8061 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8062   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8063     return FastLowered;
8064 
8065   SDLoc SL(Op);
8066   SDValue Src0 = Op.getOperand(0);
8067   SDValue Src1 = Op.getOperand(1);
8068 
8069   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8070   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8071 
8072   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8073   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8074 
8075   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8076   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8077 
8078   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8079 }
8080 
8081 // Faster 2.5 ULP division that does not support denormals.
8082 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8083   SDLoc SL(Op);
8084   SDValue LHS = Op.getOperand(1);
8085   SDValue RHS = Op.getOperand(2);
8086 
8087   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8088 
8089   const APFloat K0Val(BitsToFloat(0x6f800000));
8090   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8091 
8092   const APFloat K1Val(BitsToFloat(0x2f800000));
8093   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8094 
8095   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8096 
8097   EVT SetCCVT =
8098     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8099 
8100   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8101 
8102   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8103 
8104   // TODO: Should this propagate fast-math-flags?
8105   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8106 
8107   // rcp does not support denormals.
8108   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8109 
8110   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8111 
8112   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8113 }
8114 
8115 // Returns immediate value for setting the F32 denorm mode when using the
8116 // S_DENORM_MODE instruction.
8117 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8118                                           const SDLoc &SL, const GCNSubtarget *ST) {
8119   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8120   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8121                                 ? FP_DENORM_FLUSH_NONE
8122                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8123 
8124   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8125   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8126 }
8127 
8128 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8129   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8130     return FastLowered;
8131 
8132   // The selection matcher assumes anything with a chain selecting to a
8133   // mayRaiseFPException machine instruction. Since we're introducing a chain
8134   // here, we need to explicitly report nofpexcept for the regular fdiv
8135   // lowering.
8136   SDNodeFlags Flags = Op->getFlags();
8137   Flags.setNoFPExcept(true);
8138 
8139   SDLoc SL(Op);
8140   SDValue LHS = Op.getOperand(0);
8141   SDValue RHS = Op.getOperand(1);
8142 
8143   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8144 
8145   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8146 
8147   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8148                                           {RHS, RHS, LHS}, Flags);
8149   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8150                                         {LHS, RHS, LHS}, Flags);
8151 
8152   // Denominator is scaled to not be denormal, so using rcp is ok.
8153   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8154                                   DenominatorScaled, Flags);
8155   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8156                                      DenominatorScaled, Flags);
8157 
8158   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8159                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8160                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8161   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8162 
8163   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8164 
8165   if (!HasFP32Denormals) {
8166     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8167     // lowering. The chain dependence is insufficient, and we need glue. We do
8168     // not need the glue variants in a strictfp function.
8169 
8170     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8171 
8172     SDNode *EnableDenorm;
8173     if (Subtarget->hasDenormModeInst()) {
8174       const SDValue EnableDenormValue =
8175           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8176 
8177       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8178                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8179     } else {
8180       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8181                                                         SL, MVT::i32);
8182       EnableDenorm =
8183           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8184                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8185     }
8186 
8187     SDValue Ops[3] = {
8188       NegDivScale0,
8189       SDValue(EnableDenorm, 0),
8190       SDValue(EnableDenorm, 1)
8191     };
8192 
8193     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8194   }
8195 
8196   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8197                              ApproxRcp, One, NegDivScale0, Flags);
8198 
8199   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8200                              ApproxRcp, Fma0, Flags);
8201 
8202   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8203                            Fma1, Fma1, Flags);
8204 
8205   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8206                              NumeratorScaled, Mul, Flags);
8207 
8208   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8209                              Fma2, Fma1, Mul, Fma2, Flags);
8210 
8211   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8212                              NumeratorScaled, Fma3, Flags);
8213 
8214   if (!HasFP32Denormals) {
8215     SDNode *DisableDenorm;
8216     if (Subtarget->hasDenormModeInst()) {
8217       const SDValue DisableDenormValue =
8218           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8219 
8220       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8221                                   Fma4.getValue(1), DisableDenormValue,
8222                                   Fma4.getValue(2)).getNode();
8223     } else {
8224       const SDValue DisableDenormValue =
8225           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8226 
8227       DisableDenorm = DAG.getMachineNode(
8228           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8229           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8230     }
8231 
8232     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8233                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8234     DAG.setRoot(OutputChain);
8235   }
8236 
8237   SDValue Scale = NumeratorScaled.getValue(1);
8238   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8239                              {Fma4, Fma1, Fma3, Scale}, Flags);
8240 
8241   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8242 }
8243 
8244 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8245   if (DAG.getTarget().Options.UnsafeFPMath)
8246     return lowerFastUnsafeFDIV(Op, DAG);
8247 
8248   SDLoc SL(Op);
8249   SDValue X = Op.getOperand(0);
8250   SDValue Y = Op.getOperand(1);
8251 
8252   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8253 
8254   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8255 
8256   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8257 
8258   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8259 
8260   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8261 
8262   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8263 
8264   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8265 
8266   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8267 
8268   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8269 
8270   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8271   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8272 
8273   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8274                              NegDivScale0, Mul, DivScale1);
8275 
8276   SDValue Scale;
8277 
8278   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8279     // Workaround a hardware bug on SI where the condition output from div_scale
8280     // is not usable.
8281 
8282     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8283 
8284     // Figure out if the scale to use for div_fmas.
8285     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8286     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8287     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8288     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8289 
8290     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8291     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8292 
8293     SDValue Scale0Hi
8294       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8295     SDValue Scale1Hi
8296       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8297 
8298     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8299     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8300     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8301   } else {
8302     Scale = DivScale1.getValue(1);
8303   }
8304 
8305   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8306                              Fma4, Fma3, Mul, Scale);
8307 
8308   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8309 }
8310 
8311 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8312   EVT VT = Op.getValueType();
8313 
8314   if (VT == MVT::f32)
8315     return LowerFDIV32(Op, DAG);
8316 
8317   if (VT == MVT::f64)
8318     return LowerFDIV64(Op, DAG);
8319 
8320   if (VT == MVT::f16)
8321     return LowerFDIV16(Op, DAG);
8322 
8323   llvm_unreachable("Unexpected type for fdiv");
8324 }
8325 
8326 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8327   SDLoc DL(Op);
8328   StoreSDNode *Store = cast<StoreSDNode>(Op);
8329   EVT VT = Store->getMemoryVT();
8330 
8331   if (VT == MVT::i1) {
8332     return DAG.getTruncStore(Store->getChain(), DL,
8333        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8334        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8335   }
8336 
8337   assert(VT.isVector() &&
8338          Store->getValue().getValueType().getScalarType() == MVT::i32);
8339 
8340   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8341                                       VT, *Store->getMemOperand())) {
8342     return expandUnalignedStore(Store, DAG);
8343   }
8344 
8345   unsigned AS = Store->getAddressSpace();
8346   if (Subtarget->hasLDSMisalignedBug() &&
8347       AS == AMDGPUAS::FLAT_ADDRESS &&
8348       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8349     return SplitVectorStore(Op, DAG);
8350   }
8351 
8352   MachineFunction &MF = DAG.getMachineFunction();
8353   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8354   // If there is a possibilty that flat instruction access scratch memory
8355   // then we need to use the same legalization rules we use for private.
8356   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8357       !Subtarget->hasMultiDwordFlatScratchAddressing())
8358     AS = MFI->hasFlatScratchInit() ?
8359          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8360 
8361   unsigned NumElements = VT.getVectorNumElements();
8362   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8363       AS == AMDGPUAS::FLAT_ADDRESS) {
8364     if (NumElements > 4)
8365       return SplitVectorStore(Op, DAG);
8366     // v3 stores not supported on SI.
8367     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8368       return SplitVectorStore(Op, DAG);
8369     return SDValue();
8370   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8371     switch (Subtarget->getMaxPrivateElementSize()) {
8372     case 4:
8373       return scalarizeVectorStore(Store, DAG);
8374     case 8:
8375       if (NumElements > 2)
8376         return SplitVectorStore(Op, DAG);
8377       return SDValue();
8378     case 16:
8379       if (NumElements > 4 || NumElements == 3)
8380         return SplitVectorStore(Op, DAG);
8381       return SDValue();
8382     default:
8383       llvm_unreachable("unsupported private_element_size");
8384     }
8385   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8386     // Use ds_write_b128 if possible.
8387     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8388         VT.getStoreSize() == 16 && NumElements != 3)
8389       return SDValue();
8390 
8391     if (NumElements > 2)
8392       return SplitVectorStore(Op, DAG);
8393 
8394     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8395     // address is negative, then the instruction is incorrectly treated as
8396     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8397     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8398     // store later in the SILoadStoreOptimizer.
8399     if (!Subtarget->hasUsableDSOffset() &&
8400         NumElements == 2 && VT.getStoreSize() == 8 &&
8401         Store->getAlignment() < 8) {
8402       return SplitVectorStore(Op, DAG);
8403     }
8404 
8405     return SDValue();
8406   } else {
8407     llvm_unreachable("unhandled address space");
8408   }
8409 }
8410 
8411 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8412   SDLoc DL(Op);
8413   EVT VT = Op.getValueType();
8414   SDValue Arg = Op.getOperand(0);
8415   SDValue TrigVal;
8416 
8417   // Propagate fast-math flags so that the multiply we introduce can be folded
8418   // if Arg is already the result of a multiply by constant.
8419   auto Flags = Op->getFlags();
8420 
8421   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8422 
8423   if (Subtarget->hasTrigReducedRange()) {
8424     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8425     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8426   } else {
8427     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8428   }
8429 
8430   switch (Op.getOpcode()) {
8431   case ISD::FCOS:
8432     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8433   case ISD::FSIN:
8434     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8435   default:
8436     llvm_unreachable("Wrong trig opcode");
8437   }
8438 }
8439 
8440 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8441   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8442   assert(AtomicNode->isCompareAndSwap());
8443   unsigned AS = AtomicNode->getAddressSpace();
8444 
8445   // No custom lowering required for local address space
8446   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8447     return Op;
8448 
8449   // Non-local address space requires custom lowering for atomic compare
8450   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8451   SDLoc DL(Op);
8452   SDValue ChainIn = Op.getOperand(0);
8453   SDValue Addr = Op.getOperand(1);
8454   SDValue Old = Op.getOperand(2);
8455   SDValue New = Op.getOperand(3);
8456   EVT VT = Op.getValueType();
8457   MVT SimpleVT = VT.getSimpleVT();
8458   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8459 
8460   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8461   SDValue Ops[] = { ChainIn, Addr, NewOld };
8462 
8463   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8464                                  Ops, VT, AtomicNode->getMemOperand());
8465 }
8466 
8467 //===----------------------------------------------------------------------===//
8468 // Custom DAG optimizations
8469 //===----------------------------------------------------------------------===//
8470 
8471 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8472                                                      DAGCombinerInfo &DCI) const {
8473   EVT VT = N->getValueType(0);
8474   EVT ScalarVT = VT.getScalarType();
8475   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8476     return SDValue();
8477 
8478   SelectionDAG &DAG = DCI.DAG;
8479   SDLoc DL(N);
8480 
8481   SDValue Src = N->getOperand(0);
8482   EVT SrcVT = Src.getValueType();
8483 
8484   // TODO: We could try to match extracting the higher bytes, which would be
8485   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8486   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8487   // about in practice.
8488   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8489     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8490       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8491       DCI.AddToWorklist(Cvt.getNode());
8492 
8493       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8494       if (ScalarVT != MVT::f32) {
8495         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8496                           DAG.getTargetConstant(0, DL, MVT::i32));
8497       }
8498       return Cvt;
8499     }
8500   }
8501 
8502   return SDValue();
8503 }
8504 
8505 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8506 
8507 // This is a variant of
8508 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8509 //
8510 // The normal DAG combiner will do this, but only if the add has one use since
8511 // that would increase the number of instructions.
8512 //
8513 // This prevents us from seeing a constant offset that can be folded into a
8514 // memory instruction's addressing mode. If we know the resulting add offset of
8515 // a pointer can be folded into an addressing offset, we can replace the pointer
8516 // operand with the add of new constant offset. This eliminates one of the uses,
8517 // and may allow the remaining use to also be simplified.
8518 //
8519 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8520                                                unsigned AddrSpace,
8521                                                EVT MemVT,
8522                                                DAGCombinerInfo &DCI) const {
8523   SDValue N0 = N->getOperand(0);
8524   SDValue N1 = N->getOperand(1);
8525 
8526   // We only do this to handle cases where it's profitable when there are
8527   // multiple uses of the add, so defer to the standard combine.
8528   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8529       N0->hasOneUse())
8530     return SDValue();
8531 
8532   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8533   if (!CN1)
8534     return SDValue();
8535 
8536   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8537   if (!CAdd)
8538     return SDValue();
8539 
8540   // If the resulting offset is too large, we can't fold it into the addressing
8541   // mode offset.
8542   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8543   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8544 
8545   AddrMode AM;
8546   AM.HasBaseReg = true;
8547   AM.BaseOffs = Offset.getSExtValue();
8548   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8549     return SDValue();
8550 
8551   SelectionDAG &DAG = DCI.DAG;
8552   SDLoc SL(N);
8553   EVT VT = N->getValueType(0);
8554 
8555   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8556   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8557 
8558   SDNodeFlags Flags;
8559   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8560                           (N0.getOpcode() == ISD::OR ||
8561                            N0->getFlags().hasNoUnsignedWrap()));
8562 
8563   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8564 }
8565 
8566 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8567                                                   DAGCombinerInfo &DCI) const {
8568   // FIXME: getBasePtr does not work correctly for intrinsic nodes and will find
8569   // the intrinsic ID, not the pointer.
8570   SDValue Ptr = N->getBasePtr();
8571   SelectionDAG &DAG = DCI.DAG;
8572   SDLoc SL(N);
8573 
8574   // TODO: We could also do this for multiplies.
8575   if (Ptr.getOpcode() == ISD::SHL) {
8576     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8577                                           N->getMemoryVT(), DCI);
8578     if (NewPtr) {
8579       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8580 
8581       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8582       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8583     }
8584   }
8585 
8586   return SDValue();
8587 }
8588 
8589 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8590   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8591          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8592          (Opc == ISD::XOR && Val == 0);
8593 }
8594 
8595 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8596 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8597 // integer combine opportunities since most 64-bit operations are decomposed
8598 // this way.  TODO: We won't want this for SALU especially if it is an inline
8599 // immediate.
8600 SDValue SITargetLowering::splitBinaryBitConstantOp(
8601   DAGCombinerInfo &DCI,
8602   const SDLoc &SL,
8603   unsigned Opc, SDValue LHS,
8604   const ConstantSDNode *CRHS) const {
8605   uint64_t Val = CRHS->getZExtValue();
8606   uint32_t ValLo = Lo_32(Val);
8607   uint32_t ValHi = Hi_32(Val);
8608   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8609 
8610     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8611          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8612         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8613     // If we need to materialize a 64-bit immediate, it will be split up later
8614     // anyway. Avoid creating the harder to understand 64-bit immediate
8615     // materialization.
8616     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8617   }
8618 
8619   return SDValue();
8620 }
8621 
8622 // Returns true if argument is a boolean value which is not serialized into
8623 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8624 static bool isBoolSGPR(SDValue V) {
8625   if (V.getValueType() != MVT::i1)
8626     return false;
8627   switch (V.getOpcode()) {
8628   default: break;
8629   case ISD::SETCC:
8630   case ISD::AND:
8631   case ISD::OR:
8632   case ISD::XOR:
8633   case AMDGPUISD::FP_CLASS:
8634     return true;
8635   }
8636   return false;
8637 }
8638 
8639 // If a constant has all zeroes or all ones within each byte return it.
8640 // Otherwise return 0.
8641 static uint32_t getConstantPermuteMask(uint32_t C) {
8642   // 0xff for any zero byte in the mask
8643   uint32_t ZeroByteMask = 0;
8644   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8645   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8646   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8647   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8648   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8649   if ((NonZeroByteMask & C) != NonZeroByteMask)
8650     return 0; // Partial bytes selected.
8651   return C;
8652 }
8653 
8654 // Check if a node selects whole bytes from its operand 0 starting at a byte
8655 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8656 // or -1 if not succeeded.
8657 // Note byte select encoding:
8658 // value 0-3 selects corresponding source byte;
8659 // value 0xc selects zero;
8660 // value 0xff selects 0xff.
8661 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8662   assert(V.getValueSizeInBits() == 32);
8663 
8664   if (V.getNumOperands() != 2)
8665     return ~0;
8666 
8667   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8668   if (!N1)
8669     return ~0;
8670 
8671   uint32_t C = N1->getZExtValue();
8672 
8673   switch (V.getOpcode()) {
8674   default:
8675     break;
8676   case ISD::AND:
8677     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8678       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8679     }
8680     break;
8681 
8682   case ISD::OR:
8683     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8684       return (0x03020100 & ~ConstMask) | ConstMask;
8685     }
8686     break;
8687 
8688   case ISD::SHL:
8689     if (C % 8)
8690       return ~0;
8691 
8692     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8693 
8694   case ISD::SRL:
8695     if (C % 8)
8696       return ~0;
8697 
8698     return uint32_t(0x0c0c0c0c03020100ull >> C);
8699   }
8700 
8701   return ~0;
8702 }
8703 
8704 SDValue SITargetLowering::performAndCombine(SDNode *N,
8705                                             DAGCombinerInfo &DCI) const {
8706   if (DCI.isBeforeLegalize())
8707     return SDValue();
8708 
8709   SelectionDAG &DAG = DCI.DAG;
8710   EVT VT = N->getValueType(0);
8711   SDValue LHS = N->getOperand(0);
8712   SDValue RHS = N->getOperand(1);
8713 
8714 
8715   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8716   if (VT == MVT::i64 && CRHS) {
8717     if (SDValue Split
8718         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8719       return Split;
8720   }
8721 
8722   if (CRHS && VT == MVT::i32) {
8723     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8724     // nb = number of trailing zeroes in mask
8725     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8726     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8727     uint64_t Mask = CRHS->getZExtValue();
8728     unsigned Bits = countPopulation(Mask);
8729     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8730         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8731       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8732         unsigned Shift = CShift->getZExtValue();
8733         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8734         unsigned Offset = NB + Shift;
8735         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8736           SDLoc SL(N);
8737           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8738                                     LHS->getOperand(0),
8739                                     DAG.getConstant(Offset, SL, MVT::i32),
8740                                     DAG.getConstant(Bits, SL, MVT::i32));
8741           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8742           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8743                                     DAG.getValueType(NarrowVT));
8744           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8745                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8746           return Shl;
8747         }
8748       }
8749     }
8750 
8751     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8752     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8753         isa<ConstantSDNode>(LHS.getOperand(2))) {
8754       uint32_t Sel = getConstantPermuteMask(Mask);
8755       if (!Sel)
8756         return SDValue();
8757 
8758       // Select 0xc for all zero bytes
8759       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8760       SDLoc DL(N);
8761       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8762                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8763     }
8764   }
8765 
8766   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8767   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8768   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8769     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8770     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8771 
8772     SDValue X = LHS.getOperand(0);
8773     SDValue Y = RHS.getOperand(0);
8774     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8775       return SDValue();
8776 
8777     if (LCC == ISD::SETO) {
8778       if (X != LHS.getOperand(1))
8779         return SDValue();
8780 
8781       if (RCC == ISD::SETUNE) {
8782         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8783         if (!C1 || !C1->isInfinity() || C1->isNegative())
8784           return SDValue();
8785 
8786         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8787                               SIInstrFlags::N_SUBNORMAL |
8788                               SIInstrFlags::N_ZERO |
8789                               SIInstrFlags::P_ZERO |
8790                               SIInstrFlags::P_SUBNORMAL |
8791                               SIInstrFlags::P_NORMAL;
8792 
8793         static_assert(((~(SIInstrFlags::S_NAN |
8794                           SIInstrFlags::Q_NAN |
8795                           SIInstrFlags::N_INFINITY |
8796                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8797                       "mask not equal");
8798 
8799         SDLoc DL(N);
8800         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8801                            X, DAG.getConstant(Mask, DL, MVT::i32));
8802       }
8803     }
8804   }
8805 
8806   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8807     std::swap(LHS, RHS);
8808 
8809   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8810       RHS.hasOneUse()) {
8811     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8812     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8813     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8814     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8815     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8816         (RHS.getOperand(0) == LHS.getOperand(0) &&
8817          LHS.getOperand(0) == LHS.getOperand(1))) {
8818       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8819       unsigned NewMask = LCC == ISD::SETO ?
8820         Mask->getZExtValue() & ~OrdMask :
8821         Mask->getZExtValue() & OrdMask;
8822 
8823       SDLoc DL(N);
8824       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8825                          DAG.getConstant(NewMask, DL, MVT::i32));
8826     }
8827   }
8828 
8829   if (VT == MVT::i32 &&
8830       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8831     // and x, (sext cc from i1) => select cc, x, 0
8832     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8833       std::swap(LHS, RHS);
8834     if (isBoolSGPR(RHS.getOperand(0)))
8835       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8836                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8837   }
8838 
8839   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8840   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8841   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8842       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8843     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8844     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8845     if (LHSMask != ~0u && RHSMask != ~0u) {
8846       // Canonicalize the expression in an attempt to have fewer unique masks
8847       // and therefore fewer registers used to hold the masks.
8848       if (LHSMask > RHSMask) {
8849         std::swap(LHSMask, RHSMask);
8850         std::swap(LHS, RHS);
8851       }
8852 
8853       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8854       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8855       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8856       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8857 
8858       // Check of we need to combine values from two sources within a byte.
8859       if (!(LHSUsedLanes & RHSUsedLanes) &&
8860           // If we select high and lower word keep it for SDWA.
8861           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8862           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8863         // Each byte in each mask is either selector mask 0-3, or has higher
8864         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8865         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8866         // mask which is not 0xff wins. By anding both masks we have a correct
8867         // result except that 0x0c shall be corrected to give 0x0c only.
8868         uint32_t Mask = LHSMask & RHSMask;
8869         for (unsigned I = 0; I < 32; I += 8) {
8870           uint32_t ByteSel = 0xff << I;
8871           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8872             Mask &= (0x0c << I) & 0xffffffff;
8873         }
8874 
8875         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8876         // or 0x0c.
8877         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8878         SDLoc DL(N);
8879 
8880         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8881                            LHS.getOperand(0), RHS.getOperand(0),
8882                            DAG.getConstant(Sel, DL, MVT::i32));
8883       }
8884     }
8885   }
8886 
8887   return SDValue();
8888 }
8889 
8890 SDValue SITargetLowering::performOrCombine(SDNode *N,
8891                                            DAGCombinerInfo &DCI) const {
8892   SelectionDAG &DAG = DCI.DAG;
8893   SDValue LHS = N->getOperand(0);
8894   SDValue RHS = N->getOperand(1);
8895 
8896   EVT VT = N->getValueType(0);
8897   if (VT == MVT::i1) {
8898     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8899     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8900         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8901       SDValue Src = LHS.getOperand(0);
8902       if (Src != RHS.getOperand(0))
8903         return SDValue();
8904 
8905       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8906       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8907       if (!CLHS || !CRHS)
8908         return SDValue();
8909 
8910       // Only 10 bits are used.
8911       static const uint32_t MaxMask = 0x3ff;
8912 
8913       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8914       SDLoc DL(N);
8915       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8916                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8917     }
8918 
8919     return SDValue();
8920   }
8921 
8922   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8923   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8924       LHS.getOpcode() == AMDGPUISD::PERM &&
8925       isa<ConstantSDNode>(LHS.getOperand(2))) {
8926     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8927     if (!Sel)
8928       return SDValue();
8929 
8930     Sel |= LHS.getConstantOperandVal(2);
8931     SDLoc DL(N);
8932     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8933                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8934   }
8935 
8936   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8937   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8938   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8939       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8940     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8941     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8942     if (LHSMask != ~0u && RHSMask != ~0u) {
8943       // Canonicalize the expression in an attempt to have fewer unique masks
8944       // and therefore fewer registers used to hold the masks.
8945       if (LHSMask > RHSMask) {
8946         std::swap(LHSMask, RHSMask);
8947         std::swap(LHS, RHS);
8948       }
8949 
8950       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8951       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8952       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8953       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8954 
8955       // Check of we need to combine values from two sources within a byte.
8956       if (!(LHSUsedLanes & RHSUsedLanes) &&
8957           // If we select high and lower word keep it for SDWA.
8958           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8959           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8960         // Kill zero bytes selected by other mask. Zero value is 0xc.
8961         LHSMask &= ~RHSUsedLanes;
8962         RHSMask &= ~LHSUsedLanes;
8963         // Add 4 to each active LHS lane
8964         LHSMask |= LHSUsedLanes & 0x04040404;
8965         // Combine masks
8966         uint32_t Sel = LHSMask | RHSMask;
8967         SDLoc DL(N);
8968 
8969         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8970                            LHS.getOperand(0), RHS.getOperand(0),
8971                            DAG.getConstant(Sel, DL, MVT::i32));
8972       }
8973     }
8974   }
8975 
8976   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
8977     return SDValue();
8978 
8979   // TODO: This could be a generic combine with a predicate for extracting the
8980   // high half of an integer being free.
8981 
8982   // (or i64:x, (zero_extend i32:y)) ->
8983   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8984   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8985       RHS.getOpcode() != ISD::ZERO_EXTEND)
8986     std::swap(LHS, RHS);
8987 
8988   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8989     SDValue ExtSrc = RHS.getOperand(0);
8990     EVT SrcVT = ExtSrc.getValueType();
8991     if (SrcVT == MVT::i32) {
8992       SDLoc SL(N);
8993       SDValue LowLHS, HiBits;
8994       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8995       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8996 
8997       DCI.AddToWorklist(LowOr.getNode());
8998       DCI.AddToWorklist(HiBits.getNode());
8999 
9000       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9001                                 LowOr, HiBits);
9002       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9003     }
9004   }
9005 
9006   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9007   if (CRHS) {
9008     if (SDValue Split
9009           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9010       return Split;
9011   }
9012 
9013   return SDValue();
9014 }
9015 
9016 SDValue SITargetLowering::performXorCombine(SDNode *N,
9017                                             DAGCombinerInfo &DCI) const {
9018   EVT VT = N->getValueType(0);
9019   if (VT != MVT::i64)
9020     return SDValue();
9021 
9022   SDValue LHS = N->getOperand(0);
9023   SDValue RHS = N->getOperand(1);
9024 
9025   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9026   if (CRHS) {
9027     if (SDValue Split
9028           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9029       return Split;
9030   }
9031 
9032   return SDValue();
9033 }
9034 
9035 // Instructions that will be lowered with a final instruction that zeros the
9036 // high result bits.
9037 // XXX - probably only need to list legal operations.
9038 static bool fp16SrcZerosHighBits(unsigned Opc) {
9039   switch (Opc) {
9040   case ISD::FADD:
9041   case ISD::FSUB:
9042   case ISD::FMUL:
9043   case ISD::FDIV:
9044   case ISD::FREM:
9045   case ISD::FMA:
9046   case ISD::FMAD:
9047   case ISD::FCANONICALIZE:
9048   case ISD::FP_ROUND:
9049   case ISD::UINT_TO_FP:
9050   case ISD::SINT_TO_FP:
9051   case ISD::FABS:
9052     // Fabs is lowered to a bit operation, but it's an and which will clear the
9053     // high bits anyway.
9054   case ISD::FSQRT:
9055   case ISD::FSIN:
9056   case ISD::FCOS:
9057   case ISD::FPOWI:
9058   case ISD::FPOW:
9059   case ISD::FLOG:
9060   case ISD::FLOG2:
9061   case ISD::FLOG10:
9062   case ISD::FEXP:
9063   case ISD::FEXP2:
9064   case ISD::FCEIL:
9065   case ISD::FTRUNC:
9066   case ISD::FRINT:
9067   case ISD::FNEARBYINT:
9068   case ISD::FROUND:
9069   case ISD::FFLOOR:
9070   case ISD::FMINNUM:
9071   case ISD::FMAXNUM:
9072   case AMDGPUISD::FRACT:
9073   case AMDGPUISD::CLAMP:
9074   case AMDGPUISD::COS_HW:
9075   case AMDGPUISD::SIN_HW:
9076   case AMDGPUISD::FMIN3:
9077   case AMDGPUISD::FMAX3:
9078   case AMDGPUISD::FMED3:
9079   case AMDGPUISD::FMAD_FTZ:
9080   case AMDGPUISD::RCP:
9081   case AMDGPUISD::RSQ:
9082   case AMDGPUISD::RCP_IFLAG:
9083   case AMDGPUISD::LDEXP:
9084     return true;
9085   default:
9086     // fcopysign, select and others may be lowered to 32-bit bit operations
9087     // which don't zero the high bits.
9088     return false;
9089   }
9090 }
9091 
9092 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9093                                                    DAGCombinerInfo &DCI) const {
9094   if (!Subtarget->has16BitInsts() ||
9095       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9096     return SDValue();
9097 
9098   EVT VT = N->getValueType(0);
9099   if (VT != MVT::i32)
9100     return SDValue();
9101 
9102   SDValue Src = N->getOperand(0);
9103   if (Src.getValueType() != MVT::i16)
9104     return SDValue();
9105 
9106   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9107   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9108   if (Src.getOpcode() == ISD::BITCAST) {
9109     SDValue BCSrc = Src.getOperand(0);
9110     if (BCSrc.getValueType() == MVT::f16 &&
9111         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9112       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9113   }
9114 
9115   return SDValue();
9116 }
9117 
9118 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9119                                                         DAGCombinerInfo &DCI)
9120                                                         const {
9121   SDValue Src = N->getOperand(0);
9122   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9123 
9124   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9125       VTSign->getVT() == MVT::i8) ||
9126       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9127       VTSign->getVT() == MVT::i16)) &&
9128       Src.hasOneUse()) {
9129     auto *M = cast<MemSDNode>(Src);
9130     SDValue Ops[] = {
9131       Src.getOperand(0), // Chain
9132       Src.getOperand(1), // rsrc
9133       Src.getOperand(2), // vindex
9134       Src.getOperand(3), // voffset
9135       Src.getOperand(4), // soffset
9136       Src.getOperand(5), // offset
9137       Src.getOperand(6),
9138       Src.getOperand(7)
9139     };
9140     // replace with BUFFER_LOAD_BYTE/SHORT
9141     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9142                                          Src.getOperand(0).getValueType());
9143     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9144                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9145     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9146                                                           ResList,
9147                                                           Ops, M->getMemoryVT(),
9148                                                           M->getMemOperand());
9149     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9150                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9151   }
9152   return SDValue();
9153 }
9154 
9155 SDValue SITargetLowering::performClassCombine(SDNode *N,
9156                                               DAGCombinerInfo &DCI) const {
9157   SelectionDAG &DAG = DCI.DAG;
9158   SDValue Mask = N->getOperand(1);
9159 
9160   // fp_class x, 0 -> false
9161   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9162     if (CMask->isNullValue())
9163       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9164   }
9165 
9166   if (N->getOperand(0).isUndef())
9167     return DAG.getUNDEF(MVT::i1);
9168 
9169   return SDValue();
9170 }
9171 
9172 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9173                                             DAGCombinerInfo &DCI) const {
9174   EVT VT = N->getValueType(0);
9175   SDValue N0 = N->getOperand(0);
9176 
9177   if (N0.isUndef())
9178     return N0;
9179 
9180   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9181                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9182     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9183                            N->getFlags());
9184   }
9185 
9186   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9187     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9188                            N0.getOperand(0), N->getFlags());
9189   }
9190 
9191   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9192 }
9193 
9194 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9195                                        unsigned MaxDepth) const {
9196   unsigned Opcode = Op.getOpcode();
9197   if (Opcode == ISD::FCANONICALIZE)
9198     return true;
9199 
9200   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9201     auto F = CFP->getValueAPF();
9202     if (F.isNaN() && F.isSignaling())
9203       return false;
9204     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9205   }
9206 
9207   // If source is a result of another standard FP operation it is already in
9208   // canonical form.
9209   if (MaxDepth == 0)
9210     return false;
9211 
9212   switch (Opcode) {
9213   // These will flush denorms if required.
9214   case ISD::FADD:
9215   case ISD::FSUB:
9216   case ISD::FMUL:
9217   case ISD::FCEIL:
9218   case ISD::FFLOOR:
9219   case ISD::FMA:
9220   case ISD::FMAD:
9221   case ISD::FSQRT:
9222   case ISD::FDIV:
9223   case ISD::FREM:
9224   case ISD::FP_ROUND:
9225   case ISD::FP_EXTEND:
9226   case AMDGPUISD::FMUL_LEGACY:
9227   case AMDGPUISD::FMAD_FTZ:
9228   case AMDGPUISD::RCP:
9229   case AMDGPUISD::RSQ:
9230   case AMDGPUISD::RSQ_CLAMP:
9231   case AMDGPUISD::RCP_LEGACY:
9232   case AMDGPUISD::RCP_IFLAG:
9233   case AMDGPUISD::DIV_SCALE:
9234   case AMDGPUISD::DIV_FMAS:
9235   case AMDGPUISD::DIV_FIXUP:
9236   case AMDGPUISD::FRACT:
9237   case AMDGPUISD::LDEXP:
9238   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9239   case AMDGPUISD::CVT_F32_UBYTE0:
9240   case AMDGPUISD::CVT_F32_UBYTE1:
9241   case AMDGPUISD::CVT_F32_UBYTE2:
9242   case AMDGPUISD::CVT_F32_UBYTE3:
9243     return true;
9244 
9245   // It can/will be lowered or combined as a bit operation.
9246   // Need to check their input recursively to handle.
9247   case ISD::FNEG:
9248   case ISD::FABS:
9249   case ISD::FCOPYSIGN:
9250     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9251 
9252   case ISD::FSIN:
9253   case ISD::FCOS:
9254   case ISD::FSINCOS:
9255     return Op.getValueType().getScalarType() != MVT::f16;
9256 
9257   case ISD::FMINNUM:
9258   case ISD::FMAXNUM:
9259   case ISD::FMINNUM_IEEE:
9260   case ISD::FMAXNUM_IEEE:
9261   case AMDGPUISD::CLAMP:
9262   case AMDGPUISD::FMED3:
9263   case AMDGPUISD::FMAX3:
9264   case AMDGPUISD::FMIN3: {
9265     // FIXME: Shouldn't treat the generic operations different based these.
9266     // However, we aren't really required to flush the result from
9267     // minnum/maxnum..
9268 
9269     // snans will be quieted, so we only need to worry about denormals.
9270     if (Subtarget->supportsMinMaxDenormModes() ||
9271         denormalsEnabledForType(DAG, Op.getValueType()))
9272       return true;
9273 
9274     // Flushing may be required.
9275     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9276     // targets need to check their input recursively.
9277 
9278     // FIXME: Does this apply with clamp? It's implemented with max.
9279     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9280       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9281         return false;
9282     }
9283 
9284     return true;
9285   }
9286   case ISD::SELECT: {
9287     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9288            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9289   }
9290   case ISD::BUILD_VECTOR: {
9291     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9292       SDValue SrcOp = Op.getOperand(i);
9293       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9294         return false;
9295     }
9296 
9297     return true;
9298   }
9299   case ISD::EXTRACT_VECTOR_ELT:
9300   case ISD::EXTRACT_SUBVECTOR: {
9301     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9302   }
9303   case ISD::INSERT_VECTOR_ELT: {
9304     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9305            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9306   }
9307   case ISD::UNDEF:
9308     // Could be anything.
9309     return false;
9310 
9311   case ISD::BITCAST: {
9312     // Hack round the mess we make when legalizing extract_vector_elt
9313     SDValue Src = Op.getOperand(0);
9314     if (Src.getValueType() == MVT::i16 &&
9315         Src.getOpcode() == ISD::TRUNCATE) {
9316       SDValue TruncSrc = Src.getOperand(0);
9317       if (TruncSrc.getValueType() == MVT::i32 &&
9318           TruncSrc.getOpcode() == ISD::BITCAST &&
9319           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9320         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9321       }
9322     }
9323 
9324     return false;
9325   }
9326   case ISD::INTRINSIC_WO_CHAIN: {
9327     unsigned IntrinsicID
9328       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9329     // TODO: Handle more intrinsics
9330     switch (IntrinsicID) {
9331     case Intrinsic::amdgcn_cvt_pkrtz:
9332     case Intrinsic::amdgcn_cubeid:
9333     case Intrinsic::amdgcn_frexp_mant:
9334     case Intrinsic::amdgcn_fdot2:
9335     case Intrinsic::amdgcn_rcp:
9336     case Intrinsic::amdgcn_rsq:
9337     case Intrinsic::amdgcn_rsq_clamp:
9338     case Intrinsic::amdgcn_rcp_legacy:
9339     case Intrinsic::amdgcn_rsq_legacy:
9340     case Intrinsic::amdgcn_trig_preop:
9341       return true;
9342     default:
9343       break;
9344     }
9345 
9346     LLVM_FALLTHROUGH;
9347   }
9348   default:
9349     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9350            DAG.isKnownNeverSNaN(Op);
9351   }
9352 
9353   llvm_unreachable("invalid operation");
9354 }
9355 
9356 // Constant fold canonicalize.
9357 SDValue SITargetLowering::getCanonicalConstantFP(
9358   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9359   // Flush denormals to 0 if not enabled.
9360   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9361     return DAG.getConstantFP(0.0, SL, VT);
9362 
9363   if (C.isNaN()) {
9364     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9365     if (C.isSignaling()) {
9366       // Quiet a signaling NaN.
9367       // FIXME: Is this supposed to preserve payload bits?
9368       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9369     }
9370 
9371     // Make sure it is the canonical NaN bitpattern.
9372     //
9373     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9374     // immediate?
9375     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9376       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9377   }
9378 
9379   // Already canonical.
9380   return DAG.getConstantFP(C, SL, VT);
9381 }
9382 
9383 static bool vectorEltWillFoldAway(SDValue Op) {
9384   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9385 }
9386 
9387 SDValue SITargetLowering::performFCanonicalizeCombine(
9388   SDNode *N,
9389   DAGCombinerInfo &DCI) const {
9390   SelectionDAG &DAG = DCI.DAG;
9391   SDValue N0 = N->getOperand(0);
9392   EVT VT = N->getValueType(0);
9393 
9394   // fcanonicalize undef -> qnan
9395   if (N0.isUndef()) {
9396     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9397     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9398   }
9399 
9400   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9401     EVT VT = N->getValueType(0);
9402     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9403   }
9404 
9405   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9406   //                                                   (fcanonicalize k)
9407   //
9408   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9409 
9410   // TODO: This could be better with wider vectors that will be split to v2f16,
9411   // and to consider uses since there aren't that many packed operations.
9412   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9413       isTypeLegal(MVT::v2f16)) {
9414     SDLoc SL(N);
9415     SDValue NewElts[2];
9416     SDValue Lo = N0.getOperand(0);
9417     SDValue Hi = N0.getOperand(1);
9418     EVT EltVT = Lo.getValueType();
9419 
9420     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9421       for (unsigned I = 0; I != 2; ++I) {
9422         SDValue Op = N0.getOperand(I);
9423         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9424           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9425                                               CFP->getValueAPF());
9426         } else if (Op.isUndef()) {
9427           // Handled below based on what the other operand is.
9428           NewElts[I] = Op;
9429         } else {
9430           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9431         }
9432       }
9433 
9434       // If one half is undef, and one is constant, perfer a splat vector rather
9435       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9436       // cheaper to use and may be free with a packed operation.
9437       if (NewElts[0].isUndef()) {
9438         if (isa<ConstantFPSDNode>(NewElts[1]))
9439           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9440             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9441       }
9442 
9443       if (NewElts[1].isUndef()) {
9444         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9445           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9446       }
9447 
9448       return DAG.getBuildVector(VT, SL, NewElts);
9449     }
9450   }
9451 
9452   unsigned SrcOpc = N0.getOpcode();
9453 
9454   // If it's free to do so, push canonicalizes further up the source, which may
9455   // find a canonical source.
9456   //
9457   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9458   // sNaNs.
9459   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9460     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9461     if (CRHS && N0.hasOneUse()) {
9462       SDLoc SL(N);
9463       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9464                                    N0.getOperand(0));
9465       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9466       DCI.AddToWorklist(Canon0.getNode());
9467 
9468       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9469     }
9470   }
9471 
9472   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9473 }
9474 
9475 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9476   switch (Opc) {
9477   case ISD::FMAXNUM:
9478   case ISD::FMAXNUM_IEEE:
9479     return AMDGPUISD::FMAX3;
9480   case ISD::SMAX:
9481     return AMDGPUISD::SMAX3;
9482   case ISD::UMAX:
9483     return AMDGPUISD::UMAX3;
9484   case ISD::FMINNUM:
9485   case ISD::FMINNUM_IEEE:
9486     return AMDGPUISD::FMIN3;
9487   case ISD::SMIN:
9488     return AMDGPUISD::SMIN3;
9489   case ISD::UMIN:
9490     return AMDGPUISD::UMIN3;
9491   default:
9492     llvm_unreachable("Not a min/max opcode");
9493   }
9494 }
9495 
9496 SDValue SITargetLowering::performIntMed3ImmCombine(
9497   SelectionDAG &DAG, const SDLoc &SL,
9498   SDValue Op0, SDValue Op1, bool Signed) const {
9499   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9500   if (!K1)
9501     return SDValue();
9502 
9503   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9504   if (!K0)
9505     return SDValue();
9506 
9507   if (Signed) {
9508     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9509       return SDValue();
9510   } else {
9511     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9512       return SDValue();
9513   }
9514 
9515   EVT VT = K0->getValueType(0);
9516   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9517   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9518     return DAG.getNode(Med3Opc, SL, VT,
9519                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9520   }
9521 
9522   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9523   MVT NVT = MVT::i32;
9524   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9525 
9526   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9527   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9528   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9529 
9530   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9531   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9532 }
9533 
9534 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9535   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9536     return C;
9537 
9538   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9539     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9540       return C;
9541   }
9542 
9543   return nullptr;
9544 }
9545 
9546 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9547                                                   const SDLoc &SL,
9548                                                   SDValue Op0,
9549                                                   SDValue Op1) const {
9550   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9551   if (!K1)
9552     return SDValue();
9553 
9554   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9555   if (!K0)
9556     return SDValue();
9557 
9558   // Ordered >= (although NaN inputs should have folded away by now).
9559   if (K0->getValueAPF() > K1->getValueAPF())
9560     return SDValue();
9561 
9562   const MachineFunction &MF = DAG.getMachineFunction();
9563   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9564 
9565   // TODO: Check IEEE bit enabled?
9566   EVT VT = Op0.getValueType();
9567   if (Info->getMode().DX10Clamp) {
9568     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9569     // hardware fmed3 behavior converting to a min.
9570     // FIXME: Should this be allowing -0.0?
9571     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9572       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9573   }
9574 
9575   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9576   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9577     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9578     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9579     // then give the other result, which is different from med3 with a NaN
9580     // input.
9581     SDValue Var = Op0.getOperand(0);
9582     if (!DAG.isKnownNeverSNaN(Var))
9583       return SDValue();
9584 
9585     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9586 
9587     if ((!K0->hasOneUse() ||
9588          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9589         (!K1->hasOneUse() ||
9590          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9591       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9592                          Var, SDValue(K0, 0), SDValue(K1, 0));
9593     }
9594   }
9595 
9596   return SDValue();
9597 }
9598 
9599 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9600                                                DAGCombinerInfo &DCI) const {
9601   SelectionDAG &DAG = DCI.DAG;
9602 
9603   EVT VT = N->getValueType(0);
9604   unsigned Opc = N->getOpcode();
9605   SDValue Op0 = N->getOperand(0);
9606   SDValue Op1 = N->getOperand(1);
9607 
9608   // Only do this if the inner op has one use since this will just increases
9609   // register pressure for no benefit.
9610 
9611   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9612       !VT.isVector() &&
9613       (VT == MVT::i32 || VT == MVT::f32 ||
9614        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9615     // max(max(a, b), c) -> max3(a, b, c)
9616     // min(min(a, b), c) -> min3(a, b, c)
9617     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9618       SDLoc DL(N);
9619       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9620                          DL,
9621                          N->getValueType(0),
9622                          Op0.getOperand(0),
9623                          Op0.getOperand(1),
9624                          Op1);
9625     }
9626 
9627     // Try commuted.
9628     // max(a, max(b, c)) -> max3(a, b, c)
9629     // min(a, min(b, c)) -> min3(a, b, c)
9630     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9631       SDLoc DL(N);
9632       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9633                          DL,
9634                          N->getValueType(0),
9635                          Op0,
9636                          Op1.getOperand(0),
9637                          Op1.getOperand(1));
9638     }
9639   }
9640 
9641   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9642   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9643     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9644       return Med3;
9645   }
9646 
9647   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9648     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9649       return Med3;
9650   }
9651 
9652   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9653   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9654        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9655        (Opc == AMDGPUISD::FMIN_LEGACY &&
9656         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9657       (VT == MVT::f32 || VT == MVT::f64 ||
9658        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9659        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9660       Op0.hasOneUse()) {
9661     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9662       return Res;
9663   }
9664 
9665   return SDValue();
9666 }
9667 
9668 static bool isClampZeroToOne(SDValue A, SDValue B) {
9669   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9670     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9671       // FIXME: Should this be allowing -0.0?
9672       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9673              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9674     }
9675   }
9676 
9677   return false;
9678 }
9679 
9680 // FIXME: Should only worry about snans for version with chain.
9681 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9682                                               DAGCombinerInfo &DCI) const {
9683   EVT VT = N->getValueType(0);
9684   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9685   // NaNs. With a NaN input, the order of the operands may change the result.
9686 
9687   SelectionDAG &DAG = DCI.DAG;
9688   SDLoc SL(N);
9689 
9690   SDValue Src0 = N->getOperand(0);
9691   SDValue Src1 = N->getOperand(1);
9692   SDValue Src2 = N->getOperand(2);
9693 
9694   if (isClampZeroToOne(Src0, Src1)) {
9695     // const_a, const_b, x -> clamp is safe in all cases including signaling
9696     // nans.
9697     // FIXME: Should this be allowing -0.0?
9698     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9699   }
9700 
9701   const MachineFunction &MF = DAG.getMachineFunction();
9702   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9703 
9704   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9705   // handling no dx10-clamp?
9706   if (Info->getMode().DX10Clamp) {
9707     // If NaNs is clamped to 0, we are free to reorder the inputs.
9708 
9709     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9710       std::swap(Src0, Src1);
9711 
9712     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9713       std::swap(Src1, Src2);
9714 
9715     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9716       std::swap(Src0, Src1);
9717 
9718     if (isClampZeroToOne(Src1, Src2))
9719       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9720   }
9721 
9722   return SDValue();
9723 }
9724 
9725 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9726                                                  DAGCombinerInfo &DCI) const {
9727   SDValue Src0 = N->getOperand(0);
9728   SDValue Src1 = N->getOperand(1);
9729   if (Src0.isUndef() && Src1.isUndef())
9730     return DCI.DAG.getUNDEF(N->getValueType(0));
9731   return SDValue();
9732 }
9733 
9734 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9735 // expanded into a set of cmp/select instructions.
9736 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9737                                                 unsigned NumElem,
9738                                                 bool IsDivergentIdx) {
9739   if (UseDivergentRegisterIndexing)
9740     return false;
9741 
9742   unsigned VecSize = EltSize * NumElem;
9743 
9744   // Sub-dword vectors of size 2 dword or less have better implementation.
9745   if (VecSize <= 64 && EltSize < 32)
9746     return false;
9747 
9748   // Always expand the rest of sub-dword instructions, otherwise it will be
9749   // lowered via memory.
9750   if (EltSize < 32)
9751     return true;
9752 
9753   // Always do this if var-idx is divergent, otherwise it will become a loop.
9754   if (IsDivergentIdx)
9755     return true;
9756 
9757   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9758   unsigned NumInsts = NumElem /* Number of compares */ +
9759                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9760   return NumInsts <= 16;
9761 }
9762 
9763 static bool shouldExpandVectorDynExt(SDNode *N) {
9764   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9765   if (isa<ConstantSDNode>(Idx))
9766     return false;
9767 
9768   SDValue Vec = N->getOperand(0);
9769   EVT VecVT = Vec.getValueType();
9770   EVT EltVT = VecVT.getVectorElementType();
9771   unsigned EltSize = EltVT.getSizeInBits();
9772   unsigned NumElem = VecVT.getVectorNumElements();
9773 
9774   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9775                                                     Idx->isDivergent());
9776 }
9777 
9778 SDValue SITargetLowering::performExtractVectorEltCombine(
9779   SDNode *N, DAGCombinerInfo &DCI) const {
9780   SDValue Vec = N->getOperand(0);
9781   SelectionDAG &DAG = DCI.DAG;
9782 
9783   EVT VecVT = Vec.getValueType();
9784   EVT EltVT = VecVT.getVectorElementType();
9785 
9786   if ((Vec.getOpcode() == ISD::FNEG ||
9787        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9788     SDLoc SL(N);
9789     EVT EltVT = N->getValueType(0);
9790     SDValue Idx = N->getOperand(1);
9791     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9792                               Vec.getOperand(0), Idx);
9793     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9794   }
9795 
9796   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9797   //    =>
9798   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9799   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9800   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9801   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9802     SDLoc SL(N);
9803     EVT EltVT = N->getValueType(0);
9804     SDValue Idx = N->getOperand(1);
9805     unsigned Opc = Vec.getOpcode();
9806 
9807     switch(Opc) {
9808     default:
9809       break;
9810       // TODO: Support other binary operations.
9811     case ISD::FADD:
9812     case ISD::FSUB:
9813     case ISD::FMUL:
9814     case ISD::ADD:
9815     case ISD::UMIN:
9816     case ISD::UMAX:
9817     case ISD::SMIN:
9818     case ISD::SMAX:
9819     case ISD::FMAXNUM:
9820     case ISD::FMINNUM:
9821     case ISD::FMAXNUM_IEEE:
9822     case ISD::FMINNUM_IEEE: {
9823       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9824                                  Vec.getOperand(0), Idx);
9825       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9826                                  Vec.getOperand(1), Idx);
9827 
9828       DCI.AddToWorklist(Elt0.getNode());
9829       DCI.AddToWorklist(Elt1.getNode());
9830       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9831     }
9832     }
9833   }
9834 
9835   unsigned VecSize = VecVT.getSizeInBits();
9836   unsigned EltSize = EltVT.getSizeInBits();
9837 
9838   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9839   if (::shouldExpandVectorDynExt(N)) {
9840     SDLoc SL(N);
9841     SDValue Idx = N->getOperand(1);
9842     SDValue V;
9843     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9844       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9845       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9846       if (I == 0)
9847         V = Elt;
9848       else
9849         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9850     }
9851     return V;
9852   }
9853 
9854   if (!DCI.isBeforeLegalize())
9855     return SDValue();
9856 
9857   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9858   // elements. This exposes more load reduction opportunities by replacing
9859   // multiple small extract_vector_elements with a single 32-bit extract.
9860   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9861   if (isa<MemSDNode>(Vec) &&
9862       EltSize <= 16 &&
9863       EltVT.isByteSized() &&
9864       VecSize > 32 &&
9865       VecSize % 32 == 0 &&
9866       Idx) {
9867     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9868 
9869     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9870     unsigned EltIdx = BitIndex / 32;
9871     unsigned LeftoverBitIdx = BitIndex % 32;
9872     SDLoc SL(N);
9873 
9874     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9875     DCI.AddToWorklist(Cast.getNode());
9876 
9877     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9878                               DAG.getConstant(EltIdx, SL, MVT::i32));
9879     DCI.AddToWorklist(Elt.getNode());
9880     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9881                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9882     DCI.AddToWorklist(Srl.getNode());
9883 
9884     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9885     DCI.AddToWorklist(Trunc.getNode());
9886     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9887   }
9888 
9889   return SDValue();
9890 }
9891 
9892 SDValue
9893 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9894                                                 DAGCombinerInfo &DCI) const {
9895   SDValue Vec = N->getOperand(0);
9896   SDValue Idx = N->getOperand(2);
9897   EVT VecVT = Vec.getValueType();
9898   EVT EltVT = VecVT.getVectorElementType();
9899 
9900   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9901   // => BUILD_VECTOR n x select (e, const-idx)
9902   if (!::shouldExpandVectorDynExt(N))
9903     return SDValue();
9904 
9905   SelectionDAG &DAG = DCI.DAG;
9906   SDLoc SL(N);
9907   SDValue Ins = N->getOperand(1);
9908   EVT IdxVT = Idx.getValueType();
9909 
9910   SmallVector<SDValue, 16> Ops;
9911   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9912     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9913     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9914     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9915     Ops.push_back(V);
9916   }
9917 
9918   return DAG.getBuildVector(VecVT, SL, Ops);
9919 }
9920 
9921 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9922                                           const SDNode *N0,
9923                                           const SDNode *N1) const {
9924   EVT VT = N0->getValueType(0);
9925 
9926   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9927   // support denormals ever.
9928   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9929        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9930         getSubtarget()->hasMadF16())) &&
9931        isOperationLegal(ISD::FMAD, VT))
9932     return ISD::FMAD;
9933 
9934   const TargetOptions &Options = DAG.getTarget().Options;
9935   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9936        (N0->getFlags().hasAllowContract() &&
9937         N1->getFlags().hasAllowContract())) &&
9938       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9939     return ISD::FMA;
9940   }
9941 
9942   return 0;
9943 }
9944 
9945 // For a reassociatable opcode perform:
9946 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9947 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9948                                                SelectionDAG &DAG) const {
9949   EVT VT = N->getValueType(0);
9950   if (VT != MVT::i32 && VT != MVT::i64)
9951     return SDValue();
9952 
9953   unsigned Opc = N->getOpcode();
9954   SDValue Op0 = N->getOperand(0);
9955   SDValue Op1 = N->getOperand(1);
9956 
9957   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9958     return SDValue();
9959 
9960   if (Op0->isDivergent())
9961     std::swap(Op0, Op1);
9962 
9963   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9964     return SDValue();
9965 
9966   SDValue Op2 = Op1.getOperand(1);
9967   Op1 = Op1.getOperand(0);
9968   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9969     return SDValue();
9970 
9971   if (Op1->isDivergent())
9972     std::swap(Op1, Op2);
9973 
9974   // If either operand is constant this will conflict with
9975   // DAGCombiner::ReassociateOps().
9976   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9977       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9978     return SDValue();
9979 
9980   SDLoc SL(N);
9981   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9982   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9983 }
9984 
9985 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9986                            EVT VT,
9987                            SDValue N0, SDValue N1, SDValue N2,
9988                            bool Signed) {
9989   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9990   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9991   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9992   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9993 }
9994 
9995 SDValue SITargetLowering::performAddCombine(SDNode *N,
9996                                             DAGCombinerInfo &DCI) const {
9997   SelectionDAG &DAG = DCI.DAG;
9998   EVT VT = N->getValueType(0);
9999   SDLoc SL(N);
10000   SDValue LHS = N->getOperand(0);
10001   SDValue RHS = N->getOperand(1);
10002 
10003   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10004       && Subtarget->hasMad64_32() &&
10005       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10006       VT.getScalarSizeInBits() <= 64) {
10007     if (LHS.getOpcode() != ISD::MUL)
10008       std::swap(LHS, RHS);
10009 
10010     SDValue MulLHS = LHS.getOperand(0);
10011     SDValue MulRHS = LHS.getOperand(1);
10012     SDValue AddRHS = RHS;
10013 
10014     // TODO: Maybe restrict if SGPR inputs.
10015     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10016         numBitsUnsigned(MulRHS, DAG) <= 32) {
10017       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10018       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10019       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10020       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10021     }
10022 
10023     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10024       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10025       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10026       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10027       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10028     }
10029 
10030     return SDValue();
10031   }
10032 
10033   if (SDValue V = reassociateScalarOps(N, DAG)) {
10034     return V;
10035   }
10036 
10037   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10038     return SDValue();
10039 
10040   // add x, zext (setcc) => addcarry x, 0, setcc
10041   // add x, sext (setcc) => subcarry x, 0, setcc
10042   unsigned Opc = LHS.getOpcode();
10043   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10044       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10045     std::swap(RHS, LHS);
10046 
10047   Opc = RHS.getOpcode();
10048   switch (Opc) {
10049   default: break;
10050   case ISD::ZERO_EXTEND:
10051   case ISD::SIGN_EXTEND:
10052   case ISD::ANY_EXTEND: {
10053     auto Cond = RHS.getOperand(0);
10054     // If this won't be a real VOPC output, we would still need to insert an
10055     // extra instruction anyway.
10056     if (!isBoolSGPR(Cond))
10057       break;
10058     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10059     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10060     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10061     return DAG.getNode(Opc, SL, VTList, Args);
10062   }
10063   case ISD::ADDCARRY: {
10064     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10065     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10066     if (!C || C->getZExtValue() != 0) break;
10067     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10068     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10069   }
10070   }
10071   return SDValue();
10072 }
10073 
10074 SDValue SITargetLowering::performSubCombine(SDNode *N,
10075                                             DAGCombinerInfo &DCI) const {
10076   SelectionDAG &DAG = DCI.DAG;
10077   EVT VT = N->getValueType(0);
10078 
10079   if (VT != MVT::i32)
10080     return SDValue();
10081 
10082   SDLoc SL(N);
10083   SDValue LHS = N->getOperand(0);
10084   SDValue RHS = N->getOperand(1);
10085 
10086   // sub x, zext (setcc) => subcarry x, 0, setcc
10087   // sub x, sext (setcc) => addcarry x, 0, setcc
10088   unsigned Opc = RHS.getOpcode();
10089   switch (Opc) {
10090   default: break;
10091   case ISD::ZERO_EXTEND:
10092   case ISD::SIGN_EXTEND:
10093   case ISD::ANY_EXTEND: {
10094     auto Cond = RHS.getOperand(0);
10095     // If this won't be a real VOPC output, we would still need to insert an
10096     // extra instruction anyway.
10097     if (!isBoolSGPR(Cond))
10098       break;
10099     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10100     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10101     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10102     return DAG.getNode(Opc, SL, VTList, Args);
10103   }
10104   }
10105 
10106   if (LHS.getOpcode() == ISD::SUBCARRY) {
10107     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10108     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10109     if (!C || !C->isNullValue())
10110       return SDValue();
10111     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10112     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10113   }
10114   return SDValue();
10115 }
10116 
10117 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10118   DAGCombinerInfo &DCI) const {
10119 
10120   if (N->getValueType(0) != MVT::i32)
10121     return SDValue();
10122 
10123   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10124   if (!C || C->getZExtValue() != 0)
10125     return SDValue();
10126 
10127   SelectionDAG &DAG = DCI.DAG;
10128   SDValue LHS = N->getOperand(0);
10129 
10130   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10131   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10132   unsigned LHSOpc = LHS.getOpcode();
10133   unsigned Opc = N->getOpcode();
10134   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10135       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10136     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10137     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10138   }
10139   return SDValue();
10140 }
10141 
10142 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10143                                              DAGCombinerInfo &DCI) const {
10144   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10145     return SDValue();
10146 
10147   SelectionDAG &DAG = DCI.DAG;
10148   EVT VT = N->getValueType(0);
10149 
10150   SDLoc SL(N);
10151   SDValue LHS = N->getOperand(0);
10152   SDValue RHS = N->getOperand(1);
10153 
10154   // These should really be instruction patterns, but writing patterns with
10155   // source modiifiers is a pain.
10156 
10157   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10158   if (LHS.getOpcode() == ISD::FADD) {
10159     SDValue A = LHS.getOperand(0);
10160     if (A == LHS.getOperand(1)) {
10161       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10162       if (FusedOp != 0) {
10163         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10164         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10165       }
10166     }
10167   }
10168 
10169   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10170   if (RHS.getOpcode() == ISD::FADD) {
10171     SDValue A = RHS.getOperand(0);
10172     if (A == RHS.getOperand(1)) {
10173       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10174       if (FusedOp != 0) {
10175         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10176         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10177       }
10178     }
10179   }
10180 
10181   return SDValue();
10182 }
10183 
10184 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10185                                              DAGCombinerInfo &DCI) const {
10186   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10187     return SDValue();
10188 
10189   SelectionDAG &DAG = DCI.DAG;
10190   SDLoc SL(N);
10191   EVT VT = N->getValueType(0);
10192   assert(!VT.isVector());
10193 
10194   // Try to get the fneg to fold into the source modifier. This undoes generic
10195   // DAG combines and folds them into the mad.
10196   //
10197   // Only do this if we are not trying to support denormals. v_mad_f32 does
10198   // not support denormals ever.
10199   SDValue LHS = N->getOperand(0);
10200   SDValue RHS = N->getOperand(1);
10201   if (LHS.getOpcode() == ISD::FADD) {
10202     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10203     SDValue A = LHS.getOperand(0);
10204     if (A == LHS.getOperand(1)) {
10205       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10206       if (FusedOp != 0){
10207         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10208         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10209 
10210         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10211       }
10212     }
10213   }
10214 
10215   if (RHS.getOpcode() == ISD::FADD) {
10216     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10217 
10218     SDValue A = RHS.getOperand(0);
10219     if (A == RHS.getOperand(1)) {
10220       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10221       if (FusedOp != 0){
10222         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10223         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10224       }
10225     }
10226   }
10227 
10228   return SDValue();
10229 }
10230 
10231 SDValue SITargetLowering::performFMACombine(SDNode *N,
10232                                             DAGCombinerInfo &DCI) const {
10233   SelectionDAG &DAG = DCI.DAG;
10234   EVT VT = N->getValueType(0);
10235   SDLoc SL(N);
10236 
10237   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10238     return SDValue();
10239 
10240   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10241   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10242   SDValue Op1 = N->getOperand(0);
10243   SDValue Op2 = N->getOperand(1);
10244   SDValue FMA = N->getOperand(2);
10245 
10246   if (FMA.getOpcode() != ISD::FMA ||
10247       Op1.getOpcode() != ISD::FP_EXTEND ||
10248       Op2.getOpcode() != ISD::FP_EXTEND)
10249     return SDValue();
10250 
10251   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10252   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10253   // is sufficient to allow generaing fdot2.
10254   const TargetOptions &Options = DAG.getTarget().Options;
10255   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10256       (N->getFlags().hasAllowContract() &&
10257        FMA->getFlags().hasAllowContract())) {
10258     Op1 = Op1.getOperand(0);
10259     Op2 = Op2.getOperand(0);
10260     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10261         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10262       return SDValue();
10263 
10264     SDValue Vec1 = Op1.getOperand(0);
10265     SDValue Idx1 = Op1.getOperand(1);
10266     SDValue Vec2 = Op2.getOperand(0);
10267 
10268     SDValue FMAOp1 = FMA.getOperand(0);
10269     SDValue FMAOp2 = FMA.getOperand(1);
10270     SDValue FMAAcc = FMA.getOperand(2);
10271 
10272     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10273         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10274       return SDValue();
10275 
10276     FMAOp1 = FMAOp1.getOperand(0);
10277     FMAOp2 = FMAOp2.getOperand(0);
10278     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10279         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10280       return SDValue();
10281 
10282     SDValue Vec3 = FMAOp1.getOperand(0);
10283     SDValue Vec4 = FMAOp2.getOperand(0);
10284     SDValue Idx2 = FMAOp1.getOperand(1);
10285 
10286     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10287         // Idx1 and Idx2 cannot be the same.
10288         Idx1 == Idx2)
10289       return SDValue();
10290 
10291     if (Vec1 == Vec2 || Vec3 == Vec4)
10292       return SDValue();
10293 
10294     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10295       return SDValue();
10296 
10297     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10298         (Vec1 == Vec4 && Vec2 == Vec3)) {
10299       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10300                          DAG.getTargetConstant(0, SL, MVT::i1));
10301     }
10302   }
10303   return SDValue();
10304 }
10305 
10306 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10307                                               DAGCombinerInfo &DCI) const {
10308   SelectionDAG &DAG = DCI.DAG;
10309   SDLoc SL(N);
10310 
10311   SDValue LHS = N->getOperand(0);
10312   SDValue RHS = N->getOperand(1);
10313   EVT VT = LHS.getValueType();
10314   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10315 
10316   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10317   if (!CRHS) {
10318     CRHS = dyn_cast<ConstantSDNode>(LHS);
10319     if (CRHS) {
10320       std::swap(LHS, RHS);
10321       CC = getSetCCSwappedOperands(CC);
10322     }
10323   }
10324 
10325   if (CRHS) {
10326     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10327         isBoolSGPR(LHS.getOperand(0))) {
10328       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10329       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10330       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10331       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10332       if ((CRHS->isAllOnesValue() &&
10333            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10334           (CRHS->isNullValue() &&
10335            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10336         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10337                            DAG.getConstant(-1, SL, MVT::i1));
10338       if ((CRHS->isAllOnesValue() &&
10339            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10340           (CRHS->isNullValue() &&
10341            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10342         return LHS.getOperand(0);
10343     }
10344 
10345     uint64_t CRHSVal = CRHS->getZExtValue();
10346     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10347         LHS.getOpcode() == ISD::SELECT &&
10348         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10349         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10350         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10351         isBoolSGPR(LHS.getOperand(0))) {
10352       // Given CT != FT:
10353       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10354       // setcc (select cc, CT, CF), CF, ne => cc
10355       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10356       // setcc (select cc, CT, CF), CT, eq => cc
10357       uint64_t CT = LHS.getConstantOperandVal(1);
10358       uint64_t CF = LHS.getConstantOperandVal(2);
10359 
10360       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10361           (CT == CRHSVal && CC == ISD::SETNE))
10362         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10363                            DAG.getConstant(-1, SL, MVT::i1));
10364       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10365           (CT == CRHSVal && CC == ISD::SETEQ))
10366         return LHS.getOperand(0);
10367     }
10368   }
10369 
10370   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10371                                            VT != MVT::f16))
10372     return SDValue();
10373 
10374   // Match isinf/isfinite pattern
10375   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10376   // (fcmp one (fabs x), inf) -> (fp_class x,
10377   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10378   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10379     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10380     if (!CRHS)
10381       return SDValue();
10382 
10383     const APFloat &APF = CRHS->getValueAPF();
10384     if (APF.isInfinity() && !APF.isNegative()) {
10385       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10386                                  SIInstrFlags::N_INFINITY;
10387       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10388                                     SIInstrFlags::P_ZERO |
10389                                     SIInstrFlags::N_NORMAL |
10390                                     SIInstrFlags::P_NORMAL |
10391                                     SIInstrFlags::N_SUBNORMAL |
10392                                     SIInstrFlags::P_SUBNORMAL;
10393       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10394       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10395                          DAG.getConstant(Mask, SL, MVT::i32));
10396     }
10397   }
10398 
10399   return SDValue();
10400 }
10401 
10402 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10403                                                      DAGCombinerInfo &DCI) const {
10404   SelectionDAG &DAG = DCI.DAG;
10405   SDLoc SL(N);
10406   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10407 
10408   SDValue Src = N->getOperand(0);
10409   SDValue Shift = N->getOperand(0);
10410 
10411   // TODO: Extend type shouldn't matter (assuming legal types).
10412   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10413     Shift = Shift.getOperand(0);
10414 
10415   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10416     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10417     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10418     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10419     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10420     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10421     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10422       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10423                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10424 
10425       unsigned ShiftOffset = 8 * Offset;
10426       if (Shift.getOpcode() == ISD::SHL)
10427         ShiftOffset -= C->getZExtValue();
10428       else
10429         ShiftOffset += C->getZExtValue();
10430 
10431       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10432         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10433                            MVT::f32, Shift);
10434       }
10435     }
10436   }
10437 
10438   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10439   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10440   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10441     // We simplified Src. If this node is not dead, visit it again so it is
10442     // folded properly.
10443     if (N->getOpcode() != ISD::DELETED_NODE)
10444       DCI.AddToWorklist(N);
10445     return SDValue(N, 0);
10446   }
10447 
10448   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10449   if (SDValue DemandedSrc =
10450           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10451     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10452 
10453   return SDValue();
10454 }
10455 
10456 SDValue SITargetLowering::performClampCombine(SDNode *N,
10457                                               DAGCombinerInfo &DCI) const {
10458   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10459   if (!CSrc)
10460     return SDValue();
10461 
10462   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10463   const APFloat &F = CSrc->getValueAPF();
10464   APFloat Zero = APFloat::getZero(F.getSemantics());
10465   if (F < Zero ||
10466       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10467     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10468   }
10469 
10470   APFloat One(F.getSemantics(), "1.0");
10471   if (F > One)
10472     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10473 
10474   return SDValue(CSrc, 0);
10475 }
10476 
10477 
10478 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10479                                             DAGCombinerInfo &DCI) const {
10480   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10481     return SDValue();
10482   switch (N->getOpcode()) {
10483   case ISD::ADD:
10484     return performAddCombine(N, DCI);
10485   case ISD::SUB:
10486     return performSubCombine(N, DCI);
10487   case ISD::ADDCARRY:
10488   case ISD::SUBCARRY:
10489     return performAddCarrySubCarryCombine(N, DCI);
10490   case ISD::FADD:
10491     return performFAddCombine(N, DCI);
10492   case ISD::FSUB:
10493     return performFSubCombine(N, DCI);
10494   case ISD::SETCC:
10495     return performSetCCCombine(N, DCI);
10496   case ISD::FMAXNUM:
10497   case ISD::FMINNUM:
10498   case ISD::FMAXNUM_IEEE:
10499   case ISD::FMINNUM_IEEE:
10500   case ISD::SMAX:
10501   case ISD::SMIN:
10502   case ISD::UMAX:
10503   case ISD::UMIN:
10504   case AMDGPUISD::FMIN_LEGACY:
10505   case AMDGPUISD::FMAX_LEGACY:
10506     return performMinMaxCombine(N, DCI);
10507   case ISD::FMA:
10508     return performFMACombine(N, DCI);
10509   case ISD::AND:
10510     return performAndCombine(N, DCI);
10511   case ISD::OR:
10512     return performOrCombine(N, DCI);
10513   case ISD::XOR:
10514     return performXorCombine(N, DCI);
10515   case ISD::ZERO_EXTEND:
10516     return performZeroExtendCombine(N, DCI);
10517   case ISD::SIGN_EXTEND_INREG:
10518     return performSignExtendInRegCombine(N , DCI);
10519   case AMDGPUISD::FP_CLASS:
10520     return performClassCombine(N, DCI);
10521   case ISD::FCANONICALIZE:
10522     return performFCanonicalizeCombine(N, DCI);
10523   case AMDGPUISD::RCP:
10524     return performRcpCombine(N, DCI);
10525   case AMDGPUISD::FRACT:
10526   case AMDGPUISD::RSQ:
10527   case AMDGPUISD::RCP_LEGACY:
10528   case AMDGPUISD::RCP_IFLAG:
10529   case AMDGPUISD::RSQ_CLAMP:
10530   case AMDGPUISD::LDEXP: {
10531     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10532     SDValue Src = N->getOperand(0);
10533     if (Src.isUndef())
10534       return Src;
10535     break;
10536   }
10537   case ISD::SINT_TO_FP:
10538   case ISD::UINT_TO_FP:
10539     return performUCharToFloatCombine(N, DCI);
10540   case AMDGPUISD::CVT_F32_UBYTE0:
10541   case AMDGPUISD::CVT_F32_UBYTE1:
10542   case AMDGPUISD::CVT_F32_UBYTE2:
10543   case AMDGPUISD::CVT_F32_UBYTE3:
10544     return performCvtF32UByteNCombine(N, DCI);
10545   case AMDGPUISD::FMED3:
10546     return performFMed3Combine(N, DCI);
10547   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10548     return performCvtPkRTZCombine(N, DCI);
10549   case AMDGPUISD::CLAMP:
10550     return performClampCombine(N, DCI);
10551   case ISD::SCALAR_TO_VECTOR: {
10552     SelectionDAG &DAG = DCI.DAG;
10553     EVT VT = N->getValueType(0);
10554 
10555     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10556     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10557       SDLoc SL(N);
10558       SDValue Src = N->getOperand(0);
10559       EVT EltVT = Src.getValueType();
10560       if (EltVT == MVT::f16)
10561         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10562 
10563       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10564       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10565     }
10566 
10567     break;
10568   }
10569   case ISD::EXTRACT_VECTOR_ELT:
10570     return performExtractVectorEltCombine(N, DCI);
10571   case ISD::INSERT_VECTOR_ELT:
10572     return performInsertVectorEltCombine(N, DCI);
10573   case ISD::LOAD: {
10574     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10575       return Widended;
10576     LLVM_FALLTHROUGH;
10577   }
10578   default: {
10579     if (!DCI.isBeforeLegalize()) {
10580       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10581         return performMemSDNodeCombine(MemNode, DCI);
10582     }
10583 
10584     break;
10585   }
10586   }
10587 
10588   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10589 }
10590 
10591 /// Helper function for adjustWritemask
10592 static unsigned SubIdx2Lane(unsigned Idx) {
10593   switch (Idx) {
10594   default: return 0;
10595   case AMDGPU::sub0: return 0;
10596   case AMDGPU::sub1: return 1;
10597   case AMDGPU::sub2: return 2;
10598   case AMDGPU::sub3: return 3;
10599   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10600   }
10601 }
10602 
10603 /// Adjust the writemask of MIMG instructions
10604 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10605                                           SelectionDAG &DAG) const {
10606   unsigned Opcode = Node->getMachineOpcode();
10607 
10608   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10609   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10610   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10611     return Node; // not implemented for D16
10612 
10613   SDNode *Users[5] = { nullptr };
10614   unsigned Lane = 0;
10615   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10616   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10617   unsigned NewDmask = 0;
10618   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10619   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10620   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10621                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10622   unsigned TFCLane = 0;
10623   bool HasChain = Node->getNumValues() > 1;
10624 
10625   if (OldDmask == 0) {
10626     // These are folded out, but on the chance it happens don't assert.
10627     return Node;
10628   }
10629 
10630   unsigned OldBitsSet = countPopulation(OldDmask);
10631   // Work out which is the TFE/LWE lane if that is enabled.
10632   if (UsesTFC) {
10633     TFCLane = OldBitsSet;
10634   }
10635 
10636   // Try to figure out the used register components
10637   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10638        I != E; ++I) {
10639 
10640     // Don't look at users of the chain.
10641     if (I.getUse().getResNo() != 0)
10642       continue;
10643 
10644     // Abort if we can't understand the usage
10645     if (!I->isMachineOpcode() ||
10646         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10647       return Node;
10648 
10649     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10650     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10651     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10652     // set, etc.
10653     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10654 
10655     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10656     if (UsesTFC && Lane == TFCLane) {
10657       Users[Lane] = *I;
10658     } else {
10659       // Set which texture component corresponds to the lane.
10660       unsigned Comp;
10661       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10662         Comp = countTrailingZeros(Dmask);
10663         Dmask &= ~(1 << Comp);
10664       }
10665 
10666       // Abort if we have more than one user per component.
10667       if (Users[Lane])
10668         return Node;
10669 
10670       Users[Lane] = *I;
10671       NewDmask |= 1 << Comp;
10672     }
10673   }
10674 
10675   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10676   bool NoChannels = !NewDmask;
10677   if (NoChannels) {
10678     if (!UsesTFC) {
10679       // No uses of the result and not using TFC. Then do nothing.
10680       return Node;
10681     }
10682     // If the original dmask has one channel - then nothing to do
10683     if (OldBitsSet == 1)
10684       return Node;
10685     // Use an arbitrary dmask - required for the instruction to work
10686     NewDmask = 1;
10687   }
10688   // Abort if there's no change
10689   if (NewDmask == OldDmask)
10690     return Node;
10691 
10692   unsigned BitsSet = countPopulation(NewDmask);
10693 
10694   // Check for TFE or LWE - increase the number of channels by one to account
10695   // for the extra return value
10696   // This will need adjustment for D16 if this is also included in
10697   // adjustWriteMask (this function) but at present D16 are excluded.
10698   unsigned NewChannels = BitsSet + UsesTFC;
10699 
10700   int NewOpcode =
10701       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10702   assert(NewOpcode != -1 &&
10703          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10704          "failed to find equivalent MIMG op");
10705 
10706   // Adjust the writemask in the node
10707   SmallVector<SDValue, 12> Ops;
10708   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10709   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10710   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10711 
10712   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10713 
10714   MVT ResultVT = NewChannels == 1 ?
10715     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10716                            NewChannels == 5 ? 8 : NewChannels);
10717   SDVTList NewVTList = HasChain ?
10718     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10719 
10720 
10721   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10722                                               NewVTList, Ops);
10723 
10724   if (HasChain) {
10725     // Update chain.
10726     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10727     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10728   }
10729 
10730   if (NewChannels == 1) {
10731     assert(Node->hasNUsesOfValue(1, 0));
10732     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10733                                       SDLoc(Node), Users[Lane]->getValueType(0),
10734                                       SDValue(NewNode, 0));
10735     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10736     return nullptr;
10737   }
10738 
10739   // Update the users of the node with the new indices
10740   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10741     SDNode *User = Users[i];
10742     if (!User) {
10743       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10744       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10745       if (i || !NoChannels)
10746         continue;
10747     } else {
10748       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10749       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10750     }
10751 
10752     switch (Idx) {
10753     default: break;
10754     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10755     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10756     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10757     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10758     }
10759   }
10760 
10761   DAG.RemoveDeadNode(Node);
10762   return nullptr;
10763 }
10764 
10765 static bool isFrameIndexOp(SDValue Op) {
10766   if (Op.getOpcode() == ISD::AssertZext)
10767     Op = Op.getOperand(0);
10768 
10769   return isa<FrameIndexSDNode>(Op);
10770 }
10771 
10772 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10773 /// with frame index operands.
10774 /// LLVM assumes that inputs are to these instructions are registers.
10775 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10776                                                         SelectionDAG &DAG) const {
10777   if (Node->getOpcode() == ISD::CopyToReg) {
10778     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10779     SDValue SrcVal = Node->getOperand(2);
10780 
10781     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10782     // to try understanding copies to physical registers.
10783     if (SrcVal.getValueType() == MVT::i1 &&
10784         Register::isPhysicalRegister(DestReg->getReg())) {
10785       SDLoc SL(Node);
10786       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10787       SDValue VReg = DAG.getRegister(
10788         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10789 
10790       SDNode *Glued = Node->getGluedNode();
10791       SDValue ToVReg
10792         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10793                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10794       SDValue ToResultReg
10795         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10796                            VReg, ToVReg.getValue(1));
10797       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10798       DAG.RemoveDeadNode(Node);
10799       return ToResultReg.getNode();
10800     }
10801   }
10802 
10803   SmallVector<SDValue, 8> Ops;
10804   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10805     if (!isFrameIndexOp(Node->getOperand(i))) {
10806       Ops.push_back(Node->getOperand(i));
10807       continue;
10808     }
10809 
10810     SDLoc DL(Node);
10811     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10812                                      Node->getOperand(i).getValueType(),
10813                                      Node->getOperand(i)), 0));
10814   }
10815 
10816   return DAG.UpdateNodeOperands(Node, Ops);
10817 }
10818 
10819 /// Fold the instructions after selecting them.
10820 /// Returns null if users were already updated.
10821 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10822                                           SelectionDAG &DAG) const {
10823   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10824   unsigned Opcode = Node->getMachineOpcode();
10825 
10826   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10827       !TII->isGather4(Opcode)) {
10828     return adjustWritemask(Node, DAG);
10829   }
10830 
10831   if (Opcode == AMDGPU::INSERT_SUBREG ||
10832       Opcode == AMDGPU::REG_SEQUENCE) {
10833     legalizeTargetIndependentNode(Node, DAG);
10834     return Node;
10835   }
10836 
10837   switch (Opcode) {
10838   case AMDGPU::V_DIV_SCALE_F32:
10839   case AMDGPU::V_DIV_SCALE_F64: {
10840     // Satisfy the operand register constraint when one of the inputs is
10841     // undefined. Ordinarily each undef value will have its own implicit_def of
10842     // a vreg, so force these to use a single register.
10843     SDValue Src0 = Node->getOperand(0);
10844     SDValue Src1 = Node->getOperand(1);
10845     SDValue Src2 = Node->getOperand(2);
10846 
10847     if ((Src0.isMachineOpcode() &&
10848          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10849         (Src0 == Src1 || Src0 == Src2))
10850       break;
10851 
10852     MVT VT = Src0.getValueType().getSimpleVT();
10853     const TargetRegisterClass *RC =
10854         getRegClassFor(VT, Src0.getNode()->isDivergent());
10855 
10856     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10857     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10858 
10859     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10860                                       UndefReg, Src0, SDValue());
10861 
10862     // src0 must be the same register as src1 or src2, even if the value is
10863     // undefined, so make sure we don't violate this constraint.
10864     if (Src0.isMachineOpcode() &&
10865         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10866       if (Src1.isMachineOpcode() &&
10867           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10868         Src0 = Src1;
10869       else if (Src2.isMachineOpcode() &&
10870                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10871         Src0 = Src2;
10872       else {
10873         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10874         Src0 = UndefReg;
10875         Src1 = UndefReg;
10876       }
10877     } else
10878       break;
10879 
10880     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10881     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10882       Ops.push_back(Node->getOperand(I));
10883 
10884     Ops.push_back(ImpDef.getValue(1));
10885     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10886   }
10887   default:
10888     break;
10889   }
10890 
10891   return Node;
10892 }
10893 
10894 /// Assign the register class depending on the number of
10895 /// bits set in the writemask
10896 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10897                                                      SDNode *Node) const {
10898   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10899 
10900   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10901 
10902   if (TII->isVOP3(MI.getOpcode())) {
10903     // Make sure constant bus requirements are respected.
10904     TII->legalizeOperandsVOP3(MRI, MI);
10905 
10906     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10907     // This saves a chain-copy of registers and better ballance register
10908     // use between vgpr and agpr as agpr tuples tend to be big.
10909     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10910       unsigned Opc = MI.getOpcode();
10911       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10912       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10913                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10914         if (I == -1)
10915           break;
10916         MachineOperand &Op = MI.getOperand(I);
10917         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10918              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10919             !Register::isVirtualRegister(Op.getReg()) ||
10920             !TRI->isAGPR(MRI, Op.getReg()))
10921           continue;
10922         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10923         if (!Src || !Src->isCopy() ||
10924             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10925           continue;
10926         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10927         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10928         // All uses of agpr64 and agpr32 can also accept vgpr except for
10929         // v_accvgpr_read, but we do not produce agpr reads during selection,
10930         // so no use checks are needed.
10931         MRI.setRegClass(Op.getReg(), NewRC);
10932       }
10933     }
10934 
10935     return;
10936   }
10937 
10938   // Replace unused atomics with the no return version.
10939   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10940   if (NoRetAtomicOp != -1) {
10941     if (!Node->hasAnyUseOfValue(0)) {
10942       MI.setDesc(TII->get(NoRetAtomicOp));
10943       MI.RemoveOperand(0);
10944       return;
10945     }
10946 
10947     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10948     // instruction, because the return type of these instructions is a vec2 of
10949     // the memory type, so it can be tied to the input operand.
10950     // This means these instructions always have a use, so we need to add a
10951     // special case to check if the atomic has only one extract_subreg use,
10952     // which itself has no uses.
10953     if ((Node->hasNUsesOfValue(1, 0) &&
10954          Node->use_begin()->isMachineOpcode() &&
10955          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10956          !Node->use_begin()->hasAnyUseOfValue(0))) {
10957       Register Def = MI.getOperand(0).getReg();
10958 
10959       // Change this into a noret atomic.
10960       MI.setDesc(TII->get(NoRetAtomicOp));
10961       MI.RemoveOperand(0);
10962 
10963       // If we only remove the def operand from the atomic instruction, the
10964       // extract_subreg will be left with a use of a vreg without a def.
10965       // So we need to insert an implicit_def to avoid machine verifier
10966       // errors.
10967       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10968               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10969     }
10970     return;
10971   }
10972 }
10973 
10974 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10975                               uint64_t Val) {
10976   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10977   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10978 }
10979 
10980 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10981                                                 const SDLoc &DL,
10982                                                 SDValue Ptr) const {
10983   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10984 
10985   // Build the half of the subregister with the constants before building the
10986   // full 128-bit register. If we are building multiple resource descriptors,
10987   // this will allow CSEing of the 2-component register.
10988   const SDValue Ops0[] = {
10989     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10990     buildSMovImm32(DAG, DL, 0),
10991     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10992     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10993     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10994   };
10995 
10996   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10997                                                 MVT::v2i32, Ops0), 0);
10998 
10999   // Combine the constants and the pointer.
11000   const SDValue Ops1[] = {
11001     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11002     Ptr,
11003     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11004     SubRegHi,
11005     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11006   };
11007 
11008   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11009 }
11010 
11011 /// Return a resource descriptor with the 'Add TID' bit enabled
11012 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11013 ///        of the resource descriptor) to create an offset, which is added to
11014 ///        the resource pointer.
11015 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11016                                            SDValue Ptr, uint32_t RsrcDword1,
11017                                            uint64_t RsrcDword2And3) const {
11018   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11019   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11020   if (RsrcDword1) {
11021     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11022                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11023                     0);
11024   }
11025 
11026   SDValue DataLo = buildSMovImm32(DAG, DL,
11027                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11028   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11029 
11030   const SDValue Ops[] = {
11031     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11032     PtrLo,
11033     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11034     PtrHi,
11035     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11036     DataLo,
11037     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11038     DataHi,
11039     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11040   };
11041 
11042   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11043 }
11044 
11045 //===----------------------------------------------------------------------===//
11046 //                         SI Inline Assembly Support
11047 //===----------------------------------------------------------------------===//
11048 
11049 std::pair<unsigned, const TargetRegisterClass *>
11050 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11051                                                StringRef Constraint,
11052                                                MVT VT) const {
11053   const TargetRegisterClass *RC = nullptr;
11054   if (Constraint.size() == 1) {
11055     const unsigned BitWidth = VT.getSizeInBits();
11056     switch (Constraint[0]) {
11057     default:
11058       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11059     case 's':
11060     case 'r':
11061       switch (BitWidth) {
11062       case 16:
11063         RC = &AMDGPU::SReg_32RegClass;
11064         break;
11065       case 64:
11066         RC = &AMDGPU::SGPR_64RegClass;
11067         break;
11068       default:
11069         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11070         if (!RC)
11071           return std::make_pair(0U, nullptr);
11072         break;
11073       }
11074       break;
11075     case 'v':
11076       switch (BitWidth) {
11077       case 16:
11078         RC = &AMDGPU::VGPR_32RegClass;
11079         break;
11080       default:
11081         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11082         if (!RC)
11083           return std::make_pair(0U, nullptr);
11084         break;
11085       }
11086       break;
11087     case 'a':
11088       if (!Subtarget->hasMAIInsts())
11089         break;
11090       switch (BitWidth) {
11091       case 16:
11092         RC = &AMDGPU::AGPR_32RegClass;
11093         break;
11094       default:
11095         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11096         if (!RC)
11097           return std::make_pair(0U, nullptr);
11098         break;
11099       }
11100       break;
11101     }
11102     // We actually support i128, i16 and f16 as inline parameters
11103     // even if they are not reported as legal
11104     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11105                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11106       return std::make_pair(0U, RC);
11107   }
11108 
11109   if (Constraint.size() > 1) {
11110     if (Constraint[1] == 'v') {
11111       RC = &AMDGPU::VGPR_32RegClass;
11112     } else if (Constraint[1] == 's') {
11113       RC = &AMDGPU::SGPR_32RegClass;
11114     } else if (Constraint[1] == 'a') {
11115       RC = &AMDGPU::AGPR_32RegClass;
11116     }
11117 
11118     if (RC) {
11119       uint32_t Idx;
11120       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11121       if (!Failed && Idx < RC->getNumRegs())
11122         return std::make_pair(RC->getRegister(Idx), RC);
11123     }
11124   }
11125 
11126   // FIXME: Returns VS_32 for physical SGPR constraints
11127   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11128 }
11129 
11130 static bool isImmConstraint(StringRef Constraint) {
11131   if (Constraint.size() == 1) {
11132     switch (Constraint[0]) {
11133     default: break;
11134     case 'I':
11135     case 'J':
11136     case 'A':
11137     case 'B':
11138     case 'C':
11139       return true;
11140     }
11141   } else if (Constraint == "DA" ||
11142              Constraint == "DB") {
11143     return true;
11144   }
11145   return false;
11146 }
11147 
11148 SITargetLowering::ConstraintType
11149 SITargetLowering::getConstraintType(StringRef Constraint) const {
11150   if (Constraint.size() == 1) {
11151     switch (Constraint[0]) {
11152     default: break;
11153     case 's':
11154     case 'v':
11155     case 'a':
11156       return C_RegisterClass;
11157     }
11158   }
11159   if (isImmConstraint(Constraint)) {
11160     return C_Other;
11161   }
11162   return TargetLowering::getConstraintType(Constraint);
11163 }
11164 
11165 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11166   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11167     Val = Val & maskTrailingOnes<uint64_t>(Size);
11168   }
11169   return Val;
11170 }
11171 
11172 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11173                                                     std::string &Constraint,
11174                                                     std::vector<SDValue> &Ops,
11175                                                     SelectionDAG &DAG) const {
11176   if (isImmConstraint(Constraint)) {
11177     uint64_t Val;
11178     if (getAsmOperandConstVal(Op, Val) &&
11179         checkAsmConstraintVal(Op, Constraint, Val)) {
11180       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11181       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11182     }
11183   } else {
11184     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11185   }
11186 }
11187 
11188 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11189   unsigned Size = Op.getScalarValueSizeInBits();
11190   if (Size > 64)
11191     return false;
11192 
11193   if (Size == 16 && !Subtarget->has16BitInsts())
11194     return false;
11195 
11196   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11197     Val = C->getSExtValue();
11198     return true;
11199   }
11200   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11201     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11202     return true;
11203   }
11204   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11205     if (Size != 16 || Op.getNumOperands() != 2)
11206       return false;
11207     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11208       return false;
11209     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11210       Val = C->getSExtValue();
11211       return true;
11212     }
11213     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11214       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11215       return true;
11216     }
11217   }
11218 
11219   return false;
11220 }
11221 
11222 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11223                                              const std::string &Constraint,
11224                                              uint64_t Val) const {
11225   if (Constraint.size() == 1) {
11226     switch (Constraint[0]) {
11227     case 'I':
11228       return AMDGPU::isInlinableIntLiteral(Val);
11229     case 'J':
11230       return isInt<16>(Val);
11231     case 'A':
11232       return checkAsmConstraintValA(Op, Val);
11233     case 'B':
11234       return isInt<32>(Val);
11235     case 'C':
11236       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11237              AMDGPU::isInlinableIntLiteral(Val);
11238     default:
11239       break;
11240     }
11241   } else if (Constraint.size() == 2) {
11242     if (Constraint == "DA") {
11243       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11244       int64_t LoBits = static_cast<int32_t>(Val);
11245       return checkAsmConstraintValA(Op, HiBits, 32) &&
11246              checkAsmConstraintValA(Op, LoBits, 32);
11247     }
11248     if (Constraint == "DB") {
11249       return true;
11250     }
11251   }
11252   llvm_unreachable("Invalid asm constraint");
11253 }
11254 
11255 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11256                                               uint64_t Val,
11257                                               unsigned MaxSize) const {
11258   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11259   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11260   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11261       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11262       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11263     return true;
11264   }
11265   return false;
11266 }
11267 
11268 // Figure out which registers should be reserved for stack access. Only after
11269 // the function is legalized do we know all of the non-spill stack objects or if
11270 // calls are present.
11271 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11272   MachineRegisterInfo &MRI = MF.getRegInfo();
11273   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11274   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11275   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11276 
11277   if (Info->isEntryFunction()) {
11278     // Callable functions have fixed registers used for stack access.
11279     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11280   }
11281 
11282   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11283                              Info->getStackPtrOffsetReg()));
11284   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11285     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11286 
11287   // We need to worry about replacing the default register with itself in case
11288   // of MIR testcases missing the MFI.
11289   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11290     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11291 
11292   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11293     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11294 
11295   Info->limitOccupancy(MF);
11296 
11297   if (ST.isWave32() && !MF.empty()) {
11298     // Add VCC_HI def because many instructions marked as imp-use VCC where
11299     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11300     // having a use of undef.
11301 
11302     const SIInstrInfo *TII = ST.getInstrInfo();
11303     DebugLoc DL;
11304 
11305     MachineBasicBlock &MBB = MF.front();
11306     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11307     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11308 
11309     for (auto &MBB : MF) {
11310       for (auto &MI : MBB) {
11311         TII->fixImplicitOperands(MI);
11312       }
11313     }
11314   }
11315 
11316   TargetLoweringBase::finalizeLowering(MF);
11317 
11318   // Allocate a VGPR for future SGPR Spill if
11319   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11320   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11321   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11322       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11323     Info->reserveVGPRforSGPRSpills(MF);
11324 }
11325 
11326 void SITargetLowering::computeKnownBitsForFrameIndex(
11327   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11328   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11329 
11330   // Set the high bits to zero based on the maximum allowed scratch size per
11331   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11332   // calculation won't overflow, so assume the sign bit is never set.
11333   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11334 }
11335 
11336 Align SITargetLowering::computeKnownAlignForTargetInstr(
11337   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11338   unsigned Depth) const {
11339   const MachineInstr *MI = MRI.getVRegDef(R);
11340   switch (MI->getOpcode()) {
11341   case AMDGPU::G_INTRINSIC:
11342   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11343     // FIXME: Can this move to generic code? What about the case where the call
11344     // site specifies a lower alignment?
11345     Intrinsic::ID IID = MI->getIntrinsicID();
11346     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11347     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11348     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11349       return *RetAlign;
11350     return Align(1);
11351   }
11352   default:
11353     return Align(1);
11354   }
11355 }
11356 
11357 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11358   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11359   const Align CacheLineAlign = Align(64);
11360 
11361   // Pre-GFX10 target did not benefit from loop alignment
11362   if (!ML || DisableLoopAlignment ||
11363       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11364       getSubtarget()->hasInstFwdPrefetchBug())
11365     return PrefAlign;
11366 
11367   // On GFX10 I$ is 4 x 64 bytes cache lines.
11368   // By default prefetcher keeps one cache line behind and reads two ahead.
11369   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11370   // behind and one ahead.
11371   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11372   // If loop fits 64 bytes it always spans no more than two cache lines and
11373   // does not need an alignment.
11374   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11375   // Else if loop is less or equal 192 bytes we need two lines behind.
11376 
11377   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11378   const MachineBasicBlock *Header = ML->getHeader();
11379   if (Header->getAlignment() != PrefAlign)
11380     return Header->getAlignment(); // Already processed.
11381 
11382   unsigned LoopSize = 0;
11383   for (const MachineBasicBlock *MBB : ML->blocks()) {
11384     // If inner loop block is aligned assume in average half of the alignment
11385     // size to be added as nops.
11386     if (MBB != Header)
11387       LoopSize += MBB->getAlignment().value() / 2;
11388 
11389     for (const MachineInstr &MI : *MBB) {
11390       LoopSize += TII->getInstSizeInBytes(MI);
11391       if (LoopSize > 192)
11392         return PrefAlign;
11393     }
11394   }
11395 
11396   if (LoopSize <= 64)
11397     return PrefAlign;
11398 
11399   if (LoopSize <= 128)
11400     return CacheLineAlign;
11401 
11402   // If any of parent loops is surrounded by prefetch instructions do not
11403   // insert new for inner loop, which would reset parent's settings.
11404   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11405     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11406       auto I = Exit->getFirstNonDebugInstr();
11407       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11408         return CacheLineAlign;
11409     }
11410   }
11411 
11412   MachineBasicBlock *Pre = ML->getLoopPreheader();
11413   MachineBasicBlock *Exit = ML->getExitBlock();
11414 
11415   if (Pre && Exit) {
11416     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11417             TII->get(AMDGPU::S_INST_PREFETCH))
11418       .addImm(1); // prefetch 2 lines behind PC
11419 
11420     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11421             TII->get(AMDGPU::S_INST_PREFETCH))
11422       .addImm(2); // prefetch 1 line behind PC
11423   }
11424 
11425   return CacheLineAlign;
11426 }
11427 
11428 LLVM_ATTRIBUTE_UNUSED
11429 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11430   assert(N->getOpcode() == ISD::CopyFromReg);
11431   do {
11432     // Follow the chain until we find an INLINEASM node.
11433     N = N->getOperand(0).getNode();
11434     if (N->getOpcode() == ISD::INLINEASM ||
11435         N->getOpcode() == ISD::INLINEASM_BR)
11436       return true;
11437   } while (N->getOpcode() == ISD::CopyFromReg);
11438   return false;
11439 }
11440 
11441 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11442   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11443 {
11444   switch (N->getOpcode()) {
11445     case ISD::CopyFromReg:
11446     {
11447       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11448       const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11449       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11450       Register Reg = R->getReg();
11451 
11452       // FIXME: Why does this need to consider isLiveIn?
11453       if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11454         return !TRI->isSGPRReg(MRI, Reg);
11455 
11456       if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11457         return KDA->isDivergent(V);
11458 
11459       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11460       return !TRI->isSGPRReg(MRI, Reg);
11461     }
11462     break;
11463     case ISD::LOAD: {
11464       const LoadSDNode *L = cast<LoadSDNode>(N);
11465       unsigned AS = L->getAddressSpace();
11466       // A flat load may access private memory.
11467       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11468     } break;
11469     case ISD::CALLSEQ_END:
11470     return true;
11471     break;
11472     case ISD::INTRINSIC_WO_CHAIN:
11473     {
11474 
11475     }
11476       return AMDGPU::isIntrinsicSourceOfDivergence(
11477       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11478     case ISD::INTRINSIC_W_CHAIN:
11479       return AMDGPU::isIntrinsicSourceOfDivergence(
11480       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11481   }
11482   return false;
11483 }
11484 
11485 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11486                                                EVT VT) const {
11487   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11488   case MVT::f32:
11489     return hasFP32Denormals(DAG.getMachineFunction());
11490   case MVT::f64:
11491   case MVT::f16:
11492     return hasFP64FP16Denormals(DAG.getMachineFunction());
11493   default:
11494     return false;
11495   }
11496 }
11497 
11498 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11499                                                     const SelectionDAG &DAG,
11500                                                     bool SNaN,
11501                                                     unsigned Depth) const {
11502   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11503     const MachineFunction &MF = DAG.getMachineFunction();
11504     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11505 
11506     if (Info->getMode().DX10Clamp)
11507       return true; // Clamped to 0.
11508     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11509   }
11510 
11511   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11512                                                             SNaN, Depth);
11513 }
11514 
11515 TargetLowering::AtomicExpansionKind
11516 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11517   switch (RMW->getOperation()) {
11518   case AtomicRMWInst::FAdd: {
11519     Type *Ty = RMW->getType();
11520 
11521     // We don't have a way to support 16-bit atomics now, so just leave them
11522     // as-is.
11523     if (Ty->isHalfTy())
11524       return AtomicExpansionKind::None;
11525 
11526     if (!Ty->isFloatTy())
11527       return AtomicExpansionKind::CmpXChg;
11528 
11529     // TODO: Do have these for flat. Older targets also had them for buffers.
11530     unsigned AS = RMW->getPointerAddressSpace();
11531 
11532     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11533       return RMW->use_empty() ? AtomicExpansionKind::None :
11534                                 AtomicExpansionKind::CmpXChg;
11535     }
11536 
11537     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11538       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11539   }
11540   default:
11541     break;
11542   }
11543 
11544   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11545 }
11546 
11547 const TargetRegisterClass *
11548 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11549   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11550   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11551   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11552     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11553                                                : &AMDGPU::SReg_32RegClass;
11554   if (!TRI->isSGPRClass(RC) && !isDivergent)
11555     return TRI->getEquivalentSGPRClass(RC);
11556   else if (TRI->isSGPRClass(RC) && isDivergent)
11557     return TRI->getEquivalentVGPRClass(RC);
11558 
11559   return RC;
11560 }
11561 
11562 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11563 // uniform values (as produced by the mask results of control flow intrinsics)
11564 // used outside of divergent blocks. The phi users need to also be treated as
11565 // always uniform.
11566 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11567                       unsigned WaveSize) {
11568   // FIXME: We asssume we never cast the mask results of a control flow
11569   // intrinsic.
11570   // Early exit if the type won't be consistent as a compile time hack.
11571   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11572   if (!IT || IT->getBitWidth() != WaveSize)
11573     return false;
11574 
11575   if (!isa<Instruction>(V))
11576     return false;
11577   if (!Visited.insert(V).second)
11578     return false;
11579   bool Result = false;
11580   for (auto U : V->users()) {
11581     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11582       if (V == U->getOperand(1)) {
11583         switch (Intrinsic->getIntrinsicID()) {
11584         default:
11585           Result = false;
11586           break;
11587         case Intrinsic::amdgcn_if_break:
11588         case Intrinsic::amdgcn_if:
11589         case Intrinsic::amdgcn_else:
11590           Result = true;
11591           break;
11592         }
11593       }
11594       if (V == U->getOperand(0)) {
11595         switch (Intrinsic->getIntrinsicID()) {
11596         default:
11597           Result = false;
11598           break;
11599         case Intrinsic::amdgcn_end_cf:
11600         case Intrinsic::amdgcn_loop:
11601           Result = true;
11602           break;
11603         }
11604       }
11605     } else {
11606       Result = hasCFUser(U, Visited, WaveSize);
11607     }
11608     if (Result)
11609       break;
11610   }
11611   return Result;
11612 }
11613 
11614 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11615                                                const Value *V) const {
11616   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11617     if (CI->isInlineAsm()) {
11618       // FIXME: This cannot give a correct answer. This should only trigger in
11619       // the case where inline asm returns mixed SGPR and VGPR results, used
11620       // outside the defining block. We don't have a specific result to
11621       // consider, so this assumes if any value is SGPR, the overall register
11622       // also needs to be SGPR.
11623       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11624       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11625           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11626       for (auto &TC : TargetConstraints) {
11627         if (TC.Type == InlineAsm::isOutput) {
11628           ComputeConstraintToUse(TC, SDValue());
11629           unsigned AssignedReg;
11630           const TargetRegisterClass *RC;
11631           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11632               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11633           if (RC) {
11634             MachineRegisterInfo &MRI = MF.getRegInfo();
11635             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11636               return true;
11637             else if (SIRI->isSGPRClass(RC))
11638               return true;
11639           }
11640         }
11641       }
11642     }
11643   }
11644   SmallPtrSet<const Value *, 16> Visited;
11645   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11646 }
11647 
11648 std::pair<int, MVT>
11649 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11650                                           Type *Ty) const {
11651   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11652   auto Size = DL.getTypeSizeInBits(Ty);
11653   // Maximum load or store can handle 8 dwords for scalar and 4 for
11654   // vector ALU. Let's assume anything above 8 dwords is expensive
11655   // even if legal.
11656   if (Size <= 256)
11657     return Cost;
11658 
11659   Cost.first = (Size + 255) / 256;
11660   return Cost;
11661 }
11662