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/FunctionLoweringInfo.h"
38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/SelectionDAG.h"
51 #include "llvm/CodeGen/SelectionDAGNodes.h"
52 #include "llvm/CodeGen/TargetCallingConv.h"
53 #include "llvm/CodeGen/TargetRegisterInfo.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/IR/Constants.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/DebugLoc.h"
58 #include "llvm/IR/DerivedTypes.h"
59 #include "llvm/IR/DiagnosticInfo.h"
60 #include "llvm/IR/Function.h"
61 #include "llvm/IR/GlobalValue.h"
62 #include "llvm/IR/InstrTypes.h"
63 #include "llvm/IR/Instruction.h"
64 #include "llvm/IR/Instructions.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/Type.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CodeGen.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/KnownBits.h"
73 #include "llvm/Support/MachineValueType.h"
74 #include "llvm/Support/MathExtras.h"
75 #include "llvm/Target/TargetOptions.h"
76 #include <cassert>
77 #include <cmath>
78 #include <cstdint>
79 #include <iterator>
80 #include <tuple>
81 #include <utility>
82 #include <vector>
83 
84 using namespace llvm;
85 
86 #define DEBUG_TYPE "si-lower"
87 
88 STATISTIC(NumTailCalls, "Number of tail calls");
89 
90 static cl::opt<bool> DisableLoopAlignment(
91   "amdgpu-disable-loop-alignment",
92   cl::desc("Do not align and prefetch loops"),
93   cl::init(false));
94 
95 static cl::opt<bool> VGPRReserveforSGPRSpill(
96     "amdgpu-reserve-vgpr-for-sgpr-spill",
97     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
98 
99 static cl::opt<bool> UseDivergentRegisterIndexing(
100   "amdgpu-use-divergent-register-indexing",
101   cl::Hidden,
102   cl::desc("Use indirect register addressing for divergent indexes"),
103   cl::init(false));
104 
105 static bool hasFP32Denormals(const MachineFunction &MF) {
106   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
107   return Info->getMode().allFP32Denormals();
108 }
109 
110 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
111   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
112   return Info->getMode().allFP64FP16Denormals();
113 }
114 
115 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
116   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
117   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
118     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
119       return AMDGPU::SGPR0 + Reg;
120     }
121   }
122   llvm_unreachable("Cannot allocate sgpr");
123 }
124 
125 SITargetLowering::SITargetLowering(const TargetMachine &TM,
126                                    const GCNSubtarget &STI)
127     : AMDGPUTargetLowering(TM, STI),
128       Subtarget(&STI) {
129   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
130   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
131 
132   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
133   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
134 
135   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
136   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
137   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
138 
139   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
140   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
141 
142   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
143   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
144 
145   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
146   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
147 
148   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
149   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
150 
151   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
152   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
153 
154   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
155   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
156 
157   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
158   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
159 
160   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
161   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
162 
163   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
164   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
165 
166   if (Subtarget->has16BitInsts()) {
167     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
168     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
169 
170     // Unless there are also VOP3P operations, not operations are really legal.
171     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
172     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
173     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
174     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
175   }
176 
177   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
178   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
179 
180   computeRegisterProperties(Subtarget->getRegisterInfo());
181 
182   // The boolean content concept here is too inflexible. Compares only ever
183   // really produce a 1-bit result. Any copy/extend from these will turn into a
184   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
185   // it's what most targets use.
186   setBooleanContents(ZeroOrOneBooleanContent);
187   setBooleanVectorContents(ZeroOrOneBooleanContent);
188 
189   // We need to custom lower vector stores from local memory
190   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
195   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
196   setOperationAction(ISD::LOAD, MVT::i1, Custom);
197   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
198 
199   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
202   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
203   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
204   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
205   setOperationAction(ISD::STORE, MVT::i1, Custom);
206   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
207 
208   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
209   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
210   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
211   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
212   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
213   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
214   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
215   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
216   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
217   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
218   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
219   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
220   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
221   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
222   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
223   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
224 
225   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
226   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
227   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
228   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
229   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
230 
231   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
232   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
233 
234   setOperationAction(ISD::SELECT, MVT::i1, Promote);
235   setOperationAction(ISD::SELECT, MVT::i64, Custom);
236   setOperationAction(ISD::SELECT, MVT::f64, Promote);
237   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
238 
239   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
241   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
242   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
243   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
244 
245   setOperationAction(ISD::SETCC, MVT::i1, Promote);
246   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
247   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
248   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
249 
250   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
251   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
252   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
253   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
254   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
255   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
256   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
257   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
258 
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
266   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
267 
268   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
269   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
270   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
271   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
272   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
273   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
274 
275   setOperationAction(ISD::UADDO, MVT::i32, Legal);
276   setOperationAction(ISD::USUBO, MVT::i32, Legal);
277 
278   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
279   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
280 
281   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
282   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
283   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
284 
285 #if 0
286   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
287   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
288 #endif
289 
290   // We only support LOAD/STORE and vector manipulation ops for vectors
291   // with > 4 elements.
292   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
293                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
294                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
295                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
296     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
297       switch (Op) {
298       case ISD::LOAD:
299       case ISD::STORE:
300       case ISD::BUILD_VECTOR:
301       case ISD::BITCAST:
302       case ISD::EXTRACT_VECTOR_ELT:
303       case ISD::INSERT_VECTOR_ELT:
304       case ISD::INSERT_SUBVECTOR:
305       case ISD::EXTRACT_SUBVECTOR:
306       case ISD::SCALAR_TO_VECTOR:
307         break;
308       case ISD::CONCAT_VECTORS:
309         setOperationAction(Op, VT, Custom);
310         break;
311       default:
312         setOperationAction(Op, VT, Expand);
313         break;
314       }
315     }
316   }
317 
318   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
319 
320   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
321   // is expanded to avoid having two separate loops in case the index is a VGPR.
322 
323   // Most operations are naturally 32-bit vector operations. We only support
324   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
325   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
326     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
327     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
328 
329     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
330     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
331 
332     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
333     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
334 
335     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
336     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
337   }
338 
339   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
340     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
341     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
342 
343     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
344     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
345 
346     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
347     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
348 
349     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
350     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
351   }
352 
353   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
354     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
355     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
356 
357     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
358     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
359 
360     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
361     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
362 
363     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
364     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
365   }
366 
367   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
368     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
369     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
370 
371     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
372     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
373 
374     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
375     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
376 
377     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
378     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
379   }
380 
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
382   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
383   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
384   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
385 
386   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
387   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
388 
389   // Avoid stack access for these.
390   // TODO: Generalize to more vector types.
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
395 
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
400   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
401 
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
403   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
404   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
405 
406   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
407   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
408   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
409   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
410 
411   // Deal with vec3 vector operations when widened to vec4.
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
416 
417   // Deal with vec5 vector operations when widened to vec8.
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
419   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
420   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
421   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
422 
423   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
424   // and output demarshalling
425   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
426   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
427 
428   // We can't return success/failure, only the old value,
429   // let LLVM add the comparison
430   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
431   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
432 
433   if (Subtarget->hasFlatAddressSpace()) {
434     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
435     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
436   }
437 
438   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
439 
440   // FIXME: This should be narrowed to i32, but that only happens if i64 is
441   // illegal.
442   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
443   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
444   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
445 
446   // On SI this is s_memtime and s_memrealtime on VI.
447   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
448   setOperationAction(ISD::TRAP, MVT::Other, Custom);
449   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
450 
451   if (Subtarget->has16BitInsts()) {
452     setOperationAction(ISD::FPOW, MVT::f16, Promote);
453     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
454     setOperationAction(ISD::FLOG, MVT::f16, Custom);
455     setOperationAction(ISD::FEXP, MVT::f16, Custom);
456     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
457   }
458 
459   if (Subtarget->hasMadMacF32Insts())
460     setOperationAction(ISD::FMAD, MVT::f32, Legal);
461 
462   if (!Subtarget->hasBFI()) {
463     // fcopysign can be done in a single instruction with BFI.
464     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
465     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
466   }
467 
468   if (!Subtarget->hasBCNT(32))
469     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
470 
471   if (!Subtarget->hasBCNT(64))
472     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
473 
474   if (Subtarget->hasFFBH())
475     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
476 
477   if (Subtarget->hasFFBL())
478     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
479 
480   // We only really have 32-bit BFE instructions (and 16-bit on VI).
481   //
482   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
483   // effort to match them now. We want this to be false for i64 cases when the
484   // extraction isn't restricted to the upper or lower half. Ideally we would
485   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
486   // span the midpoint are probably relatively rare, so don't worry about them
487   // for now.
488   if (Subtarget->hasBFE())
489     setHasExtractBitsInsn(true);
490 
491   // Clamp modifier on add/sub
492   if (Subtarget->hasIntClamp()) {
493     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
494     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
495   }
496 
497   if (Subtarget->hasAddNoCarry()) {
498     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
500     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
501     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
502   }
503 
504   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
506   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
507   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
508 
509 
510   // These are really only legal for ieee_mode functions. We should be avoiding
511   // them for functions that don't have ieee_mode enabled, so just say they are
512   // legal.
513   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
515   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
516   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
517 
518 
519   if (Subtarget->haveRoundOpsF64()) {
520     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
521     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
522     setOperationAction(ISD::FRINT, MVT::f64, Legal);
523   } else {
524     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
525     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
526     setOperationAction(ISD::FRINT, MVT::f64, Custom);
527     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
528   }
529 
530   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
531 
532   setOperationAction(ISD::FSIN, MVT::f32, Custom);
533   setOperationAction(ISD::FCOS, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f32, Custom);
535   setOperationAction(ISD::FDIV, MVT::f64, Custom);
536 
537   if (Subtarget->has16BitInsts()) {
538     setOperationAction(ISD::Constant, MVT::i16, Legal);
539 
540     setOperationAction(ISD::SMIN, MVT::i16, Legal);
541     setOperationAction(ISD::SMAX, MVT::i16, Legal);
542 
543     setOperationAction(ISD::UMIN, MVT::i16, Legal);
544     setOperationAction(ISD::UMAX, MVT::i16, Legal);
545 
546     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
547     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
548 
549     setOperationAction(ISD::ROTR, MVT::i16, Expand);
550     setOperationAction(ISD::ROTL, MVT::i16, Expand);
551 
552     setOperationAction(ISD::SDIV, MVT::i16, Promote);
553     setOperationAction(ISD::UDIV, MVT::i16, Promote);
554     setOperationAction(ISD::SREM, MVT::i16, Promote);
555     setOperationAction(ISD::UREM, MVT::i16, Promote);
556     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
557     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
558 
559     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
560 
561     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
564     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
565     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
566 
567     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
568 
569     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
570 
571     setOperationAction(ISD::LOAD, MVT::i16, Custom);
572 
573     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
574 
575     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
576     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
577     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
578     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
579 
580     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
581     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
582 
583     // F16 - Constant Actions.
584     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
585 
586     // F16 - Load/Store Actions.
587     setOperationAction(ISD::LOAD, MVT::f16, Promote);
588     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
589     setOperationAction(ISD::STORE, MVT::f16, Promote);
590     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
591 
592     // F16 - VOP1 Actions.
593     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
594     setOperationAction(ISD::FCOS, MVT::f16, Custom);
595     setOperationAction(ISD::FSIN, MVT::f16, Custom);
596 
597     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
598     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
599 
600     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
601     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
602     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
604     setOperationAction(ISD::FROUND, MVT::f16, Custom);
605 
606     // F16 - VOP2 Actions.
607     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
608     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
609 
610     setOperationAction(ISD::FDIV, MVT::f16, Custom);
611 
612     // F16 - VOP3 Actions.
613     setOperationAction(ISD::FMA, MVT::f16, Legal);
614     if (STI.hasMadF16())
615       setOperationAction(ISD::FMAD, MVT::f16, Legal);
616 
617     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
618       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
619         switch (Op) {
620         case ISD::LOAD:
621         case ISD::STORE:
622         case ISD::BUILD_VECTOR:
623         case ISD::BITCAST:
624         case ISD::EXTRACT_VECTOR_ELT:
625         case ISD::INSERT_VECTOR_ELT:
626         case ISD::INSERT_SUBVECTOR:
627         case ISD::EXTRACT_SUBVECTOR:
628         case ISD::SCALAR_TO_VECTOR:
629           break;
630         case ISD::CONCAT_VECTORS:
631           setOperationAction(Op, VT, Custom);
632           break;
633         default:
634           setOperationAction(Op, VT, Expand);
635           break;
636         }
637       }
638     }
639 
640     // v_perm_b32 can handle either of these.
641     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
642     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
643     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
644 
645     // XXX - Do these do anything? Vector constants turn into build_vector.
646     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
647     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
648 
649     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
650     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
651 
652     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
653     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
654     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
655     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
656 
657     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
658     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
659     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
660     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
661 
662     setOperationAction(ISD::AND, MVT::v2i16, Promote);
663     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
664     setOperationAction(ISD::OR, MVT::v2i16, Promote);
665     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
666     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
667     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
668 
669     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
670     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
671     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
672     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
673 
674     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
675     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
676     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
677     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
678 
679     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
680     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
682     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
683 
684     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
685     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
686     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
687 
688     if (!Subtarget->hasVOP3PInsts()) {
689       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
690       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
691     }
692 
693     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
694     // This isn't really legal, but this avoids the legalizer unrolling it (and
695     // allows matching fneg (fabs x) patterns)
696     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
697 
698     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
699     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
700     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
701     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
702 
703     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
704     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
705 
706     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
707     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
708   }
709 
710   if (Subtarget->hasVOP3PInsts()) {
711     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
712     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
713     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
714     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
716     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
717     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
718     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
719     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
720     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
721 
722     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
723     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
725     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
726 
727     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
728     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
729     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
730 
731     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
732     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
733 
734     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
735 
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
737     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
738 
739     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
740     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
741 
742     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
743     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
744     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
745     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
746     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
747     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
748 
749     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
750     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
751     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
752     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
753 
754     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
755     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
757     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
758 
759     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
760     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
761     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
762 
763     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
764     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
765 
766     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
767     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
768     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
769 
770     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
771     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
772     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
773   }
774 
775   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
776   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
777 
778   if (Subtarget->has16BitInsts()) {
779     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
780     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
781     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
782     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
783   } else {
784     // Legalization hack.
785     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
786     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
787 
788     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
789     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
790   }
791 
792   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
793     setOperationAction(ISD::SELECT, VT, Custom);
794   }
795 
796   setOperationAction(ISD::SMULO, MVT::i64, Custom);
797   setOperationAction(ISD::UMULO, MVT::i64, Custom);
798 
799   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
800   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
801   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
802   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
803   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
804   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
805   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
806 
807   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
808   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
809   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
810   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
811   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
812   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
813   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
814   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
815   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
816   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
817   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
818 
819   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
820   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
821   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
822   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
823   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
824   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
825   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
826   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
827   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
828   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
829 
830   setTargetDAGCombine(ISD::ADD);
831   setTargetDAGCombine(ISD::ADDCARRY);
832   setTargetDAGCombine(ISD::SUB);
833   setTargetDAGCombine(ISD::SUBCARRY);
834   setTargetDAGCombine(ISD::FADD);
835   setTargetDAGCombine(ISD::FSUB);
836   setTargetDAGCombine(ISD::FMINNUM);
837   setTargetDAGCombine(ISD::FMAXNUM);
838   setTargetDAGCombine(ISD::FMINNUM_IEEE);
839   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
840   setTargetDAGCombine(ISD::FMA);
841   setTargetDAGCombine(ISD::SMIN);
842   setTargetDAGCombine(ISD::SMAX);
843   setTargetDAGCombine(ISD::UMIN);
844   setTargetDAGCombine(ISD::UMAX);
845   setTargetDAGCombine(ISD::SETCC);
846   setTargetDAGCombine(ISD::AND);
847   setTargetDAGCombine(ISD::OR);
848   setTargetDAGCombine(ISD::XOR);
849   setTargetDAGCombine(ISD::SINT_TO_FP);
850   setTargetDAGCombine(ISD::UINT_TO_FP);
851   setTargetDAGCombine(ISD::FCANONICALIZE);
852   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
853   setTargetDAGCombine(ISD::ZERO_EXTEND);
854   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
855   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
856   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
857 
858   // All memory operations. Some folding on the pointer operand is done to help
859   // matching the constant offsets in the addressing modes.
860   setTargetDAGCombine(ISD::LOAD);
861   setTargetDAGCombine(ISD::STORE);
862   setTargetDAGCombine(ISD::ATOMIC_LOAD);
863   setTargetDAGCombine(ISD::ATOMIC_STORE);
864   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
865   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
866   setTargetDAGCombine(ISD::ATOMIC_SWAP);
867   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
868   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
869   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
870   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
871   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
872   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
873   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
874   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
875   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
876   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
877   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
878   setTargetDAGCombine(ISD::INTRINSIC_VOID);
879   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
880 
881   // FIXME: In other contexts we pretend this is a per-function property.
882   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
883 
884   setSchedulingPreference(Sched::RegPressure);
885 }
886 
887 const GCNSubtarget *SITargetLowering::getSubtarget() const {
888   return Subtarget;
889 }
890 
891 //===----------------------------------------------------------------------===//
892 // TargetLowering queries
893 //===----------------------------------------------------------------------===//
894 
895 // v_mad_mix* support a conversion from f16 to f32.
896 //
897 // There is only one special case when denormals are enabled we don't currently,
898 // where this is OK to use.
899 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
900                                        EVT DestVT, EVT SrcVT) const {
901   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
902           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
903     DestVT.getScalarType() == MVT::f32 &&
904     SrcVT.getScalarType() == MVT::f16 &&
905     // TODO: This probably only requires no input flushing?
906     !hasFP32Denormals(DAG.getMachineFunction());
907 }
908 
909 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
910   // SI has some legal vector types, but no legal vector operations. Say no
911   // shuffles are legal in order to prefer scalarizing some vector operations.
912   return false;
913 }
914 
915 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
916                                                     CallingConv::ID CC,
917                                                     EVT VT) const {
918   if (CC == CallingConv::AMDGPU_KERNEL)
919     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
920 
921   if (VT.isVector()) {
922     EVT ScalarVT = VT.getScalarType();
923     unsigned Size = ScalarVT.getSizeInBits();
924     if (Size == 16) {
925       if (Subtarget->has16BitInsts())
926         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
927       return VT.isInteger() ? MVT::i32 : MVT::f32;
928     }
929 
930     if (Size < 16)
931       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
932     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
933   }
934 
935   if (VT.getSizeInBits() > 32)
936     return MVT::i32;
937 
938   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
939 }
940 
941 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
942                                                          CallingConv::ID CC,
943                                                          EVT VT) const {
944   if (CC == CallingConv::AMDGPU_KERNEL)
945     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
946 
947   if (VT.isVector()) {
948     unsigned NumElts = VT.getVectorNumElements();
949     EVT ScalarVT = VT.getScalarType();
950     unsigned Size = ScalarVT.getSizeInBits();
951 
952     // FIXME: Should probably promote 8-bit vectors to i16.
953     if (Size == 16 && Subtarget->has16BitInsts())
954       return (NumElts + 1) / 2;
955 
956     if (Size <= 32)
957       return NumElts;
958 
959     if (Size > 32)
960       return NumElts * ((Size + 31) / 32);
961   } else if (VT.getSizeInBits() > 32)
962     return (VT.getSizeInBits() + 31) / 32;
963 
964   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
965 }
966 
967 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
968   LLVMContext &Context, CallingConv::ID CC,
969   EVT VT, EVT &IntermediateVT,
970   unsigned &NumIntermediates, MVT &RegisterVT) const {
971   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
972     unsigned NumElts = VT.getVectorNumElements();
973     EVT ScalarVT = VT.getScalarType();
974     unsigned Size = ScalarVT.getSizeInBits();
975     // FIXME: We should fix the ABI to be the same on targets without 16-bit
976     // support, but unless we can properly handle 3-vectors, it will be still be
977     // inconsistent.
978     if (Size == 16 && Subtarget->has16BitInsts()) {
979       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
980       IntermediateVT = RegisterVT;
981       NumIntermediates = (NumElts + 1) / 2;
982       return NumIntermediates;
983     }
984 
985     if (Size == 32) {
986       RegisterVT = ScalarVT.getSimpleVT();
987       IntermediateVT = RegisterVT;
988       NumIntermediates = NumElts;
989       return NumIntermediates;
990     }
991 
992     if (Size < 16 && Subtarget->has16BitInsts()) {
993       // FIXME: Should probably form v2i16 pieces
994       RegisterVT = MVT::i16;
995       IntermediateVT = ScalarVT;
996       NumIntermediates = NumElts;
997       return NumIntermediates;
998     }
999 
1000 
1001     if (Size != 16 && Size <= 32) {
1002       RegisterVT = MVT::i32;
1003       IntermediateVT = ScalarVT;
1004       NumIntermediates = NumElts;
1005       return NumIntermediates;
1006     }
1007 
1008     if (Size > 32) {
1009       RegisterVT = MVT::i32;
1010       IntermediateVT = RegisterVT;
1011       NumIntermediates = NumElts * ((Size + 31) / 32);
1012       return NumIntermediates;
1013     }
1014   }
1015 
1016   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1017     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1018 }
1019 
1020 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1021   assert(DMaskLanes != 0);
1022 
1023   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1024     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1025     return EVT::getVectorVT(Ty->getContext(),
1026                             EVT::getEVT(VT->getElementType()),
1027                             NumElts);
1028   }
1029 
1030   return EVT::getEVT(Ty);
1031 }
1032 
1033 // Peek through TFE struct returns to only use the data size.
1034 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1035   auto *ST = dyn_cast<StructType>(Ty);
1036   if (!ST)
1037     return memVTFromImageData(Ty, DMaskLanes);
1038 
1039   // Some intrinsics return an aggregate type - special case to work out the
1040   // correct memVT.
1041   //
1042   // Only limited forms of aggregate type currently expected.
1043   if (ST->getNumContainedTypes() != 2 ||
1044       !ST->getContainedType(1)->isIntegerTy(32))
1045     return EVT();
1046   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1047 }
1048 
1049 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1050                                           const CallInst &CI,
1051                                           MachineFunction &MF,
1052                                           unsigned IntrID) const {
1053   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1054           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1055     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1056                                                   (Intrinsic::ID)IntrID);
1057     if (Attr.hasFnAttribute(Attribute::ReadNone))
1058       return false;
1059 
1060     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1061 
1062     if (RsrcIntr->IsImage) {
1063       Info.ptrVal = MFI->getImagePSV(
1064         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1065         CI.getArgOperand(RsrcIntr->RsrcArg));
1066       Info.align.reset();
1067     } else {
1068       Info.ptrVal = MFI->getBufferPSV(
1069         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1070         CI.getArgOperand(RsrcIntr->RsrcArg));
1071     }
1072 
1073     Info.flags = MachineMemOperand::MODereferenceable;
1074     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1075       unsigned DMaskLanes = 4;
1076 
1077       if (RsrcIntr->IsImage) {
1078         const AMDGPU::ImageDimIntrinsicInfo *Intr
1079           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1080         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1081           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1082 
1083         if (!BaseOpcode->Gather4) {
1084           // If this isn't a gather, we may have excess loaded elements in the
1085           // IR type. Check the dmask for the real number of elements loaded.
1086           unsigned DMask
1087             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1088           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1089         }
1090 
1091         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1092       } else
1093         Info.memVT = EVT::getEVT(CI.getType());
1094 
1095       // FIXME: What does alignment mean for an image?
1096       Info.opc = ISD::INTRINSIC_W_CHAIN;
1097       Info.flags |= MachineMemOperand::MOLoad;
1098     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1099       Info.opc = ISD::INTRINSIC_VOID;
1100 
1101       Type *DataTy = CI.getArgOperand(0)->getType();
1102       if (RsrcIntr->IsImage) {
1103         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1104         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1105         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1106       } else
1107         Info.memVT = EVT::getEVT(DataTy);
1108 
1109       Info.flags |= MachineMemOperand::MOStore;
1110     } else {
1111       // Atomic
1112       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1113                                             ISD::INTRINSIC_W_CHAIN;
1114       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1115       Info.flags = MachineMemOperand::MOLoad |
1116                    MachineMemOperand::MOStore |
1117                    MachineMemOperand::MODereferenceable;
1118 
1119       // XXX - Should this be volatile without known ordering?
1120       Info.flags |= MachineMemOperand::MOVolatile;
1121     }
1122     return true;
1123   }
1124 
1125   switch (IntrID) {
1126   case Intrinsic::amdgcn_atomic_inc:
1127   case Intrinsic::amdgcn_atomic_dec:
1128   case Intrinsic::amdgcn_ds_ordered_add:
1129   case Intrinsic::amdgcn_ds_ordered_swap:
1130   case Intrinsic::amdgcn_ds_fadd:
1131   case Intrinsic::amdgcn_ds_fmin:
1132   case Intrinsic::amdgcn_ds_fmax: {
1133     Info.opc = ISD::INTRINSIC_W_CHAIN;
1134     Info.memVT = MVT::getVT(CI.getType());
1135     Info.ptrVal = CI.getOperand(0);
1136     Info.align.reset();
1137     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1138 
1139     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1140     if (!Vol->isZero())
1141       Info.flags |= MachineMemOperand::MOVolatile;
1142 
1143     return true;
1144   }
1145   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1146     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1147 
1148     Info.opc = ISD::INTRINSIC_W_CHAIN;
1149     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1150     Info.ptrVal = MFI->getBufferPSV(
1151       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1152       CI.getArgOperand(1));
1153     Info.align.reset();
1154     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1155 
1156     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1157     if (!Vol || !Vol->isZero())
1158       Info.flags |= MachineMemOperand::MOVolatile;
1159 
1160     return true;
1161   }
1162   case Intrinsic::amdgcn_ds_append:
1163   case Intrinsic::amdgcn_ds_consume: {
1164     Info.opc = ISD::INTRINSIC_W_CHAIN;
1165     Info.memVT = MVT::getVT(CI.getType());
1166     Info.ptrVal = CI.getOperand(0);
1167     Info.align.reset();
1168     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1169 
1170     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1171     if (!Vol->isZero())
1172       Info.flags |= MachineMemOperand::MOVolatile;
1173 
1174     return true;
1175   }
1176   case Intrinsic::amdgcn_global_atomic_csub: {
1177     Info.opc = ISD::INTRINSIC_W_CHAIN;
1178     Info.memVT = MVT::getVT(CI.getType());
1179     Info.ptrVal = CI.getOperand(0);
1180     Info.align.reset();
1181     Info.flags = MachineMemOperand::MOLoad |
1182                  MachineMemOperand::MOStore |
1183                  MachineMemOperand::MOVolatile;
1184     return true;
1185   }
1186   case Intrinsic::amdgcn_global_atomic_fadd: {
1187     Info.opc = ISD::INTRINSIC_W_CHAIN;
1188     Info.memVT = MVT::getVT(CI.getType());
1189     Info.ptrVal = CI.getOperand(0);
1190     Info.align.reset();
1191     Info.flags = MachineMemOperand::MOLoad |
1192                  MachineMemOperand::MOStore |
1193                  MachineMemOperand::MODereferenceable |
1194                  MachineMemOperand::MOVolatile;
1195     return true;
1196   }
1197   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1198     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1199     Info.opc = ISD::INTRINSIC_W_CHAIN;
1200     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1201     Info.ptrVal = MFI->getImagePSV(
1202         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), CI.getArgOperand(5));
1203     Info.align.reset();
1204     Info.flags = MachineMemOperand::MOLoad |
1205                  MachineMemOperand::MODereferenceable;
1206     return true;
1207   }
1208   case Intrinsic::amdgcn_ds_gws_init:
1209   case Intrinsic::amdgcn_ds_gws_barrier:
1210   case Intrinsic::amdgcn_ds_gws_sema_v:
1211   case Intrinsic::amdgcn_ds_gws_sema_br:
1212   case Intrinsic::amdgcn_ds_gws_sema_p:
1213   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1214     Info.opc = ISD::INTRINSIC_VOID;
1215 
1216     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1217     Info.ptrVal =
1218         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1219 
1220     // This is an abstract access, but we need to specify a type and size.
1221     Info.memVT = MVT::i32;
1222     Info.size = 4;
1223     Info.align = Align(4);
1224 
1225     Info.flags = MachineMemOperand::MOStore;
1226     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1227       Info.flags = MachineMemOperand::MOLoad;
1228     return true;
1229   }
1230   default:
1231     return false;
1232   }
1233 }
1234 
1235 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1236                                             SmallVectorImpl<Value*> &Ops,
1237                                             Type *&AccessTy) const {
1238   switch (II->getIntrinsicID()) {
1239   case Intrinsic::amdgcn_atomic_inc:
1240   case Intrinsic::amdgcn_atomic_dec:
1241   case Intrinsic::amdgcn_ds_ordered_add:
1242   case Intrinsic::amdgcn_ds_ordered_swap:
1243   case Intrinsic::amdgcn_ds_append:
1244   case Intrinsic::amdgcn_ds_consume:
1245   case Intrinsic::amdgcn_ds_fadd:
1246   case Intrinsic::amdgcn_ds_fmin:
1247   case Intrinsic::amdgcn_ds_fmax:
1248   case Intrinsic::amdgcn_global_atomic_fadd:
1249   case Intrinsic::amdgcn_global_atomic_csub: {
1250     Value *Ptr = II->getArgOperand(0);
1251     AccessTy = II->getType();
1252     Ops.push_back(Ptr);
1253     return true;
1254   }
1255   default:
1256     return false;
1257   }
1258 }
1259 
1260 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1261   if (!Subtarget->hasFlatInstOffsets()) {
1262     // Flat instructions do not have offsets, and only have the register
1263     // address.
1264     return AM.BaseOffs == 0 && AM.Scale == 0;
1265   }
1266 
1267   return AM.Scale == 0 &&
1268          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1269                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1270                                   /*Signed=*/false));
1271 }
1272 
1273 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1274   if (Subtarget->hasFlatGlobalInsts())
1275     return AM.Scale == 0 &&
1276            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1277                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1278                                     /*Signed=*/true));
1279 
1280   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1281       // Assume the we will use FLAT for all global memory accesses
1282       // on VI.
1283       // FIXME: This assumption is currently wrong.  On VI we still use
1284       // MUBUF instructions for the r + i addressing mode.  As currently
1285       // implemented, the MUBUF instructions only work on buffer < 4GB.
1286       // It may be possible to support > 4GB buffers with MUBUF instructions,
1287       // by setting the stride value in the resource descriptor which would
1288       // increase the size limit to (stride * 4GB).  However, this is risky,
1289       // because it has never been validated.
1290     return isLegalFlatAddressingMode(AM);
1291   }
1292 
1293   return isLegalMUBUFAddressingMode(AM);
1294 }
1295 
1296 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1297   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1298   // additionally can do r + r + i with addr64. 32-bit has more addressing
1299   // mode options. Depending on the resource constant, it can also do
1300   // (i64 r0) + (i32 r1) * (i14 i).
1301   //
1302   // Private arrays end up using a scratch buffer most of the time, so also
1303   // assume those use MUBUF instructions. Scratch loads / stores are currently
1304   // implemented as mubuf instructions with offen bit set, so slightly
1305   // different than the normal addr64.
1306   if (!isUInt<12>(AM.BaseOffs))
1307     return false;
1308 
1309   // FIXME: Since we can split immediate into soffset and immediate offset,
1310   // would it make sense to allow any immediate?
1311 
1312   switch (AM.Scale) {
1313   case 0: // r + i or just i, depending on HasBaseReg.
1314     return true;
1315   case 1:
1316     return true; // We have r + r or r + i.
1317   case 2:
1318     if (AM.HasBaseReg) {
1319       // Reject 2 * r + r.
1320       return false;
1321     }
1322 
1323     // Allow 2 * r as r + r
1324     // Or  2 * r + i is allowed as r + r + i.
1325     return true;
1326   default: // Don't allow n * r
1327     return false;
1328   }
1329 }
1330 
1331 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1332                                              const AddrMode &AM, Type *Ty,
1333                                              unsigned AS, Instruction *I) const {
1334   // No global is ever allowed as a base.
1335   if (AM.BaseGV)
1336     return false;
1337 
1338   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1339     return isLegalGlobalAddressingMode(AM);
1340 
1341   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1342       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1343       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1344     // If the offset isn't a multiple of 4, it probably isn't going to be
1345     // correctly aligned.
1346     // FIXME: Can we get the real alignment here?
1347     if (AM.BaseOffs % 4 != 0)
1348       return isLegalMUBUFAddressingMode(AM);
1349 
1350     // There are no SMRD extloads, so if we have to do a small type access we
1351     // will use a MUBUF load.
1352     // FIXME?: We also need to do this if unaligned, but we don't know the
1353     // alignment here.
1354     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1355       return isLegalGlobalAddressingMode(AM);
1356 
1357     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1358       // SMRD instructions have an 8-bit, dword offset on SI.
1359       if (!isUInt<8>(AM.BaseOffs / 4))
1360         return false;
1361     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1362       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1363       // in 8-bits, it can use a smaller encoding.
1364       if (!isUInt<32>(AM.BaseOffs / 4))
1365         return false;
1366     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1367       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1368       if (!isUInt<20>(AM.BaseOffs))
1369         return false;
1370     } else
1371       llvm_unreachable("unhandled generation");
1372 
1373     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1374       return true;
1375 
1376     if (AM.Scale == 1 && AM.HasBaseReg)
1377       return true;
1378 
1379     return false;
1380 
1381   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1382     return isLegalMUBUFAddressingMode(AM);
1383   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1384              AS == AMDGPUAS::REGION_ADDRESS) {
1385     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1386     // field.
1387     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1388     // an 8-bit dword offset but we don't know the alignment here.
1389     if (!isUInt<16>(AM.BaseOffs))
1390       return false;
1391 
1392     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1393       return true;
1394 
1395     if (AM.Scale == 1 && AM.HasBaseReg)
1396       return true;
1397 
1398     return false;
1399   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1400              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1401     // For an unknown address space, this usually means that this is for some
1402     // reason being used for pure arithmetic, and not based on some addressing
1403     // computation. We don't have instructions that compute pointers with any
1404     // addressing modes, so treat them as having no offset like flat
1405     // instructions.
1406     return isLegalFlatAddressingMode(AM);
1407   }
1408 
1409   // Assume a user alias of global for unknown address spaces.
1410   return isLegalGlobalAddressingMode(AM);
1411 }
1412 
1413 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1414                                         const SelectionDAG &DAG) const {
1415   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1416     return (MemVT.getSizeInBits() <= 4 * 32);
1417   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1418     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1419     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1420   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1421     return (MemVT.getSizeInBits() <= 2 * 32);
1422   }
1423   return true;
1424 }
1425 
1426 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1427     unsigned Size, unsigned AddrSpace, Align Alignment,
1428     MachineMemOperand::Flags Flags, bool *IsFast) const {
1429   if (IsFast)
1430     *IsFast = false;
1431 
1432   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1433       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1434     // Check if alignment requirements for ds_read/write instructions are
1435     // disabled.
1436     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1437         !Subtarget->hasLDSMisalignedBug()) {
1438       if (IsFast)
1439         *IsFast = Alignment != Align(2);
1440       return true;
1441     }
1442 
1443     if (Size == 64) {
1444       // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1445       // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1446       // with adjacent offsets.
1447       bool AlignedBy4 = Alignment >= Align(4);
1448       if (IsFast)
1449         *IsFast = AlignedBy4;
1450 
1451       return AlignedBy4;
1452     }
1453     if (Size == 96) {
1454       // ds_read/write_b96 require 16-byte alignment on gfx8 and older.
1455       bool Aligned = Alignment >= Align(16);
1456       if (IsFast)
1457         *IsFast = Aligned;
1458 
1459       return Aligned;
1460     }
1461     if (Size == 128) {
1462       // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we
1463       // can do a 8 byte aligned, 16 byte access in a single operation using
1464       // ds_read2/write2_b64.
1465       bool Aligned = Alignment >= Align(8);
1466       if (IsFast)
1467         *IsFast = Aligned;
1468 
1469       return Aligned;
1470     }
1471   }
1472 
1473   // FIXME: We have to be conservative here and assume that flat operations
1474   // will access scratch.  If we had access to the IR function, then we
1475   // could determine if any private memory was used in the function.
1476   if (!Subtarget->hasUnalignedScratchAccess() &&
1477       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1478        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1479     bool AlignedBy4 = Alignment >= Align(4);
1480     if (IsFast)
1481       *IsFast = AlignedBy4;
1482 
1483     return AlignedBy4;
1484   }
1485 
1486   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1487       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1488         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1489     // If we have an uniform constant load, it still requires using a slow
1490     // buffer instruction if unaligned.
1491     if (IsFast) {
1492       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1493       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1494       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1495                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1496         Alignment >= Align(4) : Alignment != Align(2);
1497     }
1498 
1499     return true;
1500   }
1501 
1502   // Smaller than dword value must be aligned.
1503   if (Size < 32)
1504     return false;
1505 
1506   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1507   // byte-address are ignored, thus forcing Dword alignment.
1508   // This applies to private, global, and constant memory.
1509   if (IsFast)
1510     *IsFast = true;
1511 
1512   return Size >= 32 && Alignment >= Align(4);
1513 }
1514 
1515 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1516     EVT VT, unsigned AddrSpace, unsigned Alignment,
1517     MachineMemOperand::Flags Flags, bool *IsFast) const {
1518   if (IsFast)
1519     *IsFast = false;
1520 
1521   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1522   // which isn't a simple VT.
1523   // Until MVT is extended to handle this, simply check for the size and
1524   // rely on the condition below: allow accesses if the size is a multiple of 4.
1525   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1526                            VT.getStoreSize() > 16)) {
1527     return false;
1528   }
1529 
1530   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1531                                             Align(Alignment), Flags, IsFast);
1532 }
1533 
1534 EVT SITargetLowering::getOptimalMemOpType(
1535     const MemOp &Op, const AttributeList &FuncAttributes) const {
1536   // FIXME: Should account for address space here.
1537 
1538   // The default fallback uses the private pointer size as a guess for a type to
1539   // use. Make sure we switch these to 64-bit accesses.
1540 
1541   if (Op.size() >= 16 &&
1542       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1543     return MVT::v4i32;
1544 
1545   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1546     return MVT::v2i32;
1547 
1548   // Use the default.
1549   return MVT::Other;
1550 }
1551 
1552 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1553   const MemSDNode *MemNode = cast<MemSDNode>(N);
1554   const Value *Ptr = MemNode->getMemOperand()->getValue();
1555   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1556   return I && I->getMetadata("amdgpu.noclobber");
1557 }
1558 
1559 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1560                                            unsigned DestAS) const {
1561   // Flat -> private/local is a simple truncate.
1562   // Flat -> global is no-op
1563   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1564     return true;
1565 
1566   const GCNTargetMachine &TM =
1567       static_cast<const GCNTargetMachine &>(getTargetMachine());
1568   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1569 }
1570 
1571 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1572   const MemSDNode *MemNode = cast<MemSDNode>(N);
1573 
1574   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1575 }
1576 
1577 TargetLoweringBase::LegalizeTypeAction
1578 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1579   int NumElts = VT.getVectorNumElements();
1580   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1581     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1582   return TargetLoweringBase::getPreferredVectorAction(VT);
1583 }
1584 
1585 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1586                                                          Type *Ty) const {
1587   // FIXME: Could be smarter if called for vector constants.
1588   return true;
1589 }
1590 
1591 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1592   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1593     switch (Op) {
1594     case ISD::LOAD:
1595     case ISD::STORE:
1596 
1597     // These operations are done with 32-bit instructions anyway.
1598     case ISD::AND:
1599     case ISD::OR:
1600     case ISD::XOR:
1601     case ISD::SELECT:
1602       // TODO: Extensions?
1603       return true;
1604     default:
1605       return false;
1606     }
1607   }
1608 
1609   // SimplifySetCC uses this function to determine whether or not it should
1610   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1611   if (VT == MVT::i1 && Op == ISD::SETCC)
1612     return false;
1613 
1614   return TargetLowering::isTypeDesirableForOp(Op, VT);
1615 }
1616 
1617 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1618                                                    const SDLoc &SL,
1619                                                    SDValue Chain,
1620                                                    uint64_t Offset) const {
1621   const DataLayout &DL = DAG.getDataLayout();
1622   MachineFunction &MF = DAG.getMachineFunction();
1623   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1624 
1625   const ArgDescriptor *InputPtrReg;
1626   const TargetRegisterClass *RC;
1627   LLT ArgTy;
1628 
1629   std::tie(InputPtrReg, RC, ArgTy) =
1630       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1631 
1632   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1633   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1634   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1635     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1636 
1637   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1638 }
1639 
1640 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1641                                             const SDLoc &SL) const {
1642   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1643                                                FIRST_IMPLICIT);
1644   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1645 }
1646 
1647 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1648                                          const SDLoc &SL, SDValue Val,
1649                                          bool Signed,
1650                                          const ISD::InputArg *Arg) const {
1651   // First, if it is a widened vector, narrow it.
1652   if (VT.isVector() &&
1653       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1654     EVT NarrowedVT =
1655         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1656                          VT.getVectorNumElements());
1657     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1658                       DAG.getConstant(0, SL, MVT::i32));
1659   }
1660 
1661   // Then convert the vector elements or scalar value.
1662   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1663       VT.bitsLT(MemVT)) {
1664     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1665     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1666   }
1667 
1668   if (MemVT.isFloatingPoint())
1669     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1670   else if (Signed)
1671     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1672   else
1673     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1674 
1675   return Val;
1676 }
1677 
1678 SDValue SITargetLowering::lowerKernargMemParameter(
1679     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1680     uint64_t Offset, Align Alignment, bool Signed,
1681     const ISD::InputArg *Arg) const {
1682   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1683 
1684   // Try to avoid using an extload by loading earlier than the argument address,
1685   // and extracting the relevant bits. The load should hopefully be merged with
1686   // the previous argument.
1687   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1688     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1689     int64_t AlignDownOffset = alignDown(Offset, 4);
1690     int64_t OffsetDiff = Offset - AlignDownOffset;
1691 
1692     EVT IntVT = MemVT.changeTypeToInteger();
1693 
1694     // TODO: If we passed in the base kernel offset we could have a better
1695     // alignment than 4, but we don't really need it.
1696     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1697     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1698                                MachineMemOperand::MODereferenceable |
1699                                    MachineMemOperand::MOInvariant);
1700 
1701     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1702     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1703 
1704     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1705     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1706     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1707 
1708 
1709     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1710   }
1711 
1712   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1713   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1714                              MachineMemOperand::MODereferenceable |
1715                                  MachineMemOperand::MOInvariant);
1716 
1717   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1718   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1719 }
1720 
1721 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1722                                               const SDLoc &SL, SDValue Chain,
1723                                               const ISD::InputArg &Arg) const {
1724   MachineFunction &MF = DAG.getMachineFunction();
1725   MachineFrameInfo &MFI = MF.getFrameInfo();
1726 
1727   if (Arg.Flags.isByVal()) {
1728     unsigned Size = Arg.Flags.getByValSize();
1729     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1730     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1731   }
1732 
1733   unsigned ArgOffset = VA.getLocMemOffset();
1734   unsigned ArgSize = VA.getValVT().getStoreSize();
1735 
1736   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1737 
1738   // Create load nodes to retrieve arguments from the stack.
1739   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1740   SDValue ArgValue;
1741 
1742   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1743   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1744   MVT MemVT = VA.getValVT();
1745 
1746   switch (VA.getLocInfo()) {
1747   default:
1748     break;
1749   case CCValAssign::BCvt:
1750     MemVT = VA.getLocVT();
1751     break;
1752   case CCValAssign::SExt:
1753     ExtType = ISD::SEXTLOAD;
1754     break;
1755   case CCValAssign::ZExt:
1756     ExtType = ISD::ZEXTLOAD;
1757     break;
1758   case CCValAssign::AExt:
1759     ExtType = ISD::EXTLOAD;
1760     break;
1761   }
1762 
1763   ArgValue = DAG.getExtLoad(
1764     ExtType, SL, VA.getLocVT(), Chain, FIN,
1765     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1766     MemVT);
1767   return ArgValue;
1768 }
1769 
1770 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1771   const SIMachineFunctionInfo &MFI,
1772   EVT VT,
1773   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1774   const ArgDescriptor *Reg;
1775   const TargetRegisterClass *RC;
1776   LLT Ty;
1777 
1778   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1779   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1780 }
1781 
1782 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1783                                    CallingConv::ID CallConv,
1784                                    ArrayRef<ISD::InputArg> Ins,
1785                                    BitVector &Skipped,
1786                                    FunctionType *FType,
1787                                    SIMachineFunctionInfo *Info) {
1788   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1789     const ISD::InputArg *Arg = &Ins[I];
1790 
1791     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1792            "vector type argument should have been split");
1793 
1794     // First check if it's a PS input addr.
1795     if (CallConv == CallingConv::AMDGPU_PS &&
1796         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1797       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1798 
1799       // Inconveniently only the first part of the split is marked as isSplit,
1800       // so skip to the end. We only want to increment PSInputNum once for the
1801       // entire split argument.
1802       if (Arg->Flags.isSplit()) {
1803         while (!Arg->Flags.isSplitEnd()) {
1804           assert((!Arg->VT.isVector() ||
1805                   Arg->VT.getScalarSizeInBits() == 16) &&
1806                  "unexpected vector split in ps argument type");
1807           if (!SkipArg)
1808             Splits.push_back(*Arg);
1809           Arg = &Ins[++I];
1810         }
1811       }
1812 
1813       if (SkipArg) {
1814         // We can safely skip PS inputs.
1815         Skipped.set(Arg->getOrigArgIndex());
1816         ++PSInputNum;
1817         continue;
1818       }
1819 
1820       Info->markPSInputAllocated(PSInputNum);
1821       if (Arg->Used)
1822         Info->markPSInputEnabled(PSInputNum);
1823 
1824       ++PSInputNum;
1825     }
1826 
1827     Splits.push_back(*Arg);
1828   }
1829 }
1830 
1831 // Allocate special inputs passed in VGPRs.
1832 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1833                                                       MachineFunction &MF,
1834                                                       const SIRegisterInfo &TRI,
1835                                                       SIMachineFunctionInfo &Info) const {
1836   const LLT S32 = LLT::scalar(32);
1837   MachineRegisterInfo &MRI = MF.getRegInfo();
1838 
1839   if (Info.hasWorkItemIDX()) {
1840     Register Reg = AMDGPU::VGPR0;
1841     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1842 
1843     CCInfo.AllocateReg(Reg);
1844     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1845   }
1846 
1847   if (Info.hasWorkItemIDY()) {
1848     Register Reg = AMDGPU::VGPR1;
1849     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1850 
1851     CCInfo.AllocateReg(Reg);
1852     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1853   }
1854 
1855   if (Info.hasWorkItemIDZ()) {
1856     Register Reg = AMDGPU::VGPR2;
1857     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1858 
1859     CCInfo.AllocateReg(Reg);
1860     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1861   }
1862 }
1863 
1864 // Try to allocate a VGPR at the end of the argument list, or if no argument
1865 // VGPRs are left allocating a stack slot.
1866 // If \p Mask is is given it indicates bitfield position in the register.
1867 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1868 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1869                                          ArgDescriptor Arg = ArgDescriptor()) {
1870   if (Arg.isSet())
1871     return ArgDescriptor::createArg(Arg, Mask);
1872 
1873   ArrayRef<MCPhysReg> ArgVGPRs
1874     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1875   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1876   if (RegIdx == ArgVGPRs.size()) {
1877     // Spill to stack required.
1878     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1879 
1880     return ArgDescriptor::createStack(Offset, Mask);
1881   }
1882 
1883   unsigned Reg = ArgVGPRs[RegIdx];
1884   Reg = CCInfo.AllocateReg(Reg);
1885   assert(Reg != AMDGPU::NoRegister);
1886 
1887   MachineFunction &MF = CCInfo.getMachineFunction();
1888   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1889   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1890   return ArgDescriptor::createRegister(Reg, Mask);
1891 }
1892 
1893 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1894                                              const TargetRegisterClass *RC,
1895                                              unsigned NumArgRegs) {
1896   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1897   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1898   if (RegIdx == ArgSGPRs.size())
1899     report_fatal_error("ran out of SGPRs for arguments");
1900 
1901   unsigned Reg = ArgSGPRs[RegIdx];
1902   Reg = CCInfo.AllocateReg(Reg);
1903   assert(Reg != AMDGPU::NoRegister);
1904 
1905   MachineFunction &MF = CCInfo.getMachineFunction();
1906   MF.addLiveIn(Reg, RC);
1907   return ArgDescriptor::createRegister(Reg);
1908 }
1909 
1910 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1911   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1912 }
1913 
1914 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1915   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1916 }
1917 
1918 /// Allocate implicit function VGPR arguments at the end of allocated user
1919 /// arguments.
1920 void SITargetLowering::allocateSpecialInputVGPRs(
1921   CCState &CCInfo, MachineFunction &MF,
1922   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1923   const unsigned Mask = 0x3ff;
1924   ArgDescriptor Arg;
1925 
1926   if (Info.hasWorkItemIDX()) {
1927     Arg = allocateVGPR32Input(CCInfo, Mask);
1928     Info.setWorkItemIDX(Arg);
1929   }
1930 
1931   if (Info.hasWorkItemIDY()) {
1932     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1933     Info.setWorkItemIDY(Arg);
1934   }
1935 
1936   if (Info.hasWorkItemIDZ())
1937     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1938 }
1939 
1940 /// Allocate implicit function VGPR arguments in fixed registers.
1941 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1942   CCState &CCInfo, MachineFunction &MF,
1943   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1944   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1945   if (!Reg)
1946     report_fatal_error("failed to allocated VGPR for implicit arguments");
1947 
1948   const unsigned Mask = 0x3ff;
1949   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1950   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1951   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1952 }
1953 
1954 void SITargetLowering::allocateSpecialInputSGPRs(
1955   CCState &CCInfo,
1956   MachineFunction &MF,
1957   const SIRegisterInfo &TRI,
1958   SIMachineFunctionInfo &Info) const {
1959   auto &ArgInfo = Info.getArgInfo();
1960 
1961   // TODO: Unify handling with private memory pointers.
1962 
1963   if (Info.hasDispatchPtr())
1964     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1965 
1966   if (Info.hasQueuePtr())
1967     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1968 
1969   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1970   // constant offset from the kernarg segment.
1971   if (Info.hasImplicitArgPtr())
1972     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1973 
1974   if (Info.hasDispatchID())
1975     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1976 
1977   // flat_scratch_init is not applicable for non-kernel functions.
1978 
1979   if (Info.hasWorkGroupIDX())
1980     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1981 
1982   if (Info.hasWorkGroupIDY())
1983     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1984 
1985   if (Info.hasWorkGroupIDZ())
1986     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1987 }
1988 
1989 // Allocate special inputs passed in user SGPRs.
1990 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1991                                             MachineFunction &MF,
1992                                             const SIRegisterInfo &TRI,
1993                                             SIMachineFunctionInfo &Info) const {
1994   if (Info.hasImplicitBufferPtr()) {
1995     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1996     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1997     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1998   }
1999 
2000   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2001   if (Info.hasPrivateSegmentBuffer()) {
2002     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2003     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2004     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2005   }
2006 
2007   if (Info.hasDispatchPtr()) {
2008     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2009     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2010     CCInfo.AllocateReg(DispatchPtrReg);
2011   }
2012 
2013   if (Info.hasQueuePtr()) {
2014     Register QueuePtrReg = Info.addQueuePtr(TRI);
2015     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2016     CCInfo.AllocateReg(QueuePtrReg);
2017   }
2018 
2019   if (Info.hasKernargSegmentPtr()) {
2020     MachineRegisterInfo &MRI = MF.getRegInfo();
2021     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2022     CCInfo.AllocateReg(InputPtrReg);
2023 
2024     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2025     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2026   }
2027 
2028   if (Info.hasDispatchID()) {
2029     Register DispatchIDReg = Info.addDispatchID(TRI);
2030     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2031     CCInfo.AllocateReg(DispatchIDReg);
2032   }
2033 
2034   if (Info.hasFlatScratchInit()) {
2035     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2036     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2037     CCInfo.AllocateReg(FlatScratchInitReg);
2038   }
2039 
2040   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2041   // these from the dispatch pointer.
2042 }
2043 
2044 // Allocate special input registers that are initialized per-wave.
2045 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2046                                            MachineFunction &MF,
2047                                            SIMachineFunctionInfo &Info,
2048                                            CallingConv::ID CallConv,
2049                                            bool IsShader) const {
2050   if (Info.hasWorkGroupIDX()) {
2051     Register Reg = Info.addWorkGroupIDX();
2052     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2053     CCInfo.AllocateReg(Reg);
2054   }
2055 
2056   if (Info.hasWorkGroupIDY()) {
2057     Register Reg = Info.addWorkGroupIDY();
2058     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2059     CCInfo.AllocateReg(Reg);
2060   }
2061 
2062   if (Info.hasWorkGroupIDZ()) {
2063     Register Reg = Info.addWorkGroupIDZ();
2064     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2065     CCInfo.AllocateReg(Reg);
2066   }
2067 
2068   if (Info.hasWorkGroupInfo()) {
2069     Register Reg = Info.addWorkGroupInfo();
2070     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2071     CCInfo.AllocateReg(Reg);
2072   }
2073 
2074   if (Info.hasPrivateSegmentWaveByteOffset()) {
2075     // Scratch wave offset passed in system SGPR.
2076     unsigned PrivateSegmentWaveByteOffsetReg;
2077 
2078     if (IsShader) {
2079       PrivateSegmentWaveByteOffsetReg =
2080         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2081 
2082       // This is true if the scratch wave byte offset doesn't have a fixed
2083       // location.
2084       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2085         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2086         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2087       }
2088     } else
2089       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2090 
2091     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2092     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2093   }
2094 }
2095 
2096 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2097                                      MachineFunction &MF,
2098                                      const SIRegisterInfo &TRI,
2099                                      SIMachineFunctionInfo &Info) {
2100   // Now that we've figured out where the scratch register inputs are, see if
2101   // should reserve the arguments and use them directly.
2102   MachineFrameInfo &MFI = MF.getFrameInfo();
2103   bool HasStackObjects = MFI.hasStackObjects();
2104   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2105 
2106   // Record that we know we have non-spill stack objects so we don't need to
2107   // check all stack objects later.
2108   if (HasStackObjects)
2109     Info.setHasNonSpillStackObjects(true);
2110 
2111   // Everything live out of a block is spilled with fast regalloc, so it's
2112   // almost certain that spilling will be required.
2113   if (TM.getOptLevel() == CodeGenOpt::None)
2114     HasStackObjects = true;
2115 
2116   // For now assume stack access is needed in any callee functions, so we need
2117   // the scratch registers to pass in.
2118   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2119 
2120   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2121     // If we have stack objects, we unquestionably need the private buffer
2122     // resource. For the Code Object V2 ABI, this will be the first 4 user
2123     // SGPR inputs. We can reserve those and use them directly.
2124 
2125     Register PrivateSegmentBufferReg =
2126         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2127     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2128   } else {
2129     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2130     // We tentatively reserve the last registers (skipping the last registers
2131     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2132     // we'll replace these with the ones immediately after those which were
2133     // really allocated. In the prologue copies will be inserted from the
2134     // argument to these reserved registers.
2135 
2136     // Without HSA, relocations are used for the scratch pointer and the
2137     // buffer resource setup is always inserted in the prologue. Scratch wave
2138     // offset is still in an input SGPR.
2139     Info.setScratchRSrcReg(ReservedBufferReg);
2140   }
2141 
2142   MachineRegisterInfo &MRI = MF.getRegInfo();
2143 
2144   // For entry functions we have to set up the stack pointer if we use it,
2145   // whereas non-entry functions get this "for free". This means there is no
2146   // intrinsic advantage to using S32 over S34 in cases where we do not have
2147   // calls but do need a frame pointer (i.e. if we are requested to have one
2148   // because frame pointer elimination is disabled). To keep things simple we
2149   // only ever use S32 as the call ABI stack pointer, and so using it does not
2150   // imply we need a separate frame pointer.
2151   //
2152   // Try to use s32 as the SP, but move it if it would interfere with input
2153   // arguments. This won't work with calls though.
2154   //
2155   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2156   // registers.
2157   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2158     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2159   } else {
2160     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2161 
2162     if (MFI.hasCalls())
2163       report_fatal_error("call in graphics shader with too many input SGPRs");
2164 
2165     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2166       if (!MRI.isLiveIn(Reg)) {
2167         Info.setStackPtrOffsetReg(Reg);
2168         break;
2169       }
2170     }
2171 
2172     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2173       report_fatal_error("failed to find register for SP");
2174   }
2175 
2176   // hasFP should be accurate for entry functions even before the frame is
2177   // finalized, because it does not rely on the known stack size, only
2178   // properties like whether variable sized objects are present.
2179   if (ST.getFrameLowering()->hasFP(MF)) {
2180     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2181   }
2182 }
2183 
2184 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2185   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2186   return !Info->isEntryFunction();
2187 }
2188 
2189 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2190 
2191 }
2192 
2193 void SITargetLowering::insertCopiesSplitCSR(
2194   MachineBasicBlock *Entry,
2195   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2196   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2197 
2198   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2199   if (!IStart)
2200     return;
2201 
2202   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2203   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2204   MachineBasicBlock::iterator MBBI = Entry->begin();
2205   for (const MCPhysReg *I = IStart; *I; ++I) {
2206     const TargetRegisterClass *RC = nullptr;
2207     if (AMDGPU::SReg_64RegClass.contains(*I))
2208       RC = &AMDGPU::SGPR_64RegClass;
2209     else if (AMDGPU::SReg_32RegClass.contains(*I))
2210       RC = &AMDGPU::SGPR_32RegClass;
2211     else
2212       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2213 
2214     Register NewVR = MRI->createVirtualRegister(RC);
2215     // Create copy from CSR to a virtual register.
2216     Entry->addLiveIn(*I);
2217     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2218       .addReg(*I);
2219 
2220     // Insert the copy-back instructions right before the terminator.
2221     for (auto *Exit : Exits)
2222       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2223               TII->get(TargetOpcode::COPY), *I)
2224         .addReg(NewVR);
2225   }
2226 }
2227 
2228 SDValue SITargetLowering::LowerFormalArguments(
2229     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2230     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2231     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2232   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2233 
2234   MachineFunction &MF = DAG.getMachineFunction();
2235   const Function &Fn = MF.getFunction();
2236   FunctionType *FType = MF.getFunction().getFunctionType();
2237   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2238 
2239   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2240     DiagnosticInfoUnsupported NoGraphicsHSA(
2241         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2242     DAG.getContext()->diagnose(NoGraphicsHSA);
2243     return DAG.getEntryNode();
2244   }
2245 
2246   SmallVector<ISD::InputArg, 16> Splits;
2247   SmallVector<CCValAssign, 16> ArgLocs;
2248   BitVector Skipped(Ins.size());
2249   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2250                  *DAG.getContext());
2251 
2252   bool IsShader = AMDGPU::isShader(CallConv);
2253   bool IsKernel = AMDGPU::isKernel(CallConv);
2254   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2255 
2256   if (IsShader) {
2257     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2258 
2259     // At least one interpolation mode must be enabled or else the GPU will
2260     // hang.
2261     //
2262     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2263     // set PSInputAddr, the user wants to enable some bits after the compilation
2264     // based on run-time states. Since we can't know what the final PSInputEna
2265     // will look like, so we shouldn't do anything here and the user should take
2266     // responsibility for the correct programming.
2267     //
2268     // Otherwise, the following restrictions apply:
2269     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2270     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2271     //   enabled too.
2272     if (CallConv == CallingConv::AMDGPU_PS) {
2273       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2274            ((Info->getPSInputAddr() & 0xF) == 0 &&
2275             Info->isPSInputAllocated(11))) {
2276         CCInfo.AllocateReg(AMDGPU::VGPR0);
2277         CCInfo.AllocateReg(AMDGPU::VGPR1);
2278         Info->markPSInputAllocated(0);
2279         Info->markPSInputEnabled(0);
2280       }
2281       if (Subtarget->isAmdPalOS()) {
2282         // For isAmdPalOS, the user does not enable some bits after compilation
2283         // based on run-time states; the register values being generated here are
2284         // the final ones set in hardware. Therefore we need to apply the
2285         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2286         // a bit is set in PSInputAddr but not PSInputEnable is where the
2287         // frontend set up an input arg for a particular interpolation mode, but
2288         // nothing uses that input arg. Really we should have an earlier pass
2289         // that removes such an arg.)
2290         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2291         if ((PsInputBits & 0x7F) == 0 ||
2292             ((PsInputBits & 0xF) == 0 &&
2293              (PsInputBits >> 11 & 1)))
2294           Info->markPSInputEnabled(
2295               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2296       }
2297     }
2298 
2299     assert(!Info->hasDispatchPtr() &&
2300            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2301            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2302            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2303            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2304            !Info->hasWorkItemIDZ());
2305   } else if (IsKernel) {
2306     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2307   } else {
2308     Splits.append(Ins.begin(), Ins.end());
2309   }
2310 
2311   if (IsEntryFunc) {
2312     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2313     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2314   } else {
2315     // For the fixed ABI, pass workitem IDs in the last argument register.
2316     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2317       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2318   }
2319 
2320   if (IsKernel) {
2321     analyzeFormalArgumentsCompute(CCInfo, Ins);
2322   } else {
2323     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2324     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2325   }
2326 
2327   SmallVector<SDValue, 16> Chains;
2328 
2329   // FIXME: This is the minimum kernel argument alignment. We should improve
2330   // this to the maximum alignment of the arguments.
2331   //
2332   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2333   // kern arg offset.
2334   const Align KernelArgBaseAlign = Align(16);
2335 
2336   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2337     const ISD::InputArg &Arg = Ins[i];
2338     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2339       InVals.push_back(DAG.getUNDEF(Arg.VT));
2340       continue;
2341     }
2342 
2343     CCValAssign &VA = ArgLocs[ArgIdx++];
2344     MVT VT = VA.getLocVT();
2345 
2346     if (IsEntryFunc && VA.isMemLoc()) {
2347       VT = Ins[i].VT;
2348       EVT MemVT = VA.getLocVT();
2349 
2350       const uint64_t Offset = VA.getLocMemOffset();
2351       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2352 
2353       if (Arg.Flags.isByRef()) {
2354         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2355 
2356         const GCNTargetMachine &TM =
2357             static_cast<const GCNTargetMachine &>(getTargetMachine());
2358         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2359                                     Arg.Flags.getPointerAddrSpace())) {
2360           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2361                                      Arg.Flags.getPointerAddrSpace());
2362         }
2363 
2364         InVals.push_back(Ptr);
2365         continue;
2366       }
2367 
2368       SDValue Arg = lowerKernargMemParameter(
2369         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2370       Chains.push_back(Arg.getValue(1));
2371 
2372       auto *ParamTy =
2373         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2374       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2375           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2376                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2377         // On SI local pointers are just offsets into LDS, so they are always
2378         // less than 16-bits.  On CI and newer they could potentially be
2379         // real pointers, so we can't guarantee their size.
2380         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2381                           DAG.getValueType(MVT::i16));
2382       }
2383 
2384       InVals.push_back(Arg);
2385       continue;
2386     } else if (!IsEntryFunc && VA.isMemLoc()) {
2387       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2388       InVals.push_back(Val);
2389       if (!Arg.Flags.isByVal())
2390         Chains.push_back(Val.getValue(1));
2391       continue;
2392     }
2393 
2394     assert(VA.isRegLoc() && "Parameter must be in a register!");
2395 
2396     Register Reg = VA.getLocReg();
2397     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2398     EVT ValVT = VA.getValVT();
2399 
2400     Reg = MF.addLiveIn(Reg, RC);
2401     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2402 
2403     if (Arg.Flags.isSRet()) {
2404       // The return object should be reasonably addressable.
2405 
2406       // FIXME: This helps when the return is a real sret. If it is a
2407       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2408       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2409       unsigned NumBits
2410         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2411       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2412         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2413     }
2414 
2415     // If this is an 8 or 16-bit value, it is really passed promoted
2416     // to 32 bits. Insert an assert[sz]ext to capture this, then
2417     // truncate to the right size.
2418     switch (VA.getLocInfo()) {
2419     case CCValAssign::Full:
2420       break;
2421     case CCValAssign::BCvt:
2422       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2423       break;
2424     case CCValAssign::SExt:
2425       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2426                         DAG.getValueType(ValVT));
2427       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2428       break;
2429     case CCValAssign::ZExt:
2430       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2431                         DAG.getValueType(ValVT));
2432       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2433       break;
2434     case CCValAssign::AExt:
2435       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2436       break;
2437     default:
2438       llvm_unreachable("Unknown loc info!");
2439     }
2440 
2441     InVals.push_back(Val);
2442   }
2443 
2444   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2445     // Special inputs come after user arguments.
2446     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2447   }
2448 
2449   // Start adding system SGPRs.
2450   if (IsEntryFunc) {
2451     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2452   } else {
2453     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2454     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2455   }
2456 
2457   auto &ArgUsageInfo =
2458     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2459   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2460 
2461   unsigned StackArgSize = CCInfo.getNextStackOffset();
2462   Info->setBytesInStackArgArea(StackArgSize);
2463 
2464   return Chains.empty() ? Chain :
2465     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2466 }
2467 
2468 // TODO: If return values can't fit in registers, we should return as many as
2469 // possible in registers before passing on stack.
2470 bool SITargetLowering::CanLowerReturn(
2471   CallingConv::ID CallConv,
2472   MachineFunction &MF, bool IsVarArg,
2473   const SmallVectorImpl<ISD::OutputArg> &Outs,
2474   LLVMContext &Context) const {
2475   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2476   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2477   // for shaders. Vector types should be explicitly handled by CC.
2478   if (AMDGPU::isEntryFunctionCC(CallConv))
2479     return true;
2480 
2481   SmallVector<CCValAssign, 16> RVLocs;
2482   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2483   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2484 }
2485 
2486 SDValue
2487 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2488                               bool isVarArg,
2489                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2490                               const SmallVectorImpl<SDValue> &OutVals,
2491                               const SDLoc &DL, SelectionDAG &DAG) const {
2492   MachineFunction &MF = DAG.getMachineFunction();
2493   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2494 
2495   if (AMDGPU::isKernel(CallConv)) {
2496     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2497                                              OutVals, DL, DAG);
2498   }
2499 
2500   bool IsShader = AMDGPU::isShader(CallConv);
2501 
2502   Info->setIfReturnsVoid(Outs.empty());
2503   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2504 
2505   // CCValAssign - represent the assignment of the return value to a location.
2506   SmallVector<CCValAssign, 48> RVLocs;
2507   SmallVector<ISD::OutputArg, 48> Splits;
2508 
2509   // CCState - Info about the registers and stack slots.
2510   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2511                  *DAG.getContext());
2512 
2513   // Analyze outgoing return values.
2514   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2515 
2516   SDValue Flag;
2517   SmallVector<SDValue, 48> RetOps;
2518   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2519 
2520   // Add return address for callable functions.
2521   if (!Info->isEntryFunction()) {
2522     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2523     SDValue ReturnAddrReg = CreateLiveInRegister(
2524       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2525 
2526     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2527         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2528         MVT::i64);
2529     Chain =
2530         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2531     Flag = Chain.getValue(1);
2532     RetOps.push_back(ReturnAddrVirtualReg);
2533   }
2534 
2535   // Copy the result values into the output registers.
2536   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2537        ++I, ++RealRVLocIdx) {
2538     CCValAssign &VA = RVLocs[I];
2539     assert(VA.isRegLoc() && "Can only return in registers!");
2540     // TODO: Partially return in registers if return values don't fit.
2541     SDValue Arg = OutVals[RealRVLocIdx];
2542 
2543     // Copied from other backends.
2544     switch (VA.getLocInfo()) {
2545     case CCValAssign::Full:
2546       break;
2547     case CCValAssign::BCvt:
2548       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2549       break;
2550     case CCValAssign::SExt:
2551       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2552       break;
2553     case CCValAssign::ZExt:
2554       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2555       break;
2556     case CCValAssign::AExt:
2557       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2558       break;
2559     default:
2560       llvm_unreachable("Unknown loc info!");
2561     }
2562 
2563     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2564     Flag = Chain.getValue(1);
2565     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2566   }
2567 
2568   // FIXME: Does sret work properly?
2569   if (!Info->isEntryFunction()) {
2570     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2571     const MCPhysReg *I =
2572       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2573     if (I) {
2574       for (; *I; ++I) {
2575         if (AMDGPU::SReg_64RegClass.contains(*I))
2576           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2577         else if (AMDGPU::SReg_32RegClass.contains(*I))
2578           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2579         else
2580           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2581       }
2582     }
2583   }
2584 
2585   // Update chain and glue.
2586   RetOps[0] = Chain;
2587   if (Flag.getNode())
2588     RetOps.push_back(Flag);
2589 
2590   unsigned Opc = AMDGPUISD::ENDPGM;
2591   if (!IsWaveEnd)
2592     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2593   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2594 }
2595 
2596 SDValue SITargetLowering::LowerCallResult(
2597     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2598     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2599     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2600     SDValue ThisVal) const {
2601   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2602 
2603   // Assign locations to each value returned by this call.
2604   SmallVector<CCValAssign, 16> RVLocs;
2605   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2606                  *DAG.getContext());
2607   CCInfo.AnalyzeCallResult(Ins, RetCC);
2608 
2609   // Copy all of the result registers out of their specified physreg.
2610   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2611     CCValAssign VA = RVLocs[i];
2612     SDValue Val;
2613 
2614     if (VA.isRegLoc()) {
2615       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2616       Chain = Val.getValue(1);
2617       InFlag = Val.getValue(2);
2618     } else if (VA.isMemLoc()) {
2619       report_fatal_error("TODO: return values in memory");
2620     } else
2621       llvm_unreachable("unknown argument location type");
2622 
2623     switch (VA.getLocInfo()) {
2624     case CCValAssign::Full:
2625       break;
2626     case CCValAssign::BCvt:
2627       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2628       break;
2629     case CCValAssign::ZExt:
2630       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2631                         DAG.getValueType(VA.getValVT()));
2632       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2633       break;
2634     case CCValAssign::SExt:
2635       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2636                         DAG.getValueType(VA.getValVT()));
2637       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2638       break;
2639     case CCValAssign::AExt:
2640       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2641       break;
2642     default:
2643       llvm_unreachable("Unknown loc info!");
2644     }
2645 
2646     InVals.push_back(Val);
2647   }
2648 
2649   return Chain;
2650 }
2651 
2652 // Add code to pass special inputs required depending on used features separate
2653 // from the explicit user arguments present in the IR.
2654 void SITargetLowering::passSpecialInputs(
2655     CallLoweringInfo &CLI,
2656     CCState &CCInfo,
2657     const SIMachineFunctionInfo &Info,
2658     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2659     SmallVectorImpl<SDValue> &MemOpChains,
2660     SDValue Chain) const {
2661   // If we don't have a call site, this was a call inserted by
2662   // legalization. These can never use special inputs.
2663   if (!CLI.CB)
2664     return;
2665 
2666   SelectionDAG &DAG = CLI.DAG;
2667   const SDLoc &DL = CLI.DL;
2668 
2669   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2670   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2671 
2672   const AMDGPUFunctionArgInfo *CalleeArgInfo
2673     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2674   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2675     auto &ArgUsageInfo =
2676       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2677     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2678   }
2679 
2680   // TODO: Unify with private memory register handling. This is complicated by
2681   // the fact that at least in kernels, the input argument is not necessarily
2682   // in the same location as the input.
2683   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2684     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2685     AMDGPUFunctionArgInfo::QUEUE_PTR,
2686     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2687     AMDGPUFunctionArgInfo::DISPATCH_ID,
2688     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2689     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2690     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2691   };
2692 
2693   for (auto InputID : InputRegs) {
2694     const ArgDescriptor *OutgoingArg;
2695     const TargetRegisterClass *ArgRC;
2696     LLT ArgTy;
2697 
2698     std::tie(OutgoingArg, ArgRC, ArgTy) =
2699         CalleeArgInfo->getPreloadedValue(InputID);
2700     if (!OutgoingArg)
2701       continue;
2702 
2703     const ArgDescriptor *IncomingArg;
2704     const TargetRegisterClass *IncomingArgRC;
2705     LLT Ty;
2706     std::tie(IncomingArg, IncomingArgRC, Ty) =
2707         CallerArgInfo.getPreloadedValue(InputID);
2708     assert(IncomingArgRC == ArgRC);
2709 
2710     // All special arguments are ints for now.
2711     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2712     SDValue InputReg;
2713 
2714     if (IncomingArg) {
2715       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2716     } else {
2717       // The implicit arg ptr is special because it doesn't have a corresponding
2718       // input for kernels, and is computed from the kernarg segment pointer.
2719       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2720       InputReg = getImplicitArgPtr(DAG, DL);
2721     }
2722 
2723     if (OutgoingArg->isRegister()) {
2724       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2725       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2726         report_fatal_error("failed to allocate implicit input argument");
2727     } else {
2728       unsigned SpecialArgOffset =
2729           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2730       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2731                                               SpecialArgOffset);
2732       MemOpChains.push_back(ArgStore);
2733     }
2734   }
2735 
2736   // Pack workitem IDs into a single register or pass it as is if already
2737   // packed.
2738   const ArgDescriptor *OutgoingArg;
2739   const TargetRegisterClass *ArgRC;
2740   LLT Ty;
2741 
2742   std::tie(OutgoingArg, ArgRC, Ty) =
2743       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2744   if (!OutgoingArg)
2745     std::tie(OutgoingArg, ArgRC, Ty) =
2746         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2747   if (!OutgoingArg)
2748     std::tie(OutgoingArg, ArgRC, Ty) =
2749         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2750   if (!OutgoingArg)
2751     return;
2752 
2753   const ArgDescriptor *IncomingArgX = std::get<0>(
2754       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2755   const ArgDescriptor *IncomingArgY = std::get<0>(
2756       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2757   const ArgDescriptor *IncomingArgZ = std::get<0>(
2758       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2759 
2760   SDValue InputReg;
2761   SDLoc SL;
2762 
2763   // If incoming ids are not packed we need to pack them.
2764   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2765     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2766 
2767   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2768     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2769     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2770                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2771     InputReg = InputReg.getNode() ?
2772                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2773   }
2774 
2775   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2776     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2777     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2778                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2779     InputReg = InputReg.getNode() ?
2780                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2781   }
2782 
2783   if (!InputReg.getNode()) {
2784     // Workitem ids are already packed, any of present incoming arguments
2785     // will carry all required fields.
2786     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2787       IncomingArgX ? *IncomingArgX :
2788       IncomingArgY ? *IncomingArgY :
2789                      *IncomingArgZ, ~0u);
2790     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2791   }
2792 
2793   if (OutgoingArg->isRegister()) {
2794     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2795     CCInfo.AllocateReg(OutgoingArg->getRegister());
2796   } else {
2797     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2798     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2799                                             SpecialArgOffset);
2800     MemOpChains.push_back(ArgStore);
2801   }
2802 }
2803 
2804 static bool canGuaranteeTCO(CallingConv::ID CC) {
2805   return CC == CallingConv::Fast;
2806 }
2807 
2808 /// Return true if we might ever do TCO for calls with this calling convention.
2809 static bool mayTailCallThisCC(CallingConv::ID CC) {
2810   switch (CC) {
2811   case CallingConv::C:
2812     return true;
2813   default:
2814     return canGuaranteeTCO(CC);
2815   }
2816 }
2817 
2818 bool SITargetLowering::isEligibleForTailCallOptimization(
2819     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2820     const SmallVectorImpl<ISD::OutputArg> &Outs,
2821     const SmallVectorImpl<SDValue> &OutVals,
2822     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2823   if (!mayTailCallThisCC(CalleeCC))
2824     return false;
2825 
2826   MachineFunction &MF = DAG.getMachineFunction();
2827   const Function &CallerF = MF.getFunction();
2828   CallingConv::ID CallerCC = CallerF.getCallingConv();
2829   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2830   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2831 
2832   // Kernels aren't callable, and don't have a live in return address so it
2833   // doesn't make sense to do a tail call with entry functions.
2834   if (!CallerPreserved)
2835     return false;
2836 
2837   bool CCMatch = CallerCC == CalleeCC;
2838 
2839   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2840     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2841       return true;
2842     return false;
2843   }
2844 
2845   // TODO: Can we handle var args?
2846   if (IsVarArg)
2847     return false;
2848 
2849   for (const Argument &Arg : CallerF.args()) {
2850     if (Arg.hasByValAttr())
2851       return false;
2852   }
2853 
2854   LLVMContext &Ctx = *DAG.getContext();
2855 
2856   // Check that the call results are passed in the same way.
2857   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2858                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2859                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2860     return false;
2861 
2862   // The callee has to preserve all registers the caller needs to preserve.
2863   if (!CCMatch) {
2864     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2865     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2866       return false;
2867   }
2868 
2869   // Nothing more to check if the callee is taking no arguments.
2870   if (Outs.empty())
2871     return true;
2872 
2873   SmallVector<CCValAssign, 16> ArgLocs;
2874   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2875 
2876   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2877 
2878   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2879   // If the stack arguments for this call do not fit into our own save area then
2880   // the call cannot be made tail.
2881   // TODO: Is this really necessary?
2882   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2883     return false;
2884 
2885   const MachineRegisterInfo &MRI = MF.getRegInfo();
2886   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2887 }
2888 
2889 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2890   if (!CI->isTailCall())
2891     return false;
2892 
2893   const Function *ParentFn = CI->getParent()->getParent();
2894   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2895     return false;
2896   return true;
2897 }
2898 
2899 // The wave scratch offset register is used as the global base pointer.
2900 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2901                                     SmallVectorImpl<SDValue> &InVals) const {
2902   SelectionDAG &DAG = CLI.DAG;
2903   const SDLoc &DL = CLI.DL;
2904   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2905   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2906   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2907   SDValue Chain = CLI.Chain;
2908   SDValue Callee = CLI.Callee;
2909   bool &IsTailCall = CLI.IsTailCall;
2910   CallingConv::ID CallConv = CLI.CallConv;
2911   bool IsVarArg = CLI.IsVarArg;
2912   bool IsSibCall = false;
2913   bool IsThisReturn = false;
2914   MachineFunction &MF = DAG.getMachineFunction();
2915 
2916   if (Callee.isUndef() || isNullConstant(Callee)) {
2917     if (!CLI.IsTailCall) {
2918       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2919         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2920     }
2921 
2922     return Chain;
2923   }
2924 
2925   if (IsVarArg) {
2926     return lowerUnhandledCall(CLI, InVals,
2927                               "unsupported call to variadic function ");
2928   }
2929 
2930   if (!CLI.CB)
2931     report_fatal_error("unsupported libcall legalization");
2932 
2933   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2934       !CLI.CB->getCalledFunction()) {
2935     return lowerUnhandledCall(CLI, InVals,
2936                               "unsupported indirect call to function ");
2937   }
2938 
2939   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2940     return lowerUnhandledCall(CLI, InVals,
2941                               "unsupported required tail call to function ");
2942   }
2943 
2944   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2945     // Note the issue is with the CC of the calling function, not of the call
2946     // itself.
2947     return lowerUnhandledCall(CLI, InVals,
2948                           "unsupported call from graphics shader of function ");
2949   }
2950 
2951   if (IsTailCall) {
2952     IsTailCall = isEligibleForTailCallOptimization(
2953       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2954     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2955       report_fatal_error("failed to perform tail call elimination on a call "
2956                          "site marked musttail");
2957     }
2958 
2959     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2960 
2961     // A sibling call is one where we're under the usual C ABI and not planning
2962     // to change that but can still do a tail call:
2963     if (!TailCallOpt && IsTailCall)
2964       IsSibCall = true;
2965 
2966     if (IsTailCall)
2967       ++NumTailCalls;
2968   }
2969 
2970   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2971   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2972   SmallVector<SDValue, 8> MemOpChains;
2973 
2974   // Analyze operands of the call, assigning locations to each operand.
2975   SmallVector<CCValAssign, 16> ArgLocs;
2976   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2977   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2978 
2979   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2980     // With a fixed ABI, allocate fixed registers before user arguments.
2981     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2982   }
2983 
2984   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2985 
2986   // Get a count of how many bytes are to be pushed on the stack.
2987   unsigned NumBytes = CCInfo.getNextStackOffset();
2988 
2989   if (IsSibCall) {
2990     // Since we're not changing the ABI to make this a tail call, the memory
2991     // operands are already available in the caller's incoming argument space.
2992     NumBytes = 0;
2993   }
2994 
2995   // FPDiff is the byte offset of the call's argument area from the callee's.
2996   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2997   // by this amount for a tail call. In a sibling call it must be 0 because the
2998   // caller will deallocate the entire stack and the callee still expects its
2999   // arguments to begin at SP+0. Completely unused for non-tail calls.
3000   int32_t FPDiff = 0;
3001   MachineFrameInfo &MFI = MF.getFrameInfo();
3002 
3003   // Adjust the stack pointer for the new arguments...
3004   // These operations are automatically eliminated by the prolog/epilog pass
3005   if (!IsSibCall) {
3006     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3007 
3008     SmallVector<SDValue, 4> CopyFromChains;
3009 
3010     // In the HSA case, this should be an identity copy.
3011     SDValue ScratchRSrcReg
3012       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3013     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3014     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3015     Chain = DAG.getTokenFactor(DL, CopyFromChains);
3016   }
3017 
3018   MVT PtrVT = MVT::i32;
3019 
3020   // Walk the register/memloc assignments, inserting copies/loads.
3021   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3022     CCValAssign &VA = ArgLocs[i];
3023     SDValue Arg = OutVals[i];
3024 
3025     // Promote the value if needed.
3026     switch (VA.getLocInfo()) {
3027     case CCValAssign::Full:
3028       break;
3029     case CCValAssign::BCvt:
3030       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3031       break;
3032     case CCValAssign::ZExt:
3033       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3034       break;
3035     case CCValAssign::SExt:
3036       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3037       break;
3038     case CCValAssign::AExt:
3039       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3040       break;
3041     case CCValAssign::FPExt:
3042       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3043       break;
3044     default:
3045       llvm_unreachable("Unknown loc info!");
3046     }
3047 
3048     if (VA.isRegLoc()) {
3049       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3050     } else {
3051       assert(VA.isMemLoc());
3052 
3053       SDValue DstAddr;
3054       MachinePointerInfo DstInfo;
3055 
3056       unsigned LocMemOffset = VA.getLocMemOffset();
3057       int32_t Offset = LocMemOffset;
3058 
3059       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3060       MaybeAlign Alignment;
3061 
3062       if (IsTailCall) {
3063         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3064         unsigned OpSize = Flags.isByVal() ?
3065           Flags.getByValSize() : VA.getValVT().getStoreSize();
3066 
3067         // FIXME: We can have better than the minimum byval required alignment.
3068         Alignment =
3069             Flags.isByVal()
3070                 ? Flags.getNonZeroByValAlign()
3071                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3072 
3073         Offset = Offset + FPDiff;
3074         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3075 
3076         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3077         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3078 
3079         // Make sure any stack arguments overlapping with where we're storing
3080         // are loaded before this eventual operation. Otherwise they'll be
3081         // clobbered.
3082 
3083         // FIXME: Why is this really necessary? This seems to just result in a
3084         // lot of code to copy the stack and write them back to the same
3085         // locations, which are supposed to be immutable?
3086         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3087       } else {
3088         DstAddr = PtrOff;
3089         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3090         Alignment =
3091             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3092       }
3093 
3094       if (Outs[i].Flags.isByVal()) {
3095         SDValue SizeNode =
3096             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3097         SDValue Cpy =
3098             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3099                           Outs[i].Flags.getNonZeroByValAlign(),
3100                           /*isVol = */ false, /*AlwaysInline = */ true,
3101                           /*isTailCall = */ false, DstInfo,
3102                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3103 
3104         MemOpChains.push_back(Cpy);
3105       } else {
3106         SDValue Store =
3107             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3108         MemOpChains.push_back(Store);
3109       }
3110     }
3111   }
3112 
3113   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
3114     // Copy special input registers after user input arguments.
3115     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3116   }
3117 
3118   if (!MemOpChains.empty())
3119     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3120 
3121   // Build a sequence of copy-to-reg nodes chained together with token chain
3122   // and flag operands which copy the outgoing args into the appropriate regs.
3123   SDValue InFlag;
3124   for (auto &RegToPass : RegsToPass) {
3125     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3126                              RegToPass.second, InFlag);
3127     InFlag = Chain.getValue(1);
3128   }
3129 
3130 
3131   SDValue PhysReturnAddrReg;
3132   if (IsTailCall) {
3133     // Since the return is being combined with the call, we need to pass on the
3134     // return address.
3135 
3136     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3137     SDValue ReturnAddrReg = CreateLiveInRegister(
3138       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3139 
3140     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3141                                         MVT::i64);
3142     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3143     InFlag = Chain.getValue(1);
3144   }
3145 
3146   // We don't usually want to end the call-sequence here because we would tidy
3147   // the frame up *after* the call, however in the ABI-changing tail-call case
3148   // we've carefully laid out the parameters so that when sp is reset they'll be
3149   // in the correct location.
3150   if (IsTailCall && !IsSibCall) {
3151     Chain = DAG.getCALLSEQ_END(Chain,
3152                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3153                                DAG.getTargetConstant(0, DL, MVT::i32),
3154                                InFlag, DL);
3155     InFlag = Chain.getValue(1);
3156   }
3157 
3158   std::vector<SDValue> Ops;
3159   Ops.push_back(Chain);
3160   Ops.push_back(Callee);
3161   // Add a redundant copy of the callee global which will not be legalized, as
3162   // we need direct access to the callee later.
3163   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3164     const GlobalValue *GV = GSD->getGlobal();
3165     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3166   } else {
3167     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3168   }
3169 
3170   if (IsTailCall) {
3171     // Each tail call may have to adjust the stack by a different amount, so
3172     // this information must travel along with the operation for eventual
3173     // consumption by emitEpilogue.
3174     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3175 
3176     Ops.push_back(PhysReturnAddrReg);
3177   }
3178 
3179   // Add argument registers to the end of the list so that they are known live
3180   // into the call.
3181   for (auto &RegToPass : RegsToPass) {
3182     Ops.push_back(DAG.getRegister(RegToPass.first,
3183                                   RegToPass.second.getValueType()));
3184   }
3185 
3186   // Add a register mask operand representing the call-preserved registers.
3187 
3188   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3189   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3190   assert(Mask && "Missing call preserved mask for calling convention");
3191   Ops.push_back(DAG.getRegisterMask(Mask));
3192 
3193   if (InFlag.getNode())
3194     Ops.push_back(InFlag);
3195 
3196   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3197 
3198   // If we're doing a tall call, use a TC_RETURN here rather than an
3199   // actual call instruction.
3200   if (IsTailCall) {
3201     MFI.setHasTailCall();
3202     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3203   }
3204 
3205   // Returns a chain and a flag for retval copy to use.
3206   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3207   Chain = Call.getValue(0);
3208   InFlag = Call.getValue(1);
3209 
3210   uint64_t CalleePopBytes = NumBytes;
3211   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3212                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3213                              InFlag, DL);
3214   if (!Ins.empty())
3215     InFlag = Chain.getValue(1);
3216 
3217   // Handle result values, copying them out of physregs into vregs that we
3218   // return.
3219   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3220                          InVals, IsThisReturn,
3221                          IsThisReturn ? OutVals[0] : SDValue());
3222 }
3223 
3224 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3225 // except for applying the wave size scale to the increment amount.
3226 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3227     SDValue Op, SelectionDAG &DAG) const {
3228   const MachineFunction &MF = DAG.getMachineFunction();
3229   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3230 
3231   SDLoc dl(Op);
3232   EVT VT = Op.getValueType();
3233   SDValue Tmp1 = Op;
3234   SDValue Tmp2 = Op.getValue(1);
3235   SDValue Tmp3 = Op.getOperand(2);
3236   SDValue Chain = Tmp1.getOperand(0);
3237 
3238   Register SPReg = Info->getStackPtrOffsetReg();
3239 
3240   // Chain the dynamic stack allocation so that it doesn't modify the stack
3241   // pointer when other instructions are using the stack.
3242   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3243 
3244   SDValue Size  = Tmp2.getOperand(1);
3245   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3246   Chain = SP.getValue(1);
3247   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3248   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3249   const TargetFrameLowering *TFL = ST.getFrameLowering();
3250   unsigned Opc =
3251     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3252     ISD::ADD : ISD::SUB;
3253 
3254   SDValue ScaledSize = DAG.getNode(
3255       ISD::SHL, dl, VT, Size,
3256       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3257 
3258   Align StackAlign = TFL->getStackAlign();
3259   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3260   if (Alignment && *Alignment > StackAlign) {
3261     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3262                        DAG.getConstant(-(uint64_t)Alignment->value()
3263                                            << ST.getWavefrontSizeLog2(),
3264                                        dl, VT));
3265   }
3266 
3267   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3268   Tmp2 = DAG.getCALLSEQ_END(
3269       Chain, DAG.getIntPtrConstant(0, dl, true),
3270       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3271 
3272   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3273 }
3274 
3275 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3276                                                   SelectionDAG &DAG) const {
3277   // We only handle constant sizes here to allow non-entry block, static sized
3278   // allocas. A truly dynamic value is more difficult to support because we
3279   // don't know if the size value is uniform or not. If the size isn't uniform,
3280   // we would need to do a wave reduction to get the maximum size to know how
3281   // much to increment the uniform stack pointer.
3282   SDValue Size = Op.getOperand(1);
3283   if (isa<ConstantSDNode>(Size))
3284       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3285 
3286   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3287 }
3288 
3289 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3290                                              const MachineFunction &MF) const {
3291   Register Reg = StringSwitch<Register>(RegName)
3292     .Case("m0", AMDGPU::M0)
3293     .Case("exec", AMDGPU::EXEC)
3294     .Case("exec_lo", AMDGPU::EXEC_LO)
3295     .Case("exec_hi", AMDGPU::EXEC_HI)
3296     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3297     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3298     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3299     .Default(Register());
3300 
3301   if (Reg == AMDGPU::NoRegister) {
3302     report_fatal_error(Twine("invalid register name \""
3303                              + StringRef(RegName)  + "\"."));
3304 
3305   }
3306 
3307   if (!Subtarget->hasFlatScrRegister() &&
3308        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3309     report_fatal_error(Twine("invalid register \""
3310                              + StringRef(RegName)  + "\" for subtarget."));
3311   }
3312 
3313   switch (Reg) {
3314   case AMDGPU::M0:
3315   case AMDGPU::EXEC_LO:
3316   case AMDGPU::EXEC_HI:
3317   case AMDGPU::FLAT_SCR_LO:
3318   case AMDGPU::FLAT_SCR_HI:
3319     if (VT.getSizeInBits() == 32)
3320       return Reg;
3321     break;
3322   case AMDGPU::EXEC:
3323   case AMDGPU::FLAT_SCR:
3324     if (VT.getSizeInBits() == 64)
3325       return Reg;
3326     break;
3327   default:
3328     llvm_unreachable("missing register type checking");
3329   }
3330 
3331   report_fatal_error(Twine("invalid type for register \""
3332                            + StringRef(RegName) + "\"."));
3333 }
3334 
3335 // If kill is not the last instruction, split the block so kill is always a
3336 // proper terminator.
3337 MachineBasicBlock *
3338 SITargetLowering::splitKillBlock(MachineInstr &MI,
3339                                  MachineBasicBlock *BB) const {
3340   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3341   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3342   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3343   return SplitBB;
3344 }
3345 
3346 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3347 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3348 // be the first instruction in the remainder block.
3349 //
3350 /// \returns { LoopBody, Remainder }
3351 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3352 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3353   MachineFunction *MF = MBB.getParent();
3354   MachineBasicBlock::iterator I(&MI);
3355 
3356   // To insert the loop we need to split the block. Move everything after this
3357   // point to a new block, and insert a new empty block between the two.
3358   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3359   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3360   MachineFunction::iterator MBBI(MBB);
3361   ++MBBI;
3362 
3363   MF->insert(MBBI, LoopBB);
3364   MF->insert(MBBI, RemainderBB);
3365 
3366   LoopBB->addSuccessor(LoopBB);
3367   LoopBB->addSuccessor(RemainderBB);
3368 
3369   // Move the rest of the block into a new block.
3370   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3371 
3372   if (InstInLoop) {
3373     auto Next = std::next(I);
3374 
3375     // Move instruction to loop body.
3376     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3377 
3378     // Move the rest of the block.
3379     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3380   } else {
3381     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3382   }
3383 
3384   MBB.addSuccessor(LoopBB);
3385 
3386   return std::make_pair(LoopBB, RemainderBB);
3387 }
3388 
3389 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3390 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3391   MachineBasicBlock *MBB = MI.getParent();
3392   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3393   auto I = MI.getIterator();
3394   auto E = std::next(I);
3395 
3396   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3397     .addImm(0);
3398 
3399   MIBundleBuilder Bundler(*MBB, I, E);
3400   finalizeBundle(*MBB, Bundler.begin());
3401 }
3402 
3403 MachineBasicBlock *
3404 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3405                                          MachineBasicBlock *BB) const {
3406   const DebugLoc &DL = MI.getDebugLoc();
3407 
3408   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3409 
3410   MachineBasicBlock *LoopBB;
3411   MachineBasicBlock *RemainderBB;
3412   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3413 
3414   // Apparently kill flags are only valid if the def is in the same block?
3415   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3416     Src->setIsKill(false);
3417 
3418   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3419 
3420   MachineBasicBlock::iterator I = LoopBB->end();
3421 
3422   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3423     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3424 
3425   // Clear TRAP_STS.MEM_VIOL
3426   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3427     .addImm(0)
3428     .addImm(EncodedReg);
3429 
3430   bundleInstWithWaitcnt(MI);
3431 
3432   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3433 
3434   // Load and check TRAP_STS.MEM_VIOL
3435   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3436     .addImm(EncodedReg);
3437 
3438   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3439   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3440     .addReg(Reg, RegState::Kill)
3441     .addImm(0);
3442   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3443     .addMBB(LoopBB);
3444 
3445   return RemainderBB;
3446 }
3447 
3448 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3449 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3450 // will only do one iteration. In the worst case, this will loop 64 times.
3451 //
3452 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3453 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3454   const SIInstrInfo *TII,
3455   MachineRegisterInfo &MRI,
3456   MachineBasicBlock &OrigBB,
3457   MachineBasicBlock &LoopBB,
3458   const DebugLoc &DL,
3459   const MachineOperand &IdxReg,
3460   unsigned InitReg,
3461   unsigned ResultReg,
3462   unsigned PhiReg,
3463   unsigned InitSaveExecReg,
3464   int Offset,
3465   bool UseGPRIdxMode,
3466   bool IsIndirectSrc) {
3467   MachineFunction *MF = OrigBB.getParent();
3468   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3469   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3470   MachineBasicBlock::iterator I = LoopBB.begin();
3471 
3472   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3473   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3474   Register NewExec = MRI.createVirtualRegister(BoolRC);
3475   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3476   Register CondReg = MRI.createVirtualRegister(BoolRC);
3477 
3478   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3479     .addReg(InitReg)
3480     .addMBB(&OrigBB)
3481     .addReg(ResultReg)
3482     .addMBB(&LoopBB);
3483 
3484   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3485     .addReg(InitSaveExecReg)
3486     .addMBB(&OrigBB)
3487     .addReg(NewExec)
3488     .addMBB(&LoopBB);
3489 
3490   // Read the next variant <- also loop target.
3491   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3492     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3493 
3494   // Compare the just read M0 value to all possible Idx values.
3495   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3496     .addReg(CurrentIdxReg)
3497     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3498 
3499   // Update EXEC, save the original EXEC value to VCC.
3500   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3501                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3502           NewExec)
3503     .addReg(CondReg, RegState::Kill);
3504 
3505   MRI.setSimpleHint(NewExec, CondReg);
3506 
3507   if (UseGPRIdxMode) {
3508     unsigned IdxReg;
3509     if (Offset == 0) {
3510       IdxReg = CurrentIdxReg;
3511     } else {
3512       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3513       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3514         .addReg(CurrentIdxReg, RegState::Kill)
3515         .addImm(Offset);
3516     }
3517     unsigned IdxMode = IsIndirectSrc ?
3518       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3519     MachineInstr *SetOn =
3520       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3521       .addReg(IdxReg, RegState::Kill)
3522       .addImm(IdxMode);
3523     SetOn->getOperand(3).setIsUndef();
3524   } else {
3525     // Move index from VCC into M0
3526     if (Offset == 0) {
3527       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3528         .addReg(CurrentIdxReg, RegState::Kill);
3529     } else {
3530       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3531         .addReg(CurrentIdxReg, RegState::Kill)
3532         .addImm(Offset);
3533     }
3534   }
3535 
3536   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3537   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3538   MachineInstr *InsertPt =
3539     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3540                                                   : AMDGPU::S_XOR_B64_term), Exec)
3541       .addReg(Exec)
3542       .addReg(NewExec);
3543 
3544   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3545   // s_cbranch_scc0?
3546 
3547   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3548   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3549     .addMBB(&LoopBB);
3550 
3551   return InsertPt->getIterator();
3552 }
3553 
3554 // This has slightly sub-optimal regalloc when the source vector is killed by
3555 // the read. The register allocator does not understand that the kill is
3556 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3557 // subregister from it, using 1 more VGPR than necessary. This was saved when
3558 // this was expanded after register allocation.
3559 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3560                                                   MachineBasicBlock &MBB,
3561                                                   MachineInstr &MI,
3562                                                   unsigned InitResultReg,
3563                                                   unsigned PhiReg,
3564                                                   int Offset,
3565                                                   bool UseGPRIdxMode,
3566                                                   bool IsIndirectSrc) {
3567   MachineFunction *MF = MBB.getParent();
3568   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3569   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3570   MachineRegisterInfo &MRI = MF->getRegInfo();
3571   const DebugLoc &DL = MI.getDebugLoc();
3572   MachineBasicBlock::iterator I(&MI);
3573 
3574   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3575   Register DstReg = MI.getOperand(0).getReg();
3576   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3577   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3578   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3579   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3580 
3581   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3582 
3583   // Save the EXEC mask
3584   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3585     .addReg(Exec);
3586 
3587   MachineBasicBlock *LoopBB;
3588   MachineBasicBlock *RemainderBB;
3589   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3590 
3591   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3592 
3593   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3594                                       InitResultReg, DstReg, PhiReg, TmpExec,
3595                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3596   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3597   MachineFunction::iterator MBBI(LoopBB);
3598   ++MBBI;
3599   MF->insert(MBBI, LandingPad);
3600   LoopBB->removeSuccessor(RemainderBB);
3601   LandingPad->addSuccessor(RemainderBB);
3602   LoopBB->addSuccessor(LandingPad);
3603   MachineBasicBlock::iterator First = LandingPad->begin();
3604   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3605     .addReg(SaveExec);
3606 
3607   return InsPt;
3608 }
3609 
3610 // Returns subreg index, offset
3611 static std::pair<unsigned, int>
3612 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3613                             const TargetRegisterClass *SuperRC,
3614                             unsigned VecReg,
3615                             int Offset) {
3616   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3617 
3618   // Skip out of bounds offsets, or else we would end up using an undefined
3619   // register.
3620   if (Offset >= NumElts || Offset < 0)
3621     return std::make_pair(AMDGPU::sub0, Offset);
3622 
3623   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3624 }
3625 
3626 // Return true if the index is an SGPR and was set.
3627 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3628                                  MachineRegisterInfo &MRI,
3629                                  MachineInstr &MI,
3630                                  int Offset,
3631                                  bool UseGPRIdxMode,
3632                                  bool IsIndirectSrc) {
3633   MachineBasicBlock *MBB = MI.getParent();
3634   const DebugLoc &DL = MI.getDebugLoc();
3635   MachineBasicBlock::iterator I(&MI);
3636 
3637   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3638   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3639 
3640   assert(Idx->getReg() != AMDGPU::NoRegister);
3641 
3642   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3643     return false;
3644 
3645   if (UseGPRIdxMode) {
3646     unsigned IdxMode = IsIndirectSrc ?
3647       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3648     if (Offset == 0) {
3649       MachineInstr *SetOn =
3650           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3651               .add(*Idx)
3652               .addImm(IdxMode);
3653 
3654       SetOn->getOperand(3).setIsUndef();
3655     } else {
3656       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3657       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3658           .add(*Idx)
3659           .addImm(Offset);
3660       MachineInstr *SetOn =
3661         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3662         .addReg(Tmp, RegState::Kill)
3663         .addImm(IdxMode);
3664 
3665       SetOn->getOperand(3).setIsUndef();
3666     }
3667 
3668     return true;
3669   }
3670 
3671   if (Offset == 0) {
3672     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3673       .add(*Idx);
3674   } else {
3675     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3676       .add(*Idx)
3677       .addImm(Offset);
3678   }
3679 
3680   return true;
3681 }
3682 
3683 // Control flow needs to be inserted if indexing with a VGPR.
3684 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3685                                           MachineBasicBlock &MBB,
3686                                           const GCNSubtarget &ST) {
3687   const SIInstrInfo *TII = ST.getInstrInfo();
3688   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3689   MachineFunction *MF = MBB.getParent();
3690   MachineRegisterInfo &MRI = MF->getRegInfo();
3691 
3692   Register Dst = MI.getOperand(0).getReg();
3693   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3694   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3695 
3696   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3697 
3698   unsigned SubReg;
3699   std::tie(SubReg, Offset)
3700     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3701 
3702   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3703 
3704   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3705     MachineBasicBlock::iterator I(&MI);
3706     const DebugLoc &DL = MI.getDebugLoc();
3707 
3708     if (UseGPRIdxMode) {
3709       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3710       // to avoid interfering with other uses, so probably requires a new
3711       // optimization pass.
3712       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3713         .addReg(SrcReg, 0, SubReg)
3714         .addReg(SrcReg, RegState::Implicit)
3715         .addReg(AMDGPU::M0, RegState::Implicit);
3716       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3717     } else {
3718       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3719         .addReg(SrcReg, 0, SubReg)
3720         .addReg(SrcReg, RegState::Implicit);
3721     }
3722 
3723     MI.eraseFromParent();
3724 
3725     return &MBB;
3726   }
3727 
3728   const DebugLoc &DL = MI.getDebugLoc();
3729   MachineBasicBlock::iterator I(&MI);
3730 
3731   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3732   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3733 
3734   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3735 
3736   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3737                               Offset, UseGPRIdxMode, true);
3738   MachineBasicBlock *LoopBB = InsPt->getParent();
3739 
3740   if (UseGPRIdxMode) {
3741     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3742       .addReg(SrcReg, 0, SubReg)
3743       .addReg(SrcReg, RegState::Implicit)
3744       .addReg(AMDGPU::M0, RegState::Implicit);
3745     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3746   } else {
3747     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3748       .addReg(SrcReg, 0, SubReg)
3749       .addReg(SrcReg, RegState::Implicit);
3750   }
3751 
3752   MI.eraseFromParent();
3753 
3754   return LoopBB;
3755 }
3756 
3757 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3758                                           MachineBasicBlock &MBB,
3759                                           const GCNSubtarget &ST) {
3760   const SIInstrInfo *TII = ST.getInstrInfo();
3761   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3762   MachineFunction *MF = MBB.getParent();
3763   MachineRegisterInfo &MRI = MF->getRegInfo();
3764 
3765   Register Dst = MI.getOperand(0).getReg();
3766   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3767   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3768   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3769   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3770   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3771 
3772   // This can be an immediate, but will be folded later.
3773   assert(Val->getReg());
3774 
3775   unsigned SubReg;
3776   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3777                                                          SrcVec->getReg(),
3778                                                          Offset);
3779   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3780 
3781   if (Idx->getReg() == AMDGPU::NoRegister) {
3782     MachineBasicBlock::iterator I(&MI);
3783     const DebugLoc &DL = MI.getDebugLoc();
3784 
3785     assert(Offset == 0);
3786 
3787     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3788         .add(*SrcVec)
3789         .add(*Val)
3790         .addImm(SubReg);
3791 
3792     MI.eraseFromParent();
3793     return &MBB;
3794   }
3795 
3796   const MCInstrDesc &MovRelDesc
3797     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3798 
3799   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3800     MachineBasicBlock::iterator I(&MI);
3801     const DebugLoc &DL = MI.getDebugLoc();
3802     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3803       .addReg(SrcVec->getReg())
3804       .add(*Val)
3805       .addImm(SubReg);
3806     if (UseGPRIdxMode)
3807       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3808 
3809     MI.eraseFromParent();
3810     return &MBB;
3811   }
3812 
3813   if (Val->isReg())
3814     MRI.clearKillFlags(Val->getReg());
3815 
3816   const DebugLoc &DL = MI.getDebugLoc();
3817 
3818   Register PhiReg = MRI.createVirtualRegister(VecRC);
3819 
3820   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3821                               Offset, UseGPRIdxMode, false);
3822   MachineBasicBlock *LoopBB = InsPt->getParent();
3823 
3824   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3825     .addReg(PhiReg)
3826     .add(*Val)
3827     .addImm(AMDGPU::sub0);
3828   if (UseGPRIdxMode)
3829     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3830 
3831   MI.eraseFromParent();
3832   return LoopBB;
3833 }
3834 
3835 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3836   MachineInstr &MI, MachineBasicBlock *BB) const {
3837 
3838   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3839   MachineFunction *MF = BB->getParent();
3840   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3841 
3842   switch (MI.getOpcode()) {
3843   case AMDGPU::S_UADDO_PSEUDO:
3844   case AMDGPU::S_USUBO_PSEUDO: {
3845     const DebugLoc &DL = MI.getDebugLoc();
3846     MachineOperand &Dest0 = MI.getOperand(0);
3847     MachineOperand &Dest1 = MI.getOperand(1);
3848     MachineOperand &Src0 = MI.getOperand(2);
3849     MachineOperand &Src1 = MI.getOperand(3);
3850 
3851     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3852                        ? AMDGPU::S_ADD_I32
3853                        : AMDGPU::S_SUB_I32;
3854     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3855 
3856     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3857         .addImm(1)
3858         .addImm(0);
3859 
3860     MI.eraseFromParent();
3861     return BB;
3862   }
3863   case AMDGPU::S_ADD_U64_PSEUDO:
3864   case AMDGPU::S_SUB_U64_PSEUDO: {
3865     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3866     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3867     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3868     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3869     const DebugLoc &DL = MI.getDebugLoc();
3870 
3871     MachineOperand &Dest = MI.getOperand(0);
3872     MachineOperand &Src0 = MI.getOperand(1);
3873     MachineOperand &Src1 = MI.getOperand(2);
3874 
3875     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3876     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3877 
3878     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3879         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3880     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3881         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3882 
3883     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3884         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3885     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3886         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3887 
3888     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3889 
3890     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3891     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3892     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3893     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3894     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3895         .addReg(DestSub0)
3896         .addImm(AMDGPU::sub0)
3897         .addReg(DestSub1)
3898         .addImm(AMDGPU::sub1);
3899     MI.eraseFromParent();
3900     return BB;
3901   }
3902   case AMDGPU::V_ADD_U64_PSEUDO:
3903   case AMDGPU::V_SUB_U64_PSEUDO: {
3904     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3905     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3906     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3907     const DebugLoc &DL = MI.getDebugLoc();
3908 
3909     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3910 
3911     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3912 
3913     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3914     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3915 
3916     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3917     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3918 
3919     MachineOperand &Dest = MI.getOperand(0);
3920     MachineOperand &Src0 = MI.getOperand(1);
3921     MachineOperand &Src1 = MI.getOperand(2);
3922 
3923     const TargetRegisterClass *Src0RC = Src0.isReg()
3924                                             ? MRI.getRegClass(Src0.getReg())
3925                                             : &AMDGPU::VReg_64RegClass;
3926     const TargetRegisterClass *Src1RC = Src1.isReg()
3927                                             ? MRI.getRegClass(Src1.getReg())
3928                                             : &AMDGPU::VReg_64RegClass;
3929 
3930     const TargetRegisterClass *Src0SubRC =
3931         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3932     const TargetRegisterClass *Src1SubRC =
3933         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3934 
3935     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3936         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3937     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3938         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3939 
3940     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3941         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3942     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3943         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3944 
3945     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3946     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3947                                .addReg(CarryReg, RegState::Define)
3948                                .add(SrcReg0Sub0)
3949                                .add(SrcReg1Sub0)
3950                                .addImm(0); // clamp bit
3951 
3952     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3953     MachineInstr *HiHalf =
3954         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3955             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3956             .add(SrcReg0Sub1)
3957             .add(SrcReg1Sub1)
3958             .addReg(CarryReg, RegState::Kill)
3959             .addImm(0); // clamp bit
3960 
3961     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3962         .addReg(DestSub0)
3963         .addImm(AMDGPU::sub0)
3964         .addReg(DestSub1)
3965         .addImm(AMDGPU::sub1);
3966     TII->legalizeOperands(*LoHalf);
3967     TII->legalizeOperands(*HiHalf);
3968     MI.eraseFromParent();
3969     return BB;
3970   }
3971   case AMDGPU::S_ADD_CO_PSEUDO:
3972   case AMDGPU::S_SUB_CO_PSEUDO: {
3973     // This pseudo has a chance to be selected
3974     // only from uniform add/subcarry node. All the VGPR operands
3975     // therefore assumed to be splat vectors.
3976     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3977     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3978     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3979     MachineBasicBlock::iterator MII = MI;
3980     const DebugLoc &DL = MI.getDebugLoc();
3981     MachineOperand &Dest = MI.getOperand(0);
3982     MachineOperand &CarryDest = MI.getOperand(1);
3983     MachineOperand &Src0 = MI.getOperand(2);
3984     MachineOperand &Src1 = MI.getOperand(3);
3985     MachineOperand &Src2 = MI.getOperand(4);
3986     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3987                        ? AMDGPU::S_ADDC_U32
3988                        : AMDGPU::S_SUBB_U32;
3989     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3990       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3991       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3992           .addReg(Src0.getReg());
3993       Src0.setReg(RegOp0);
3994     }
3995     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3996       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3997       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3998           .addReg(Src1.getReg());
3999       Src1.setReg(RegOp1);
4000     }
4001     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4002     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4003       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4004           .addReg(Src2.getReg());
4005       Src2.setReg(RegOp2);
4006     }
4007 
4008     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
4009       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4010           .addReg(Src2.getReg())
4011           .addImm(0);
4012     } else {
4013       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4014           .addReg(Src2.getReg())
4015           .addImm(0);
4016     }
4017 
4018     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4019 
4020     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4021       .addReg(AMDGPU::SCC);
4022     MI.eraseFromParent();
4023     return BB;
4024   }
4025   case AMDGPU::SI_INIT_M0: {
4026     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4027             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4028         .add(MI.getOperand(0));
4029     MI.eraseFromParent();
4030     return BB;
4031   }
4032   case AMDGPU::SI_INIT_EXEC:
4033     // This should be before all vector instructions.
4034     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
4035             AMDGPU::EXEC)
4036         .addImm(MI.getOperand(0).getImm());
4037     MI.eraseFromParent();
4038     return BB;
4039 
4040   case AMDGPU::SI_INIT_EXEC_LO:
4041     // This should be before all vector instructions.
4042     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
4043             AMDGPU::EXEC_LO)
4044         .addImm(MI.getOperand(0).getImm());
4045     MI.eraseFromParent();
4046     return BB;
4047 
4048   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
4049     // Extract the thread count from an SGPR input and set EXEC accordingly.
4050     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
4051     //
4052     // S_BFE_U32 count, input, {shift, 7}
4053     // S_BFM_B64 exec, count, 0
4054     // S_CMP_EQ_U32 count, 64
4055     // S_CMOV_B64 exec, -1
4056     MachineInstr *FirstMI = &*BB->begin();
4057     MachineRegisterInfo &MRI = MF->getRegInfo();
4058     Register InputReg = MI.getOperand(0).getReg();
4059     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4060     bool Found = false;
4061 
4062     // Move the COPY of the input reg to the beginning, so that we can use it.
4063     for (auto I = BB->begin(); I != &MI; I++) {
4064       if (I->getOpcode() != TargetOpcode::COPY ||
4065           I->getOperand(0).getReg() != InputReg)
4066         continue;
4067 
4068       if (I == FirstMI) {
4069         FirstMI = &*++BB->begin();
4070       } else {
4071         I->removeFromParent();
4072         BB->insert(FirstMI, &*I);
4073       }
4074       Found = true;
4075       break;
4076     }
4077     assert(Found);
4078     (void)Found;
4079 
4080     // This should be before all vector instructions.
4081     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
4082     bool isWave32 = getSubtarget()->isWave32();
4083     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4084     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
4085         .addReg(InputReg)
4086         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
4087     BuildMI(*BB, FirstMI, DebugLoc(),
4088             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
4089             Exec)
4090         .addReg(CountReg)
4091         .addImm(0);
4092     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
4093         .addReg(CountReg, RegState::Kill)
4094         .addImm(getSubtarget()->getWavefrontSize());
4095     BuildMI(*BB, FirstMI, DebugLoc(),
4096             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
4097             Exec)
4098         .addImm(-1);
4099     MI.eraseFromParent();
4100     return BB;
4101   }
4102 
4103   case AMDGPU::GET_GROUPSTATICSIZE: {
4104     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4105            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4106     DebugLoc DL = MI.getDebugLoc();
4107     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4108         .add(MI.getOperand(0))
4109         .addImm(MFI->getLDSSize());
4110     MI.eraseFromParent();
4111     return BB;
4112   }
4113   case AMDGPU::SI_INDIRECT_SRC_V1:
4114   case AMDGPU::SI_INDIRECT_SRC_V2:
4115   case AMDGPU::SI_INDIRECT_SRC_V4:
4116   case AMDGPU::SI_INDIRECT_SRC_V8:
4117   case AMDGPU::SI_INDIRECT_SRC_V16:
4118   case AMDGPU::SI_INDIRECT_SRC_V32:
4119     return emitIndirectSrc(MI, *BB, *getSubtarget());
4120   case AMDGPU::SI_INDIRECT_DST_V1:
4121   case AMDGPU::SI_INDIRECT_DST_V2:
4122   case AMDGPU::SI_INDIRECT_DST_V4:
4123   case AMDGPU::SI_INDIRECT_DST_V8:
4124   case AMDGPU::SI_INDIRECT_DST_V16:
4125   case AMDGPU::SI_INDIRECT_DST_V32:
4126     return emitIndirectDst(MI, *BB, *getSubtarget());
4127   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4128   case AMDGPU::SI_KILL_I1_PSEUDO:
4129     return splitKillBlock(MI, BB);
4130   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4131     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4132     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4133     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4134 
4135     Register Dst = MI.getOperand(0).getReg();
4136     Register Src0 = MI.getOperand(1).getReg();
4137     Register Src1 = MI.getOperand(2).getReg();
4138     const DebugLoc &DL = MI.getDebugLoc();
4139     Register SrcCond = MI.getOperand(3).getReg();
4140 
4141     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4142     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4143     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4144     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4145 
4146     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4147       .addReg(SrcCond);
4148     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4149       .addImm(0)
4150       .addReg(Src0, 0, AMDGPU::sub0)
4151       .addImm(0)
4152       .addReg(Src1, 0, AMDGPU::sub0)
4153       .addReg(SrcCondCopy);
4154     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4155       .addImm(0)
4156       .addReg(Src0, 0, AMDGPU::sub1)
4157       .addImm(0)
4158       .addReg(Src1, 0, AMDGPU::sub1)
4159       .addReg(SrcCondCopy);
4160 
4161     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4162       .addReg(DstLo)
4163       .addImm(AMDGPU::sub0)
4164       .addReg(DstHi)
4165       .addImm(AMDGPU::sub1);
4166     MI.eraseFromParent();
4167     return BB;
4168   }
4169   case AMDGPU::SI_BR_UNDEF: {
4170     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4171     const DebugLoc &DL = MI.getDebugLoc();
4172     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4173                            .add(MI.getOperand(0));
4174     Br->getOperand(1).setIsUndef(true); // read undef SCC
4175     MI.eraseFromParent();
4176     return BB;
4177   }
4178   case AMDGPU::ADJCALLSTACKUP:
4179   case AMDGPU::ADJCALLSTACKDOWN: {
4180     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4181     MachineInstrBuilder MIB(*MF, &MI);
4182     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4183        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4184     return BB;
4185   }
4186   case AMDGPU::SI_CALL_ISEL: {
4187     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4188     const DebugLoc &DL = MI.getDebugLoc();
4189 
4190     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4191 
4192     MachineInstrBuilder MIB;
4193     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4194 
4195     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4196       MIB.add(MI.getOperand(I));
4197 
4198     MIB.cloneMemRefs(MI);
4199     MI.eraseFromParent();
4200     return BB;
4201   }
4202   case AMDGPU::V_ADD_CO_U32_e32:
4203   case AMDGPU::V_SUB_CO_U32_e32:
4204   case AMDGPU::V_SUBREV_CO_U32_e32: {
4205     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4206     const DebugLoc &DL = MI.getDebugLoc();
4207     unsigned Opc = MI.getOpcode();
4208 
4209     bool NeedClampOperand = false;
4210     if (TII->pseudoToMCOpcode(Opc) == -1) {
4211       Opc = AMDGPU::getVOPe64(Opc);
4212       NeedClampOperand = true;
4213     }
4214 
4215     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4216     if (TII->isVOP3(*I)) {
4217       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4218       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4219       I.addReg(TRI->getVCC(), RegState::Define);
4220     }
4221     I.add(MI.getOperand(1))
4222      .add(MI.getOperand(2));
4223     if (NeedClampOperand)
4224       I.addImm(0); // clamp bit for e64 encoding
4225 
4226     TII->legalizeOperands(*I);
4227 
4228     MI.eraseFromParent();
4229     return BB;
4230   }
4231   case AMDGPU::DS_GWS_INIT:
4232   case AMDGPU::DS_GWS_SEMA_V:
4233   case AMDGPU::DS_GWS_SEMA_BR:
4234   case AMDGPU::DS_GWS_SEMA_P:
4235   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4236   case AMDGPU::DS_GWS_BARRIER:
4237     // A s_waitcnt 0 is required to be the instruction immediately following.
4238     if (getSubtarget()->hasGWSAutoReplay()) {
4239       bundleInstWithWaitcnt(MI);
4240       return BB;
4241     }
4242 
4243     return emitGWSMemViolTestLoop(MI, BB);
4244   case AMDGPU::S_SETREG_B32: {
4245     // Try to optimize cases that only set the denormal mode or rounding mode.
4246     //
4247     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4248     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4249     // instead.
4250     //
4251     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4252     // allow you to have a no side effect instruction in the output of a
4253     // sideeffecting pattern.
4254     unsigned ID, Offset, Width;
4255     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4256     if (ID != AMDGPU::Hwreg::ID_MODE)
4257       return BB;
4258 
4259     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4260     const unsigned SetMask = WidthMask << Offset;
4261 
4262     if (getSubtarget()->hasDenormModeInst()) {
4263       unsigned SetDenormOp = 0;
4264       unsigned SetRoundOp = 0;
4265 
4266       // The dedicated instructions can only set the whole denorm or round mode
4267       // at once, not a subset of bits in either.
4268       if (SetMask ==
4269           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4270         // If this fully sets both the round and denorm mode, emit the two
4271         // dedicated instructions for these.
4272         SetRoundOp = AMDGPU::S_ROUND_MODE;
4273         SetDenormOp = AMDGPU::S_DENORM_MODE;
4274       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4275         SetRoundOp = AMDGPU::S_ROUND_MODE;
4276       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4277         SetDenormOp = AMDGPU::S_DENORM_MODE;
4278       }
4279 
4280       if (SetRoundOp || SetDenormOp) {
4281         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4282         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4283         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4284           unsigned ImmVal = Def->getOperand(1).getImm();
4285           if (SetRoundOp) {
4286             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4287                 .addImm(ImmVal & 0xf);
4288 
4289             // If we also have the denorm mode, get just the denorm mode bits.
4290             ImmVal >>= 4;
4291           }
4292 
4293           if (SetDenormOp) {
4294             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4295                 .addImm(ImmVal & 0xf);
4296           }
4297 
4298           MI.eraseFromParent();
4299           return BB;
4300         }
4301       }
4302     }
4303 
4304     // If only FP bits are touched, used the no side effects pseudo.
4305     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4306                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4307       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4308 
4309     return BB;
4310   }
4311   default:
4312     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4313   }
4314 }
4315 
4316 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4317   return isTypeLegal(VT.getScalarType());
4318 }
4319 
4320 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4321   // This currently forces unfolding various combinations of fsub into fma with
4322   // free fneg'd operands. As long as we have fast FMA (controlled by
4323   // isFMAFasterThanFMulAndFAdd), we should perform these.
4324 
4325   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4326   // most of these combines appear to be cycle neutral but save on instruction
4327   // count / code size.
4328   return true;
4329 }
4330 
4331 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4332                                          EVT VT) const {
4333   if (!VT.isVector()) {
4334     return MVT::i1;
4335   }
4336   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4337 }
4338 
4339 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4340   // TODO: Should i16 be used always if legal? For now it would force VALU
4341   // shifts.
4342   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4343 }
4344 
4345 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4346   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4347              ? Ty.changeElementSize(16)
4348              : Ty.changeElementSize(32);
4349 }
4350 
4351 // Answering this is somewhat tricky and depends on the specific device which
4352 // have different rates for fma or all f64 operations.
4353 //
4354 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4355 // regardless of which device (although the number of cycles differs between
4356 // devices), so it is always profitable for f64.
4357 //
4358 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4359 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4360 // which we can always do even without fused FP ops since it returns the same
4361 // result as the separate operations and since it is always full
4362 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4363 // however does not support denormals, so we do report fma as faster if we have
4364 // a fast fma device and require denormals.
4365 //
4366 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4367                                                   EVT VT) const {
4368   VT = VT.getScalarType();
4369 
4370   switch (VT.getSimpleVT().SimpleTy) {
4371   case MVT::f32: {
4372     // If mad is not available this depends only on if f32 fma is full rate.
4373     if (!Subtarget->hasMadMacF32Insts())
4374       return Subtarget->hasFastFMAF32();
4375 
4376     // Otherwise f32 mad is always full rate and returns the same result as
4377     // the separate operations so should be preferred over fma.
4378     // However does not support denomals.
4379     if (hasFP32Denormals(MF))
4380       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4381 
4382     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4383     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4384   }
4385   case MVT::f64:
4386     return true;
4387   case MVT::f16:
4388     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4389   default:
4390     break;
4391   }
4392 
4393   return false;
4394 }
4395 
4396 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4397                                    const SDNode *N) const {
4398   // TODO: Check future ftz flag
4399   // v_mad_f32/v_mac_f32 do not support denormals.
4400   EVT VT = N->getValueType(0);
4401   if (VT == MVT::f32)
4402     return Subtarget->hasMadMacF32Insts() &&
4403            !hasFP32Denormals(DAG.getMachineFunction());
4404   if (VT == MVT::f16) {
4405     return Subtarget->hasMadF16() &&
4406            !hasFP64FP16Denormals(DAG.getMachineFunction());
4407   }
4408 
4409   return false;
4410 }
4411 
4412 //===----------------------------------------------------------------------===//
4413 // Custom DAG Lowering Operations
4414 //===----------------------------------------------------------------------===//
4415 
4416 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4417 // wider vector type is legal.
4418 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4419                                              SelectionDAG &DAG) const {
4420   unsigned Opc = Op.getOpcode();
4421   EVT VT = Op.getValueType();
4422   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4423 
4424   SDValue Lo, Hi;
4425   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4426 
4427   SDLoc SL(Op);
4428   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4429                              Op->getFlags());
4430   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4431                              Op->getFlags());
4432 
4433   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4434 }
4435 
4436 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4437 // wider vector type is legal.
4438 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4439                                               SelectionDAG &DAG) const {
4440   unsigned Opc = Op.getOpcode();
4441   EVT VT = Op.getValueType();
4442   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4443 
4444   SDValue Lo0, Hi0;
4445   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4446   SDValue Lo1, Hi1;
4447   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4448 
4449   SDLoc SL(Op);
4450 
4451   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4452                              Op->getFlags());
4453   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4454                              Op->getFlags());
4455 
4456   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4457 }
4458 
4459 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4460                                               SelectionDAG &DAG) const {
4461   unsigned Opc = Op.getOpcode();
4462   EVT VT = Op.getValueType();
4463   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4464 
4465   SDValue Lo0, Hi0;
4466   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4467   SDValue Lo1, Hi1;
4468   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4469   SDValue Lo2, Hi2;
4470   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4471 
4472   SDLoc SL(Op);
4473 
4474   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4475                              Op->getFlags());
4476   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4477                              Op->getFlags());
4478 
4479   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4480 }
4481 
4482 
4483 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4484   switch (Op.getOpcode()) {
4485   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4486   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4487   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4488   case ISD::LOAD: {
4489     SDValue Result = LowerLOAD(Op, DAG);
4490     assert((!Result.getNode() ||
4491             Result.getNode()->getNumValues() == 2) &&
4492            "Load should return a value and a chain");
4493     return Result;
4494   }
4495 
4496   case ISD::FSIN:
4497   case ISD::FCOS:
4498     return LowerTrig(Op, DAG);
4499   case ISD::SELECT: return LowerSELECT(Op, DAG);
4500   case ISD::FDIV: return LowerFDIV(Op, DAG);
4501   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4502   case ISD::STORE: return LowerSTORE(Op, DAG);
4503   case ISD::GlobalAddress: {
4504     MachineFunction &MF = DAG.getMachineFunction();
4505     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4506     return LowerGlobalAddress(MFI, Op, DAG);
4507   }
4508   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4509   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4510   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4511   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4512   case ISD::INSERT_SUBVECTOR:
4513     return lowerINSERT_SUBVECTOR(Op, DAG);
4514   case ISD::INSERT_VECTOR_ELT:
4515     return lowerINSERT_VECTOR_ELT(Op, DAG);
4516   case ISD::EXTRACT_VECTOR_ELT:
4517     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4518   case ISD::VECTOR_SHUFFLE:
4519     return lowerVECTOR_SHUFFLE(Op, DAG);
4520   case ISD::BUILD_VECTOR:
4521     return lowerBUILD_VECTOR(Op, DAG);
4522   case ISD::FP_ROUND:
4523     return lowerFP_ROUND(Op, DAG);
4524   case ISD::TRAP:
4525     return lowerTRAP(Op, DAG);
4526   case ISD::DEBUGTRAP:
4527     return lowerDEBUGTRAP(Op, DAG);
4528   case ISD::FABS:
4529   case ISD::FNEG:
4530   case ISD::FCANONICALIZE:
4531   case ISD::BSWAP:
4532     return splitUnaryVectorOp(Op, DAG);
4533   case ISD::FMINNUM:
4534   case ISD::FMAXNUM:
4535     return lowerFMINNUM_FMAXNUM(Op, DAG);
4536   case ISD::FMA:
4537     return splitTernaryVectorOp(Op, DAG);
4538   case ISD::SHL:
4539   case ISD::SRA:
4540   case ISD::SRL:
4541   case ISD::ADD:
4542   case ISD::SUB:
4543   case ISD::MUL:
4544   case ISD::SMIN:
4545   case ISD::SMAX:
4546   case ISD::UMIN:
4547   case ISD::UMAX:
4548   case ISD::FADD:
4549   case ISD::FMUL:
4550   case ISD::FMINNUM_IEEE:
4551   case ISD::FMAXNUM_IEEE:
4552   case ISD::UADDSAT:
4553   case ISD::USUBSAT:
4554   case ISD::SADDSAT:
4555   case ISD::SSUBSAT:
4556     return splitBinaryVectorOp(Op, DAG);
4557   case ISD::SMULO:
4558   case ISD::UMULO:
4559     return lowerXMULO(Op, DAG);
4560   case ISD::DYNAMIC_STACKALLOC:
4561     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4562   }
4563   return SDValue();
4564 }
4565 
4566 // Used for D16: Casts the result of an instruction into the right vector,
4567 // packs values if loads return unpacked values.
4568 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4569                                        const SDLoc &DL,
4570                                        SelectionDAG &DAG, bool Unpacked) {
4571   if (!LoadVT.isVector())
4572     return Result;
4573 
4574   // Cast back to the original packed type or to a larger type that is a
4575   // multiple of 32 bit for D16. Widening the return type is a required for
4576   // legalization.
4577   EVT FittingLoadVT = LoadVT;
4578   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4579     FittingLoadVT =
4580         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4581                          LoadVT.getVectorNumElements() + 1);
4582   }
4583 
4584   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4585     // Truncate to v2i16/v4i16.
4586     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4587 
4588     // Workaround legalizer not scalarizing truncate after vector op
4589     // legalization but not creating intermediate vector trunc.
4590     SmallVector<SDValue, 4> Elts;
4591     DAG.ExtractVectorElements(Result, Elts);
4592     for (SDValue &Elt : Elts)
4593       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4594 
4595     // Pad illegal v1i16/v3fi6 to v4i16
4596     if ((LoadVT.getVectorNumElements() % 2) == 1)
4597       Elts.push_back(DAG.getUNDEF(MVT::i16));
4598 
4599     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4600 
4601     // Bitcast to original type (v2f16/v4f16).
4602     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4603   }
4604 
4605   // Cast back to the original packed type.
4606   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4607 }
4608 
4609 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4610                                               MemSDNode *M,
4611                                               SelectionDAG &DAG,
4612                                               ArrayRef<SDValue> Ops,
4613                                               bool IsIntrinsic) const {
4614   SDLoc DL(M);
4615 
4616   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4617   EVT LoadVT = M->getValueType(0);
4618 
4619   EVT EquivLoadVT = LoadVT;
4620   if (LoadVT.isVector()) {
4621     if (Unpacked) {
4622       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4623                                      LoadVT.getVectorNumElements());
4624     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4625       // Widen v3f16 to legal type
4626       EquivLoadVT =
4627           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4628                            LoadVT.getVectorNumElements() + 1);
4629     }
4630   }
4631 
4632   // Change from v4f16/v2f16 to EquivLoadVT.
4633   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4634 
4635   SDValue Load
4636     = DAG.getMemIntrinsicNode(
4637       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4638       VTList, Ops, M->getMemoryVT(),
4639       M->getMemOperand());
4640 
4641   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4642 
4643   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4644 }
4645 
4646 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4647                                              SelectionDAG &DAG,
4648                                              ArrayRef<SDValue> Ops) const {
4649   SDLoc DL(M);
4650   EVT LoadVT = M->getValueType(0);
4651   EVT EltType = LoadVT.getScalarType();
4652   EVT IntVT = LoadVT.changeTypeToInteger();
4653 
4654   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4655 
4656   unsigned Opc =
4657       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4658 
4659   if (IsD16) {
4660     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4661   }
4662 
4663   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4664   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4665     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4666 
4667   if (isTypeLegal(LoadVT)) {
4668     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4669                                M->getMemOperand(), DAG);
4670   }
4671 
4672   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4673   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4674   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4675                                         M->getMemOperand(), DAG);
4676   return DAG.getMergeValues(
4677       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4678       DL);
4679 }
4680 
4681 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4682                                   SDNode *N, SelectionDAG &DAG) {
4683   EVT VT = N->getValueType(0);
4684   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4685   unsigned CondCode = CD->getZExtValue();
4686   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4687     return DAG.getUNDEF(VT);
4688 
4689   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4690 
4691   SDValue LHS = N->getOperand(1);
4692   SDValue RHS = N->getOperand(2);
4693 
4694   SDLoc DL(N);
4695 
4696   EVT CmpVT = LHS.getValueType();
4697   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4698     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4699       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4700     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4701     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4702   }
4703 
4704   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4705 
4706   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4707   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4708 
4709   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4710                               DAG.getCondCode(CCOpcode));
4711   if (VT.bitsEq(CCVT))
4712     return SetCC;
4713   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4714 }
4715 
4716 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4717                                   SDNode *N, SelectionDAG &DAG) {
4718   EVT VT = N->getValueType(0);
4719   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4720 
4721   unsigned CondCode = CD->getZExtValue();
4722   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4723     return DAG.getUNDEF(VT);
4724 
4725   SDValue Src0 = N->getOperand(1);
4726   SDValue Src1 = N->getOperand(2);
4727   EVT CmpVT = Src0.getValueType();
4728   SDLoc SL(N);
4729 
4730   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4731     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4732     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4733   }
4734 
4735   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4736   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4737   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4738   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4739   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4740                               Src1, DAG.getCondCode(CCOpcode));
4741   if (VT.bitsEq(CCVT))
4742     return SetCC;
4743   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4744 }
4745 
4746 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4747                                     SelectionDAG &DAG) {
4748   EVT VT = N->getValueType(0);
4749   SDValue Src = N->getOperand(1);
4750   SDLoc SL(N);
4751 
4752   if (Src.getOpcode() == ISD::SETCC) {
4753     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4754     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4755                        Src.getOperand(1), Src.getOperand(2));
4756   }
4757   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4758     // (ballot 0) -> 0
4759     if (Arg->isNullValue())
4760       return DAG.getConstant(0, SL, VT);
4761 
4762     // (ballot 1) -> EXEC/EXEC_LO
4763     if (Arg->isOne()) {
4764       Register Exec;
4765       if (VT.getScalarSizeInBits() == 32)
4766         Exec = AMDGPU::EXEC_LO;
4767       else if (VT.getScalarSizeInBits() == 64)
4768         Exec = AMDGPU::EXEC;
4769       else
4770         return SDValue();
4771 
4772       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4773     }
4774   }
4775 
4776   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4777   // ISD::SETNE)
4778   return DAG.getNode(
4779       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4780       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4781 }
4782 
4783 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4784                                           SmallVectorImpl<SDValue> &Results,
4785                                           SelectionDAG &DAG) const {
4786   switch (N->getOpcode()) {
4787   case ISD::INSERT_VECTOR_ELT: {
4788     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4789       Results.push_back(Res);
4790     return;
4791   }
4792   case ISD::EXTRACT_VECTOR_ELT: {
4793     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4794       Results.push_back(Res);
4795     return;
4796   }
4797   case ISD::INTRINSIC_WO_CHAIN: {
4798     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4799     switch (IID) {
4800     case Intrinsic::amdgcn_cvt_pkrtz: {
4801       SDValue Src0 = N->getOperand(1);
4802       SDValue Src1 = N->getOperand(2);
4803       SDLoc SL(N);
4804       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4805                                 Src0, Src1);
4806       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4807       return;
4808     }
4809     case Intrinsic::amdgcn_cvt_pknorm_i16:
4810     case Intrinsic::amdgcn_cvt_pknorm_u16:
4811     case Intrinsic::amdgcn_cvt_pk_i16:
4812     case Intrinsic::amdgcn_cvt_pk_u16: {
4813       SDValue Src0 = N->getOperand(1);
4814       SDValue Src1 = N->getOperand(2);
4815       SDLoc SL(N);
4816       unsigned Opcode;
4817 
4818       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4819         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4820       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4821         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4822       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4823         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4824       else
4825         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4826 
4827       EVT VT = N->getValueType(0);
4828       if (isTypeLegal(VT))
4829         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4830       else {
4831         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4832         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4833       }
4834       return;
4835     }
4836     }
4837     break;
4838   }
4839   case ISD::INTRINSIC_W_CHAIN: {
4840     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4841       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4842         // FIXME: Hacky
4843         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4844           Results.push_back(Res.getOperand(I));
4845         }
4846       } else {
4847         Results.push_back(Res);
4848         Results.push_back(Res.getValue(1));
4849       }
4850       return;
4851     }
4852 
4853     break;
4854   }
4855   case ISD::SELECT: {
4856     SDLoc SL(N);
4857     EVT VT = N->getValueType(0);
4858     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4859     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4860     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4861 
4862     EVT SelectVT = NewVT;
4863     if (NewVT.bitsLT(MVT::i32)) {
4864       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4865       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4866       SelectVT = MVT::i32;
4867     }
4868 
4869     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4870                                     N->getOperand(0), LHS, RHS);
4871 
4872     if (NewVT != SelectVT)
4873       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4874     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4875     return;
4876   }
4877   case ISD::FNEG: {
4878     if (N->getValueType(0) != MVT::v2f16)
4879       break;
4880 
4881     SDLoc SL(N);
4882     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4883 
4884     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4885                              BC,
4886                              DAG.getConstant(0x80008000, SL, MVT::i32));
4887     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4888     return;
4889   }
4890   case ISD::FABS: {
4891     if (N->getValueType(0) != MVT::v2f16)
4892       break;
4893 
4894     SDLoc SL(N);
4895     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4896 
4897     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4898                              BC,
4899                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4900     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4901     return;
4902   }
4903   default:
4904     break;
4905   }
4906 }
4907 
4908 /// Helper function for LowerBRCOND
4909 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4910 
4911   SDNode *Parent = Value.getNode();
4912   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4913        I != E; ++I) {
4914 
4915     if (I.getUse().get() != Value)
4916       continue;
4917 
4918     if (I->getOpcode() == Opcode)
4919       return *I;
4920   }
4921   return nullptr;
4922 }
4923 
4924 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4925   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4926     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4927     case Intrinsic::amdgcn_if:
4928       return AMDGPUISD::IF;
4929     case Intrinsic::amdgcn_else:
4930       return AMDGPUISD::ELSE;
4931     case Intrinsic::amdgcn_loop:
4932       return AMDGPUISD::LOOP;
4933     case Intrinsic::amdgcn_end_cf:
4934       llvm_unreachable("should not occur");
4935     default:
4936       return 0;
4937     }
4938   }
4939 
4940   // break, if_break, else_break are all only used as inputs to loop, not
4941   // directly as branch conditions.
4942   return 0;
4943 }
4944 
4945 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4946   const Triple &TT = getTargetMachine().getTargetTriple();
4947   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4948           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4949          AMDGPU::shouldEmitConstantsToTextSection(TT);
4950 }
4951 
4952 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4953   // FIXME: Either avoid relying on address space here or change the default
4954   // address space for functions to avoid the explicit check.
4955   return (GV->getValueType()->isFunctionTy() ||
4956           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4957          !shouldEmitFixup(GV) &&
4958          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4959 }
4960 
4961 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4962   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4963 }
4964 
4965 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4966   if (!GV->hasExternalLinkage())
4967     return true;
4968 
4969   const auto OS = getTargetMachine().getTargetTriple().getOS();
4970   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4971 }
4972 
4973 /// This transforms the control flow intrinsics to get the branch destination as
4974 /// last parameter, also switches branch target with BR if the need arise
4975 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4976                                       SelectionDAG &DAG) const {
4977   SDLoc DL(BRCOND);
4978 
4979   SDNode *Intr = BRCOND.getOperand(1).getNode();
4980   SDValue Target = BRCOND.getOperand(2);
4981   SDNode *BR = nullptr;
4982   SDNode *SetCC = nullptr;
4983 
4984   if (Intr->getOpcode() == ISD::SETCC) {
4985     // As long as we negate the condition everything is fine
4986     SetCC = Intr;
4987     Intr = SetCC->getOperand(0).getNode();
4988 
4989   } else {
4990     // Get the target from BR if we don't negate the condition
4991     BR = findUser(BRCOND, ISD::BR);
4992     assert(BR && "brcond missing unconditional branch user");
4993     Target = BR->getOperand(1);
4994   }
4995 
4996   unsigned CFNode = isCFIntrinsic(Intr);
4997   if (CFNode == 0) {
4998     // This is a uniform branch so we don't need to legalize.
4999     return BRCOND;
5000   }
5001 
5002   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5003                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5004 
5005   assert(!SetCC ||
5006         (SetCC->getConstantOperandVal(1) == 1 &&
5007          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5008                                                              ISD::SETNE));
5009 
5010   // operands of the new intrinsic call
5011   SmallVector<SDValue, 4> Ops;
5012   if (HaveChain)
5013     Ops.push_back(BRCOND.getOperand(0));
5014 
5015   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5016   Ops.push_back(Target);
5017 
5018   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5019 
5020   // build the new intrinsic call
5021   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5022 
5023   if (!HaveChain) {
5024     SDValue Ops[] =  {
5025       SDValue(Result, 0),
5026       BRCOND.getOperand(0)
5027     };
5028 
5029     Result = DAG.getMergeValues(Ops, DL).getNode();
5030   }
5031 
5032   if (BR) {
5033     // Give the branch instruction our target
5034     SDValue Ops[] = {
5035       BR->getOperand(0),
5036       BRCOND.getOperand(2)
5037     };
5038     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5039     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5040   }
5041 
5042   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5043 
5044   // Copy the intrinsic results to registers
5045   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5046     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5047     if (!CopyToReg)
5048       continue;
5049 
5050     Chain = DAG.getCopyToReg(
5051       Chain, DL,
5052       CopyToReg->getOperand(1),
5053       SDValue(Result, i - 1),
5054       SDValue());
5055 
5056     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5057   }
5058 
5059   // Remove the old intrinsic from the chain
5060   DAG.ReplaceAllUsesOfValueWith(
5061     SDValue(Intr, Intr->getNumValues() - 1),
5062     Intr->getOperand(0));
5063 
5064   return Chain;
5065 }
5066 
5067 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5068                                           SelectionDAG &DAG) const {
5069   MVT VT = Op.getSimpleValueType();
5070   SDLoc DL(Op);
5071   // Checking the depth
5072   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5073     return DAG.getConstant(0, DL, VT);
5074 
5075   MachineFunction &MF = DAG.getMachineFunction();
5076   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5077   // Check for kernel and shader functions
5078   if (Info->isEntryFunction())
5079     return DAG.getConstant(0, DL, VT);
5080 
5081   MachineFrameInfo &MFI = MF.getFrameInfo();
5082   // There is a call to @llvm.returnaddress in this function
5083   MFI.setReturnAddressIsTaken(true);
5084 
5085   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5086   // Get the return address reg and mark it as an implicit live-in
5087   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5088 
5089   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5090 }
5091 
5092 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5093                                             SDValue Op,
5094                                             const SDLoc &DL,
5095                                             EVT VT) const {
5096   return Op.getValueType().bitsLE(VT) ?
5097       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5098     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5099                 DAG.getTargetConstant(0, DL, MVT::i32));
5100 }
5101 
5102 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5103   assert(Op.getValueType() == MVT::f16 &&
5104          "Do not know how to custom lower FP_ROUND for non-f16 type");
5105 
5106   SDValue Src = Op.getOperand(0);
5107   EVT SrcVT = Src.getValueType();
5108   if (SrcVT != MVT::f64)
5109     return Op;
5110 
5111   SDLoc DL(Op);
5112 
5113   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5114   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5115   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5116 }
5117 
5118 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5119                                                SelectionDAG &DAG) const {
5120   EVT VT = Op.getValueType();
5121   const MachineFunction &MF = DAG.getMachineFunction();
5122   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5123   bool IsIEEEMode = Info->getMode().IEEE;
5124 
5125   // FIXME: Assert during selection that this is only selected for
5126   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5127   // mode functions, but this happens to be OK since it's only done in cases
5128   // where there is known no sNaN.
5129   if (IsIEEEMode)
5130     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5131 
5132   if (VT == MVT::v4f16)
5133     return splitBinaryVectorOp(Op, DAG);
5134   return Op;
5135 }
5136 
5137 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5138   EVT VT = Op.getValueType();
5139   SDLoc SL(Op);
5140   SDValue LHS = Op.getOperand(0);
5141   SDValue RHS = Op.getOperand(1);
5142   bool isSigned = Op.getOpcode() == ISD::SMULO;
5143 
5144   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5145     const APInt &C = RHSC->getAPIntValue();
5146     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5147     if (C.isPowerOf2()) {
5148       // smulo(x, signed_min) is same as umulo(x, signed_min).
5149       bool UseArithShift = isSigned && !C.isMinSignedValue();
5150       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5151       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5152       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5153           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5154                       SL, VT, Result, ShiftAmt),
5155           LHS, ISD::SETNE);
5156       return DAG.getMergeValues({ Result, Overflow }, SL);
5157     }
5158   }
5159 
5160   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5161   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5162                             SL, VT, LHS, RHS);
5163 
5164   SDValue Sign = isSigned
5165     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5166                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5167     : DAG.getConstant(0, SL, VT);
5168   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5169 
5170   return DAG.getMergeValues({ Result, Overflow }, SL);
5171 }
5172 
5173 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5174   SDLoc SL(Op);
5175   SDValue Chain = Op.getOperand(0);
5176 
5177   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5178       !Subtarget->isTrapHandlerEnabled())
5179     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5180 
5181   MachineFunction &MF = DAG.getMachineFunction();
5182   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5183   Register UserSGPR = Info->getQueuePtrUserSGPR();
5184   assert(UserSGPR != AMDGPU::NoRegister);
5185   SDValue QueuePtr = CreateLiveInRegister(
5186     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5187   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5188   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5189                                    QueuePtr, SDValue());
5190   SDValue Ops[] = {
5191     ToReg,
5192     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5193     SGPR01,
5194     ToReg.getValue(1)
5195   };
5196   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5197 }
5198 
5199 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5200   SDLoc SL(Op);
5201   SDValue Chain = Op.getOperand(0);
5202   MachineFunction &MF = DAG.getMachineFunction();
5203 
5204   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5205       !Subtarget->isTrapHandlerEnabled()) {
5206     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5207                                      "debugtrap handler not supported",
5208                                      Op.getDebugLoc(),
5209                                      DS_Warning);
5210     LLVMContext &Ctx = MF.getFunction().getContext();
5211     Ctx.diagnose(NoTrap);
5212     return Chain;
5213   }
5214 
5215   SDValue Ops[] = {
5216     Chain,
5217     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5218   };
5219   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5220 }
5221 
5222 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5223                                              SelectionDAG &DAG) const {
5224   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5225   if (Subtarget->hasApertureRegs()) {
5226     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5227         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5228         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5229     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5230         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5231         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5232     unsigned Encoding =
5233         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5234         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5235         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5236 
5237     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5238     SDValue ApertureReg = SDValue(
5239         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5240     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5241     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5242   }
5243 
5244   MachineFunction &MF = DAG.getMachineFunction();
5245   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5246   Register UserSGPR = Info->getQueuePtrUserSGPR();
5247   assert(UserSGPR != AMDGPU::NoRegister);
5248 
5249   SDValue QueuePtr = CreateLiveInRegister(
5250     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5251 
5252   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5253   // private_segment_aperture_base_hi.
5254   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5255 
5256   SDValue Ptr =
5257       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5258 
5259   // TODO: Use custom target PseudoSourceValue.
5260   // TODO: We should use the value from the IR intrinsic call, but it might not
5261   // be available and how do we get it?
5262   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5263   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5264                      commonAlignment(Align(64), StructOffset),
5265                      MachineMemOperand::MODereferenceable |
5266                          MachineMemOperand::MOInvariant);
5267 }
5268 
5269 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5270                                              SelectionDAG &DAG) const {
5271   SDLoc SL(Op);
5272   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5273 
5274   SDValue Src = ASC->getOperand(0);
5275   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5276 
5277   const AMDGPUTargetMachine &TM =
5278     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5279 
5280   // flat -> local/private
5281   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5282     unsigned DestAS = ASC->getDestAddressSpace();
5283 
5284     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5285         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5286       unsigned NullVal = TM.getNullPointerValue(DestAS);
5287       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5288       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5289       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5290 
5291       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5292                          NonNull, Ptr, SegmentNullPtr);
5293     }
5294   }
5295 
5296   // local/private -> flat
5297   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5298     unsigned SrcAS = ASC->getSrcAddressSpace();
5299 
5300     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5301         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5302       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5303       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5304 
5305       SDValue NonNull
5306         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5307 
5308       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5309       SDValue CvtPtr
5310         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5311 
5312       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5313                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5314                          FlatNullPtr);
5315     }
5316   }
5317 
5318   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5319       Src.getValueType() == MVT::i64)
5320     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5321 
5322   // global <-> flat are no-ops and never emitted.
5323 
5324   const MachineFunction &MF = DAG.getMachineFunction();
5325   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5326     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5327   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5328 
5329   return DAG.getUNDEF(ASC->getValueType(0));
5330 }
5331 
5332 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5333 // the small vector and inserting them into the big vector. That is better than
5334 // the default expansion of doing it via a stack slot. Even though the use of
5335 // the stack slot would be optimized away afterwards, the stack slot itself
5336 // remains.
5337 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5338                                                 SelectionDAG &DAG) const {
5339   SDValue Vec = Op.getOperand(0);
5340   SDValue Ins = Op.getOperand(1);
5341   SDValue Idx = Op.getOperand(2);
5342   EVT VecVT = Vec.getValueType();
5343   EVT InsVT = Ins.getValueType();
5344   EVT EltVT = VecVT.getVectorElementType();
5345   unsigned InsNumElts = InsVT.getVectorNumElements();
5346   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5347   SDLoc SL(Op);
5348 
5349   for (unsigned I = 0; I != InsNumElts; ++I) {
5350     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5351                               DAG.getConstant(I, SL, MVT::i32));
5352     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5353                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5354   }
5355   return Vec;
5356 }
5357 
5358 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5359                                                  SelectionDAG &DAG) const {
5360   SDValue Vec = Op.getOperand(0);
5361   SDValue InsVal = Op.getOperand(1);
5362   SDValue Idx = Op.getOperand(2);
5363   EVT VecVT = Vec.getValueType();
5364   EVT EltVT = VecVT.getVectorElementType();
5365   unsigned VecSize = VecVT.getSizeInBits();
5366   unsigned EltSize = EltVT.getSizeInBits();
5367 
5368 
5369   assert(VecSize <= 64);
5370 
5371   unsigned NumElts = VecVT.getVectorNumElements();
5372   SDLoc SL(Op);
5373   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5374 
5375   if (NumElts == 4 && EltSize == 16 && KIdx) {
5376     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5377 
5378     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5379                                  DAG.getConstant(0, SL, MVT::i32));
5380     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5381                                  DAG.getConstant(1, SL, MVT::i32));
5382 
5383     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5384     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5385 
5386     unsigned Idx = KIdx->getZExtValue();
5387     bool InsertLo = Idx < 2;
5388     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5389       InsertLo ? LoVec : HiVec,
5390       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5391       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5392 
5393     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5394 
5395     SDValue Concat = InsertLo ?
5396       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5397       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5398 
5399     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5400   }
5401 
5402   if (isa<ConstantSDNode>(Idx))
5403     return SDValue();
5404 
5405   MVT IntVT = MVT::getIntegerVT(VecSize);
5406 
5407   // Avoid stack access for dynamic indexing.
5408   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5409 
5410   // Create a congruent vector with the target value in each element so that
5411   // the required element can be masked and ORed into the target vector.
5412   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5413                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5414 
5415   assert(isPowerOf2_32(EltSize));
5416   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5417 
5418   // Convert vector index to bit-index.
5419   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5420 
5421   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5422   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5423                             DAG.getConstant(0xffff, SL, IntVT),
5424                             ScaledIdx);
5425 
5426   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5427   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5428                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5429 
5430   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5431   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5432 }
5433 
5434 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5435                                                   SelectionDAG &DAG) const {
5436   SDLoc SL(Op);
5437 
5438   EVT ResultVT = Op.getValueType();
5439   SDValue Vec = Op.getOperand(0);
5440   SDValue Idx = Op.getOperand(1);
5441   EVT VecVT = Vec.getValueType();
5442   unsigned VecSize = VecVT.getSizeInBits();
5443   EVT EltVT = VecVT.getVectorElementType();
5444   assert(VecSize <= 64);
5445 
5446   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5447 
5448   // Make sure we do any optimizations that will make it easier to fold
5449   // source modifiers before obscuring it with bit operations.
5450 
5451   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5452   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5453     return Combined;
5454 
5455   unsigned EltSize = EltVT.getSizeInBits();
5456   assert(isPowerOf2_32(EltSize));
5457 
5458   MVT IntVT = MVT::getIntegerVT(VecSize);
5459   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5460 
5461   // Convert vector index to bit-index (* EltSize)
5462   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5463 
5464   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5465   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5466 
5467   if (ResultVT == MVT::f16) {
5468     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5469     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5470   }
5471 
5472   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5473 }
5474 
5475 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5476   assert(Elt % 2 == 0);
5477   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5478 }
5479 
5480 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5481                                               SelectionDAG &DAG) const {
5482   SDLoc SL(Op);
5483   EVT ResultVT = Op.getValueType();
5484   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5485 
5486   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5487   EVT EltVT = PackVT.getVectorElementType();
5488   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5489 
5490   // vector_shuffle <0,1,6,7> lhs, rhs
5491   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5492   //
5493   // vector_shuffle <6,7,2,3> lhs, rhs
5494   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5495   //
5496   // vector_shuffle <6,7,0,1> lhs, rhs
5497   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5498 
5499   // Avoid scalarizing when both halves are reading from consecutive elements.
5500   SmallVector<SDValue, 4> Pieces;
5501   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5502     if (elementPairIsContiguous(SVN->getMask(), I)) {
5503       const int Idx = SVN->getMaskElt(I);
5504       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5505       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5506       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5507                                     PackVT, SVN->getOperand(VecIdx),
5508                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5509       Pieces.push_back(SubVec);
5510     } else {
5511       const int Idx0 = SVN->getMaskElt(I);
5512       const int Idx1 = SVN->getMaskElt(I + 1);
5513       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5514       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5515       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5516       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5517 
5518       SDValue Vec0 = SVN->getOperand(VecIdx0);
5519       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5520                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5521 
5522       SDValue Vec1 = SVN->getOperand(VecIdx1);
5523       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5524                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5525       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5526     }
5527   }
5528 
5529   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5530 }
5531 
5532 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5533                                             SelectionDAG &DAG) const {
5534   SDLoc SL(Op);
5535   EVT VT = Op.getValueType();
5536 
5537   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5538     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5539 
5540     // Turn into pair of packed build_vectors.
5541     // TODO: Special case for constants that can be materialized with s_mov_b64.
5542     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5543                                     { Op.getOperand(0), Op.getOperand(1) });
5544     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5545                                     { Op.getOperand(2), Op.getOperand(3) });
5546 
5547     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5548     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5549 
5550     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5551     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5552   }
5553 
5554   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5555   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5556 
5557   SDValue Lo = Op.getOperand(0);
5558   SDValue Hi = Op.getOperand(1);
5559 
5560   // Avoid adding defined bits with the zero_extend.
5561   if (Hi.isUndef()) {
5562     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5563     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5564     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5565   }
5566 
5567   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5568   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5569 
5570   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5571                               DAG.getConstant(16, SL, MVT::i32));
5572   if (Lo.isUndef())
5573     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5574 
5575   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5576   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5577 
5578   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5579   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5580 }
5581 
5582 bool
5583 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5584   // We can fold offsets for anything that doesn't require a GOT relocation.
5585   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5586           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5587           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5588          !shouldEmitGOTReloc(GA->getGlobal());
5589 }
5590 
5591 static SDValue
5592 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5593                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5594                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5595   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5596   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5597   // lowered to the following code sequence:
5598   //
5599   // For constant address space:
5600   //   s_getpc_b64 s[0:1]
5601   //   s_add_u32 s0, s0, $symbol
5602   //   s_addc_u32 s1, s1, 0
5603   //
5604   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5605   //   a fixup or relocation is emitted to replace $symbol with a literal
5606   //   constant, which is a pc-relative offset from the encoding of the $symbol
5607   //   operand to the global variable.
5608   //
5609   // For global address space:
5610   //   s_getpc_b64 s[0:1]
5611   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5612   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5613   //
5614   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5615   //   fixups or relocations are emitted to replace $symbol@*@lo and
5616   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5617   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5618   //   operand to the global variable.
5619   //
5620   // What we want here is an offset from the value returned by s_getpc
5621   // (which is the address of the s_add_u32 instruction) to the global
5622   // variable, but since the encoding of $symbol starts 4 bytes after the start
5623   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5624   // small. This requires us to add 4 to the global variable offset in order to
5625   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5626   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5627   // instruction.
5628   SDValue PtrLo =
5629       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5630   SDValue PtrHi;
5631   if (GAFlags == SIInstrInfo::MO_NONE) {
5632     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5633   } else {
5634     PtrHi =
5635         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5636   }
5637   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5638 }
5639 
5640 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5641                                              SDValue Op,
5642                                              SelectionDAG &DAG) const {
5643   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5644   SDLoc DL(GSD);
5645   EVT PtrVT = Op.getValueType();
5646 
5647   const GlobalValue *GV = GSD->getGlobal();
5648   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5649        shouldUseLDSConstAddress(GV)) ||
5650       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5651       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5652     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5653         GV->hasExternalLinkage()) {
5654       Type *Ty = GV->getValueType();
5655       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5656       // zero-sized type in other languages to declare the dynamic shared
5657       // memory which size is not known at the compile time. They will be
5658       // allocated by the runtime and placed directly after the static
5659       // allocated ones. They all share the same offset.
5660       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5661         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5662         // Adjust alignment for that dynamic shared memory array.
5663         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5664         return SDValue(
5665             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5666       }
5667     }
5668     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5669   }
5670 
5671   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5672     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5673                                             SIInstrInfo::MO_ABS32_LO);
5674     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5675   }
5676 
5677   if (shouldEmitFixup(GV))
5678     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5679   else if (shouldEmitPCReloc(GV))
5680     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5681                                    SIInstrInfo::MO_REL32);
5682 
5683   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5684                                             SIInstrInfo::MO_GOTPCREL32);
5685 
5686   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5687   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5688   const DataLayout &DataLayout = DAG.getDataLayout();
5689   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5690   MachinePointerInfo PtrInfo
5691     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5692 
5693   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5694                      MachineMemOperand::MODereferenceable |
5695                          MachineMemOperand::MOInvariant);
5696 }
5697 
5698 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5699                                    const SDLoc &DL, SDValue V) const {
5700   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5701   // the destination register.
5702   //
5703   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5704   // so we will end up with redundant moves to m0.
5705   //
5706   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5707 
5708   // A Null SDValue creates a glue result.
5709   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5710                                   V, Chain);
5711   return SDValue(M0, 0);
5712 }
5713 
5714 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5715                                                  SDValue Op,
5716                                                  MVT VT,
5717                                                  unsigned Offset) const {
5718   SDLoc SL(Op);
5719   SDValue Param = lowerKernargMemParameter(
5720       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5721   // The local size values will have the hi 16-bits as zero.
5722   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5723                      DAG.getValueType(VT));
5724 }
5725 
5726 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5727                                         EVT VT) {
5728   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5729                                       "non-hsa intrinsic with hsa target",
5730                                       DL.getDebugLoc());
5731   DAG.getContext()->diagnose(BadIntrin);
5732   return DAG.getUNDEF(VT);
5733 }
5734 
5735 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5736                                          EVT VT) {
5737   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5738                                       "intrinsic not supported on subtarget",
5739                                       DL.getDebugLoc());
5740   DAG.getContext()->diagnose(BadIntrin);
5741   return DAG.getUNDEF(VT);
5742 }
5743 
5744 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5745                                     ArrayRef<SDValue> Elts) {
5746   assert(!Elts.empty());
5747   MVT Type;
5748   unsigned NumElts;
5749 
5750   if (Elts.size() == 1) {
5751     Type = MVT::f32;
5752     NumElts = 1;
5753   } else if (Elts.size() == 2) {
5754     Type = MVT::v2f32;
5755     NumElts = 2;
5756   } else if (Elts.size() == 3) {
5757     Type = MVT::v3f32;
5758     NumElts = 3;
5759   } else if (Elts.size() <= 4) {
5760     Type = MVT::v4f32;
5761     NumElts = 4;
5762   } else if (Elts.size() <= 8) {
5763     Type = MVT::v8f32;
5764     NumElts = 8;
5765   } else {
5766     assert(Elts.size() <= 16);
5767     Type = MVT::v16f32;
5768     NumElts = 16;
5769   }
5770 
5771   SmallVector<SDValue, 16> VecElts(NumElts);
5772   for (unsigned i = 0; i < Elts.size(); ++i) {
5773     SDValue Elt = Elts[i];
5774     if (Elt.getValueType() != MVT::f32)
5775       Elt = DAG.getBitcast(MVT::f32, Elt);
5776     VecElts[i] = Elt;
5777   }
5778   for (unsigned i = Elts.size(); i < NumElts; ++i)
5779     VecElts[i] = DAG.getUNDEF(MVT::f32);
5780 
5781   if (NumElts == 1)
5782     return VecElts[0];
5783   return DAG.getBuildVector(Type, DL, VecElts);
5784 }
5785 
5786 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5787                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5788   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5789 
5790   uint64_t Value = CachePolicyConst->getZExtValue();
5791   SDLoc DL(CachePolicy);
5792   if (GLC) {
5793     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5794     Value &= ~(uint64_t)0x1;
5795   }
5796   if (SLC) {
5797     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5798     Value &= ~(uint64_t)0x2;
5799   }
5800   if (DLC) {
5801     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5802     Value &= ~(uint64_t)0x4;
5803   }
5804 
5805   return Value == 0;
5806 }
5807 
5808 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5809                               SDValue Src, int ExtraElts) {
5810   EVT SrcVT = Src.getValueType();
5811 
5812   SmallVector<SDValue, 8> Elts;
5813 
5814   if (SrcVT.isVector())
5815     DAG.ExtractVectorElements(Src, Elts);
5816   else
5817     Elts.push_back(Src);
5818 
5819   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5820   while (ExtraElts--)
5821     Elts.push_back(Undef);
5822 
5823   return DAG.getBuildVector(CastVT, DL, Elts);
5824 }
5825 
5826 // Re-construct the required return value for a image load intrinsic.
5827 // This is more complicated due to the optional use TexFailCtrl which means the required
5828 // return type is an aggregate
5829 static SDValue constructRetValue(SelectionDAG &DAG,
5830                                  MachineSDNode *Result,
5831                                  ArrayRef<EVT> ResultTypes,
5832                                  bool IsTexFail, bool Unpacked, bool IsD16,
5833                                  int DMaskPop, int NumVDataDwords,
5834                                  const SDLoc &DL, LLVMContext &Context) {
5835   // Determine the required return type. This is the same regardless of IsTexFail flag
5836   EVT ReqRetVT = ResultTypes[0];
5837   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5838   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5839     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5840 
5841   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5842     DMaskPop : (DMaskPop + 1) / 2;
5843 
5844   MVT DataDwordVT = NumDataDwords == 1 ?
5845     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5846 
5847   MVT MaskPopVT = MaskPopDwords == 1 ?
5848     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5849 
5850   SDValue Data(Result, 0);
5851   SDValue TexFail;
5852 
5853   if (IsTexFail) {
5854     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5855     if (MaskPopVT.isVector()) {
5856       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5857                          SDValue(Result, 0), ZeroIdx);
5858     } else {
5859       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5860                          SDValue(Result, 0), ZeroIdx);
5861     }
5862 
5863     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5864                           SDValue(Result, 0),
5865                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5866   }
5867 
5868   if (DataDwordVT.isVector())
5869     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5870                           NumDataDwords - MaskPopDwords);
5871 
5872   if (IsD16)
5873     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5874 
5875   EVT LegalReqRetVT = ReqRetVT;
5876   if (!ReqRetVT.isVector()) {
5877     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5878   } else {
5879     // We need to widen the return vector to a legal type
5880     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5881         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5882       LegalReqRetVT =
5883           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5884                            ReqRetVT.getVectorNumElements() + 1);
5885     }
5886   }
5887   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5888 
5889   if (TexFail)
5890     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5891 
5892   if (Result->getNumValues() == 1)
5893     return Data;
5894 
5895   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5896 }
5897 
5898 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5899                          SDValue *LWE, bool &IsTexFail) {
5900   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5901 
5902   uint64_t Value = TexFailCtrlConst->getZExtValue();
5903   if (Value) {
5904     IsTexFail = true;
5905   }
5906 
5907   SDLoc DL(TexFailCtrlConst);
5908   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5909   Value &= ~(uint64_t)0x1;
5910   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5911   Value &= ~(uint64_t)0x2;
5912 
5913   return Value == 0;
5914 }
5915 
5916 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5917                                         MVT PackVectorVT,
5918                                         SmallVectorImpl<SDValue> &PackedAddrs,
5919                                         unsigned DimIdx, unsigned EndIdx,
5920                                         unsigned NumGradients) {
5921   SDLoc DL(Op);
5922   for (unsigned I = DimIdx; I < EndIdx; I++) {
5923     SDValue Addr = Op.getOperand(I);
5924 
5925     // Gradients are packed with undef for each coordinate.
5926     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5927     // 1D: undef,dx/dh; undef,dx/dv
5928     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5929     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5930     if (((I + 1) >= EndIdx) ||
5931         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5932                                          I == DimIdx + NumGradients - 1))) {
5933       if (Addr.getValueType() != MVT::i16)
5934         Addr = DAG.getBitcast(MVT::i16, Addr);
5935       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5936     } else {
5937       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5938       I++;
5939     }
5940     Addr = DAG.getBitcast(MVT::f32, Addr);
5941     PackedAddrs.push_back(Addr);
5942   }
5943 }
5944 
5945 SDValue SITargetLowering::lowerImage(SDValue Op,
5946                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5947                                      SelectionDAG &DAG) const {
5948   SDLoc DL(Op);
5949   MachineFunction &MF = DAG.getMachineFunction();
5950   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5951   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5952       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5953   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5954   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5955       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5956   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5957       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5958   unsigned IntrOpcode = Intr->BaseOpcode;
5959   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5960 
5961   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5962   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5963   bool IsD16 = false;
5964   bool IsG16 = false;
5965   bool IsA16 = false;
5966   SDValue VData;
5967   int NumVDataDwords;
5968   bool AdjustRetType = false;
5969 
5970   unsigned AddrIdx; // Index of first address argument
5971   unsigned DMask;
5972   unsigned DMaskLanes = 0;
5973 
5974   if (BaseOpcode->Atomic) {
5975     VData = Op.getOperand(2);
5976 
5977     bool Is64Bit = VData.getValueType() == MVT::i64;
5978     if (BaseOpcode->AtomicX2) {
5979       SDValue VData2 = Op.getOperand(3);
5980       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5981                                  {VData, VData2});
5982       if (Is64Bit)
5983         VData = DAG.getBitcast(MVT::v4i32, VData);
5984 
5985       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5986       DMask = Is64Bit ? 0xf : 0x3;
5987       NumVDataDwords = Is64Bit ? 4 : 2;
5988       AddrIdx = 4;
5989     } else {
5990       DMask = Is64Bit ? 0x3 : 0x1;
5991       NumVDataDwords = Is64Bit ? 2 : 1;
5992       AddrIdx = 3;
5993     }
5994   } else {
5995     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5996     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5997     DMask = DMaskConst->getZExtValue();
5998     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5999 
6000     if (BaseOpcode->Store) {
6001       VData = Op.getOperand(2);
6002 
6003       MVT StoreVT = VData.getSimpleValueType();
6004       if (StoreVT.getScalarType() == MVT::f16) {
6005         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6006           return Op; // D16 is unsupported for this instruction
6007 
6008         IsD16 = true;
6009         VData = handleD16VData(VData, DAG);
6010       }
6011 
6012       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6013     } else {
6014       // Work out the num dwords based on the dmask popcount and underlying type
6015       // and whether packing is supported.
6016       MVT LoadVT = ResultTypes[0].getSimpleVT();
6017       if (LoadVT.getScalarType() == MVT::f16) {
6018         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6019           return Op; // D16 is unsupported for this instruction
6020 
6021         IsD16 = true;
6022       }
6023 
6024       // Confirm that the return type is large enough for the dmask specified
6025       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6026           (!LoadVT.isVector() && DMaskLanes > 1))
6027           return Op;
6028 
6029       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
6030         NumVDataDwords = (DMaskLanes + 1) / 2;
6031       else
6032         NumVDataDwords = DMaskLanes;
6033 
6034       AdjustRetType = true;
6035     }
6036 
6037     AddrIdx = DMaskIdx + 1;
6038   }
6039 
6040   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
6041   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
6042   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
6043   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
6044                        NumCoords + NumLCM;
6045   unsigned NumMIVAddrs = NumVAddrs;
6046 
6047   SmallVector<SDValue, 4> VAddrs;
6048 
6049   // Optimize _L to _LZ when _L is zero
6050   if (LZMappingInfo) {
6051     if (auto ConstantLod =
6052          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
6053       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6054         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6055         NumMIVAddrs--;               // remove 'lod'
6056       }
6057     }
6058   }
6059 
6060   // Optimize _mip away, when 'lod' is zero
6061   if (MIPMappingInfo) {
6062     if (auto ConstantLod =
6063          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
6064       if (ConstantLod->isNullValue()) {
6065         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6066         NumMIVAddrs--;               // remove 'lod'
6067       }
6068     }
6069   }
6070 
6071   // Push back extra arguments.
6072   for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++)
6073     VAddrs.push_back(Op.getOperand(AddrIdx + I));
6074 
6075   // Check for 16 bit addresses or derivatives and pack if true.
6076   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
6077   unsigned CoordIdx = DimIdx + NumGradients;
6078   unsigned CoordsEnd = AddrIdx + NumMIVAddrs;
6079 
6080   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
6081   MVT VAddrScalarVT = VAddrVT.getScalarType();
6082   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6083   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6084 
6085   VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType();
6086   VAddrScalarVT = VAddrVT.getScalarType();
6087   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6088   if (IsA16 || IsG16) {
6089     if (IsA16) {
6090       if (!ST->hasA16()) {
6091         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6092                              "support 16 bit addresses\n");
6093         return Op;
6094       }
6095       if (!IsG16) {
6096         LLVM_DEBUG(
6097             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6098                       "need 16 bit derivatives but got 32 bit derivatives\n");
6099         return Op;
6100       }
6101     } else if (!ST->hasG16()) {
6102       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6103                            "support 16 bit derivatives\n");
6104       return Op;
6105     }
6106 
6107     if (BaseOpcode->Gradients && !IsA16) {
6108       if (!ST->hasG16()) {
6109         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6110                              "support 16 bit derivatives\n");
6111         return Op;
6112       }
6113       // Activate g16
6114       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6115           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6116       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6117     }
6118 
6119     // Don't compress addresses for G16
6120     const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx;
6121     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx,
6122                                 PackEndIdx, NumGradients);
6123 
6124     if (!IsA16) {
6125       // Add uncompressed address
6126       for (unsigned I = CoordIdx; I < CoordsEnd; I++)
6127         VAddrs.push_back(Op.getOperand(I));
6128     }
6129   } else {
6130     for (unsigned I = DimIdx; I < CoordsEnd; I++)
6131       VAddrs.push_back(Op.getOperand(I));
6132   }
6133 
6134   // If the register allocator cannot place the address registers contiguously
6135   // without introducing moves, then using the non-sequential address encoding
6136   // is always preferable, since it saves VALU instructions and is usually a
6137   // wash in terms of code size or even better.
6138   //
6139   // However, we currently have no way of hinting to the register allocator that
6140   // MIMG addresses should be placed contiguously when it is possible to do so,
6141   // so force non-NSA for the common 2-address case as a heuristic.
6142   //
6143   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6144   // allocation when possible.
6145   bool UseNSA =
6146       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6147   SDValue VAddr;
6148   if (!UseNSA)
6149     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6150 
6151   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6152   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6153   unsigned CtrlIdx; // Index of texfailctrl argument
6154   SDValue Unorm;
6155   if (!BaseOpcode->Sampler) {
6156     Unorm = True;
6157     CtrlIdx = AddrIdx + NumVAddrs + 1;
6158   } else {
6159     auto UnormConst =
6160         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
6161 
6162     Unorm = UnormConst->getZExtValue() ? True : False;
6163     CtrlIdx = AddrIdx + NumVAddrs + 3;
6164   }
6165 
6166   SDValue TFE;
6167   SDValue LWE;
6168   SDValue TexFail = Op.getOperand(CtrlIdx);
6169   bool IsTexFail = false;
6170   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6171     return Op;
6172 
6173   if (IsTexFail) {
6174     if (!DMaskLanes) {
6175       // Expecting to get an error flag since TFC is on - and dmask is 0
6176       // Force dmask to be at least 1 otherwise the instruction will fail
6177       DMask = 0x1;
6178       DMaskLanes = 1;
6179       NumVDataDwords = 1;
6180     }
6181     NumVDataDwords += 1;
6182     AdjustRetType = true;
6183   }
6184 
6185   // Has something earlier tagged that the return type needs adjusting
6186   // This happens if the instruction is a load or has set TexFailCtrl flags
6187   if (AdjustRetType) {
6188     // NumVDataDwords reflects the true number of dwords required in the return type
6189     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6190       // This is a no-op load. This can be eliminated
6191       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6192       if (isa<MemSDNode>(Op))
6193         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6194       return Undef;
6195     }
6196 
6197     EVT NewVT = NumVDataDwords > 1 ?
6198                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6199                 : MVT::i32;
6200 
6201     ResultTypes[0] = NewVT;
6202     if (ResultTypes.size() == 3) {
6203       // Original result was aggregate type used for TexFailCtrl results
6204       // The actual instruction returns as a vector type which has now been
6205       // created. Remove the aggregate result.
6206       ResultTypes.erase(&ResultTypes[1]);
6207     }
6208   }
6209 
6210   SDValue GLC;
6211   SDValue SLC;
6212   SDValue DLC;
6213   if (BaseOpcode->Atomic) {
6214     GLC = True; // TODO no-return optimization
6215     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
6216                           IsGFX10 ? &DLC : nullptr))
6217       return Op;
6218   } else {
6219     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
6220                           IsGFX10 ? &DLC : nullptr))
6221       return Op;
6222   }
6223 
6224   SmallVector<SDValue, 26> Ops;
6225   if (BaseOpcode->Store || BaseOpcode->Atomic)
6226     Ops.push_back(VData); // vdata
6227   if (UseNSA) {
6228     for (const SDValue &Addr : VAddrs)
6229       Ops.push_back(Addr);
6230   } else {
6231     Ops.push_back(VAddr);
6232   }
6233   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
6234   if (BaseOpcode->Sampler)
6235     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
6236   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6237   if (IsGFX10)
6238     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6239   Ops.push_back(Unorm);
6240   if (IsGFX10)
6241     Ops.push_back(DLC);
6242   Ops.push_back(GLC);
6243   Ops.push_back(SLC);
6244   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6245                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6246   if (IsGFX10)
6247     Ops.push_back(IsA16 ? True : False);
6248   Ops.push_back(TFE);
6249   Ops.push_back(LWE);
6250   if (!IsGFX10)
6251     Ops.push_back(DimInfo->DA ? True : False);
6252   if (BaseOpcode->HasD16)
6253     Ops.push_back(IsD16 ? True : False);
6254   if (isa<MemSDNode>(Op))
6255     Ops.push_back(Op.getOperand(0)); // chain
6256 
6257   int NumVAddrDwords =
6258       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6259   int Opcode = -1;
6260 
6261   if (IsGFX10) {
6262     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6263                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6264                                           : AMDGPU::MIMGEncGfx10Default,
6265                                    NumVDataDwords, NumVAddrDwords);
6266   } else {
6267     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6268       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6269                                      NumVDataDwords, NumVAddrDwords);
6270     if (Opcode == -1)
6271       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6272                                      NumVDataDwords, NumVAddrDwords);
6273   }
6274   assert(Opcode != -1);
6275 
6276   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6277   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6278     MachineMemOperand *MemRef = MemOp->getMemOperand();
6279     DAG.setNodeMemRefs(NewNode, {MemRef});
6280   }
6281 
6282   if (BaseOpcode->AtomicX2) {
6283     SmallVector<SDValue, 1> Elt;
6284     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6285     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6286   } else if (!BaseOpcode->Store) {
6287     return constructRetValue(DAG, NewNode,
6288                              OrigResultTypes, IsTexFail,
6289                              Subtarget->hasUnpackedD16VMem(), IsD16,
6290                              DMaskLanes, NumVDataDwords, DL,
6291                              *DAG.getContext());
6292   }
6293 
6294   return SDValue(NewNode, 0);
6295 }
6296 
6297 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6298                                        SDValue Offset, SDValue CachePolicy,
6299                                        SelectionDAG &DAG) const {
6300   MachineFunction &MF = DAG.getMachineFunction();
6301 
6302   const DataLayout &DataLayout = DAG.getDataLayout();
6303   Align Alignment =
6304       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6305 
6306   MachineMemOperand *MMO = MF.getMachineMemOperand(
6307       MachinePointerInfo(),
6308       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6309           MachineMemOperand::MOInvariant,
6310       VT.getStoreSize(), Alignment);
6311 
6312   if (!Offset->isDivergent()) {
6313     SDValue Ops[] = {
6314         Rsrc,
6315         Offset, // Offset
6316         CachePolicy
6317     };
6318 
6319     // Widen vec3 load to vec4.
6320     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6321       EVT WidenedVT =
6322           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6323       auto WidenedOp = DAG.getMemIntrinsicNode(
6324           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6325           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6326       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6327                                    DAG.getVectorIdxConstant(0, DL));
6328       return Subvector;
6329     }
6330 
6331     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6332                                    DAG.getVTList(VT), Ops, VT, MMO);
6333   }
6334 
6335   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6336   // assume that the buffer is unswizzled.
6337   SmallVector<SDValue, 4> Loads;
6338   unsigned NumLoads = 1;
6339   MVT LoadVT = VT.getSimpleVT();
6340   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6341   assert((LoadVT.getScalarType() == MVT::i32 ||
6342           LoadVT.getScalarType() == MVT::f32));
6343 
6344   if (NumElts == 8 || NumElts == 16) {
6345     NumLoads = NumElts / 4;
6346     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6347   }
6348 
6349   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6350   SDValue Ops[] = {
6351       DAG.getEntryNode(),                               // Chain
6352       Rsrc,                                             // rsrc
6353       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6354       {},                                               // voffset
6355       {},                                               // soffset
6356       {},                                               // offset
6357       CachePolicy,                                      // cachepolicy
6358       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6359   };
6360 
6361   // Use the alignment to ensure that the required offsets will fit into the
6362   // immediate offsets.
6363   setBufferOffsets(Offset, DAG, &Ops[3],
6364                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6365 
6366   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6367   for (unsigned i = 0; i < NumLoads; ++i) {
6368     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6369     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6370                                         LoadVT, MMO, DAG));
6371   }
6372 
6373   if (NumElts == 8 || NumElts == 16)
6374     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6375 
6376   return Loads[0];
6377 }
6378 
6379 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6380                                                   SelectionDAG &DAG) const {
6381   MachineFunction &MF = DAG.getMachineFunction();
6382   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6383 
6384   EVT VT = Op.getValueType();
6385   SDLoc DL(Op);
6386   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6387 
6388   // TODO: Should this propagate fast-math-flags?
6389 
6390   switch (IntrinsicID) {
6391   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6392     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6393       return emitNonHSAIntrinsicError(DAG, DL, VT);
6394     return getPreloadedValue(DAG, *MFI, VT,
6395                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6396   }
6397   case Intrinsic::amdgcn_dispatch_ptr:
6398   case Intrinsic::amdgcn_queue_ptr: {
6399     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6400       DiagnosticInfoUnsupported BadIntrin(
6401           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6402           DL.getDebugLoc());
6403       DAG.getContext()->diagnose(BadIntrin);
6404       return DAG.getUNDEF(VT);
6405     }
6406 
6407     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6408       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6409     return getPreloadedValue(DAG, *MFI, VT, RegID);
6410   }
6411   case Intrinsic::amdgcn_implicitarg_ptr: {
6412     if (MFI->isEntryFunction())
6413       return getImplicitArgPtr(DAG, DL);
6414     return getPreloadedValue(DAG, *MFI, VT,
6415                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6416   }
6417   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6418     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6419       // This only makes sense to call in a kernel, so just lower to null.
6420       return DAG.getConstant(0, DL, VT);
6421     }
6422 
6423     return getPreloadedValue(DAG, *MFI, VT,
6424                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6425   }
6426   case Intrinsic::amdgcn_dispatch_id: {
6427     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6428   }
6429   case Intrinsic::amdgcn_rcp:
6430     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6431   case Intrinsic::amdgcn_rsq:
6432     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6433   case Intrinsic::amdgcn_rsq_legacy:
6434     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6435       return emitRemovedIntrinsicError(DAG, DL, VT);
6436     return SDValue();
6437   case Intrinsic::amdgcn_rcp_legacy:
6438     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6439       return emitRemovedIntrinsicError(DAG, DL, VT);
6440     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6441   case Intrinsic::amdgcn_rsq_clamp: {
6442     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6443       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6444 
6445     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6446     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6447     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6448 
6449     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6450     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6451                               DAG.getConstantFP(Max, DL, VT));
6452     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6453                        DAG.getConstantFP(Min, DL, VT));
6454   }
6455   case Intrinsic::r600_read_ngroups_x:
6456     if (Subtarget->isAmdHsaOS())
6457       return emitNonHSAIntrinsicError(DAG, DL, VT);
6458 
6459     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6460                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6461                                     false);
6462   case Intrinsic::r600_read_ngroups_y:
6463     if (Subtarget->isAmdHsaOS())
6464       return emitNonHSAIntrinsicError(DAG, DL, VT);
6465 
6466     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6467                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6468                                     false);
6469   case Intrinsic::r600_read_ngroups_z:
6470     if (Subtarget->isAmdHsaOS())
6471       return emitNonHSAIntrinsicError(DAG, DL, VT);
6472 
6473     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6474                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6475                                     false);
6476   case Intrinsic::r600_read_global_size_x:
6477     if (Subtarget->isAmdHsaOS())
6478       return emitNonHSAIntrinsicError(DAG, DL, VT);
6479 
6480     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6481                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6482                                     Align(4), false);
6483   case Intrinsic::r600_read_global_size_y:
6484     if (Subtarget->isAmdHsaOS())
6485       return emitNonHSAIntrinsicError(DAG, DL, VT);
6486 
6487     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6488                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6489                                     Align(4), false);
6490   case Intrinsic::r600_read_global_size_z:
6491     if (Subtarget->isAmdHsaOS())
6492       return emitNonHSAIntrinsicError(DAG, DL, VT);
6493 
6494     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6495                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6496                                     Align(4), false);
6497   case Intrinsic::r600_read_local_size_x:
6498     if (Subtarget->isAmdHsaOS())
6499       return emitNonHSAIntrinsicError(DAG, DL, VT);
6500 
6501     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6502                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6503   case Intrinsic::r600_read_local_size_y:
6504     if (Subtarget->isAmdHsaOS())
6505       return emitNonHSAIntrinsicError(DAG, DL, VT);
6506 
6507     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6508                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6509   case Intrinsic::r600_read_local_size_z:
6510     if (Subtarget->isAmdHsaOS())
6511       return emitNonHSAIntrinsicError(DAG, DL, VT);
6512 
6513     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6514                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6515   case Intrinsic::amdgcn_workgroup_id_x:
6516     return getPreloadedValue(DAG, *MFI, VT,
6517                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6518   case Intrinsic::amdgcn_workgroup_id_y:
6519     return getPreloadedValue(DAG, *MFI, VT,
6520                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6521   case Intrinsic::amdgcn_workgroup_id_z:
6522     return getPreloadedValue(DAG, *MFI, VT,
6523                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6524   case Intrinsic::amdgcn_workitem_id_x:
6525     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6526                           SDLoc(DAG.getEntryNode()),
6527                           MFI->getArgInfo().WorkItemIDX);
6528   case Intrinsic::amdgcn_workitem_id_y:
6529     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6530                           SDLoc(DAG.getEntryNode()),
6531                           MFI->getArgInfo().WorkItemIDY);
6532   case Intrinsic::amdgcn_workitem_id_z:
6533     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6534                           SDLoc(DAG.getEntryNode()),
6535                           MFI->getArgInfo().WorkItemIDZ);
6536   case Intrinsic::amdgcn_wavefrontsize:
6537     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6538                            SDLoc(Op), MVT::i32);
6539   case Intrinsic::amdgcn_s_buffer_load: {
6540     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6541     SDValue GLC;
6542     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6543     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6544                           IsGFX10 ? &DLC : nullptr))
6545       return Op;
6546     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6547                         DAG);
6548   }
6549   case Intrinsic::amdgcn_fdiv_fast:
6550     return lowerFDIV_FAST(Op, DAG);
6551   case Intrinsic::amdgcn_sin:
6552     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6553 
6554   case Intrinsic::amdgcn_cos:
6555     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6556 
6557   case Intrinsic::amdgcn_mul_u24:
6558     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6559   case Intrinsic::amdgcn_mul_i24:
6560     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6561 
6562   case Intrinsic::amdgcn_log_clamp: {
6563     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6564       return SDValue();
6565 
6566     DiagnosticInfoUnsupported BadIntrin(
6567       MF.getFunction(), "intrinsic not supported on subtarget",
6568       DL.getDebugLoc());
6569       DAG.getContext()->diagnose(BadIntrin);
6570       return DAG.getUNDEF(VT);
6571   }
6572   case Intrinsic::amdgcn_ldexp:
6573     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6574                        Op.getOperand(1), Op.getOperand(2));
6575 
6576   case Intrinsic::amdgcn_fract:
6577     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6578 
6579   case Intrinsic::amdgcn_class:
6580     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6581                        Op.getOperand(1), Op.getOperand(2));
6582   case Intrinsic::amdgcn_div_fmas:
6583     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6584                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6585                        Op.getOperand(4));
6586 
6587   case Intrinsic::amdgcn_div_fixup:
6588     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6589                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6590 
6591   case Intrinsic::amdgcn_div_scale: {
6592     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6593 
6594     // Translate to the operands expected by the machine instruction. The
6595     // first parameter must be the same as the first instruction.
6596     SDValue Numerator = Op.getOperand(1);
6597     SDValue Denominator = Op.getOperand(2);
6598 
6599     // Note this order is opposite of the machine instruction's operations,
6600     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6601     // intrinsic has the numerator as the first operand to match a normal
6602     // division operation.
6603 
6604     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6605 
6606     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6607                        Denominator, Numerator);
6608   }
6609   case Intrinsic::amdgcn_icmp: {
6610     // There is a Pat that handles this variant, so return it as-is.
6611     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6612         Op.getConstantOperandVal(2) == 0 &&
6613         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6614       return Op;
6615     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6616   }
6617   case Intrinsic::amdgcn_fcmp: {
6618     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6619   }
6620   case Intrinsic::amdgcn_ballot:
6621     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6622   case Intrinsic::amdgcn_fmed3:
6623     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6624                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6625   case Intrinsic::amdgcn_fdot2:
6626     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6627                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6628                        Op.getOperand(4));
6629   case Intrinsic::amdgcn_fmul_legacy:
6630     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6631                        Op.getOperand(1), Op.getOperand(2));
6632   case Intrinsic::amdgcn_sffbh:
6633     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6634   case Intrinsic::amdgcn_sbfe:
6635     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6636                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6637   case Intrinsic::amdgcn_ubfe:
6638     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6639                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6640   case Intrinsic::amdgcn_cvt_pkrtz:
6641   case Intrinsic::amdgcn_cvt_pknorm_i16:
6642   case Intrinsic::amdgcn_cvt_pknorm_u16:
6643   case Intrinsic::amdgcn_cvt_pk_i16:
6644   case Intrinsic::amdgcn_cvt_pk_u16: {
6645     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6646     EVT VT = Op.getValueType();
6647     unsigned Opcode;
6648 
6649     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6650       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6651     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6652       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6653     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6654       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6655     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6656       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6657     else
6658       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6659 
6660     if (isTypeLegal(VT))
6661       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6662 
6663     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6664                                Op.getOperand(1), Op.getOperand(2));
6665     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6666   }
6667   case Intrinsic::amdgcn_fmad_ftz:
6668     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6669                        Op.getOperand(2), Op.getOperand(3));
6670 
6671   case Intrinsic::amdgcn_if_break:
6672     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6673                                       Op->getOperand(1), Op->getOperand(2)), 0);
6674 
6675   case Intrinsic::amdgcn_groupstaticsize: {
6676     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6677     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6678       return Op;
6679 
6680     const Module *M = MF.getFunction().getParent();
6681     const GlobalValue *GV =
6682         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6683     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6684                                             SIInstrInfo::MO_ABS32_LO);
6685     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6686   }
6687   case Intrinsic::amdgcn_is_shared:
6688   case Intrinsic::amdgcn_is_private: {
6689     SDLoc SL(Op);
6690     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6691       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6692     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6693     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6694                                  Op.getOperand(1));
6695 
6696     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6697                                 DAG.getConstant(1, SL, MVT::i32));
6698     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6699   }
6700   case Intrinsic::amdgcn_alignbit:
6701     return DAG.getNode(ISD::FSHR, DL, VT,
6702                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6703   case Intrinsic::amdgcn_reloc_constant: {
6704     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6705     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6706     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6707     auto RelocSymbol = cast<GlobalVariable>(
6708         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6709     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6710                                             SIInstrInfo::MO_ABS32_LO);
6711     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6712   }
6713   default:
6714     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6715             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6716       return lowerImage(Op, ImageDimIntr, DAG);
6717 
6718     return Op;
6719   }
6720 }
6721 
6722 // This function computes an appropriate offset to pass to
6723 // MachineMemOperand::setOffset() based on the offset inputs to
6724 // an intrinsic.  If any of the offsets are non-contstant or
6725 // if VIndex is non-zero then this function returns 0.  Otherwise,
6726 // it returns the sum of VOffset, SOffset, and Offset.
6727 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6728                                       SDValue SOffset,
6729                                       SDValue Offset,
6730                                       SDValue VIndex = SDValue()) {
6731 
6732   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6733       !isa<ConstantSDNode>(Offset))
6734     return 0;
6735 
6736   if (VIndex) {
6737     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6738       return 0;
6739   }
6740 
6741   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6742          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6743          cast<ConstantSDNode>(Offset)->getSExtValue();
6744 }
6745 
6746 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6747                                                      SelectionDAG &DAG,
6748                                                      unsigned NewOpcode) const {
6749   SDLoc DL(Op);
6750 
6751   SDValue VData = Op.getOperand(2);
6752   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6753   SDValue Ops[] = {
6754     Op.getOperand(0), // Chain
6755     VData,            // vdata
6756     Op.getOperand(3), // rsrc
6757     DAG.getConstant(0, DL, MVT::i32), // vindex
6758     Offsets.first,    // voffset
6759     Op.getOperand(5), // soffset
6760     Offsets.second,   // offset
6761     Op.getOperand(6), // cachepolicy
6762     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6763   };
6764 
6765   auto *M = cast<MemSDNode>(Op);
6766   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6767 
6768   EVT MemVT = VData.getValueType();
6769   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6770                                  M->getMemOperand());
6771 }
6772 
6773 SDValue
6774 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6775                                                 unsigned NewOpcode) const {
6776   SDLoc DL(Op);
6777 
6778   SDValue VData = Op.getOperand(2);
6779   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6780   SDValue Ops[] = {
6781     Op.getOperand(0), // Chain
6782     VData,            // vdata
6783     Op.getOperand(3), // rsrc
6784     Op.getOperand(4), // vindex
6785     Offsets.first,    // voffset
6786     Op.getOperand(6), // soffset
6787     Offsets.second,   // offset
6788     Op.getOperand(7), // cachepolicy
6789     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6790   };
6791 
6792   auto *M = cast<MemSDNode>(Op);
6793   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6794                                                       Ops[3]));
6795 
6796   EVT MemVT = VData.getValueType();
6797   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6798                                  M->getMemOperand());
6799 }
6800 
6801 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6802                                                  SelectionDAG &DAG) const {
6803   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6804   SDLoc DL(Op);
6805 
6806   switch (IntrID) {
6807   case Intrinsic::amdgcn_ds_ordered_add:
6808   case Intrinsic::amdgcn_ds_ordered_swap: {
6809     MemSDNode *M = cast<MemSDNode>(Op);
6810     SDValue Chain = M->getOperand(0);
6811     SDValue M0 = M->getOperand(2);
6812     SDValue Value = M->getOperand(3);
6813     unsigned IndexOperand = M->getConstantOperandVal(7);
6814     unsigned WaveRelease = M->getConstantOperandVal(8);
6815     unsigned WaveDone = M->getConstantOperandVal(9);
6816 
6817     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6818     IndexOperand &= ~0x3f;
6819     unsigned CountDw = 0;
6820 
6821     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6822       CountDw = (IndexOperand >> 24) & 0xf;
6823       IndexOperand &= ~(0xf << 24);
6824 
6825       if (CountDw < 1 || CountDw > 4) {
6826         report_fatal_error(
6827             "ds_ordered_count: dword count must be between 1 and 4");
6828       }
6829     }
6830 
6831     if (IndexOperand)
6832       report_fatal_error("ds_ordered_count: bad index operand");
6833 
6834     if (WaveDone && !WaveRelease)
6835       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6836 
6837     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6838     unsigned ShaderType =
6839         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6840     unsigned Offset0 = OrderedCountIndex << 2;
6841     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6842                        (Instruction << 4);
6843 
6844     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6845       Offset1 |= (CountDw - 1) << 6;
6846 
6847     unsigned Offset = Offset0 | (Offset1 << 8);
6848 
6849     SDValue Ops[] = {
6850       Chain,
6851       Value,
6852       DAG.getTargetConstant(Offset, DL, MVT::i16),
6853       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6854     };
6855     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6856                                    M->getVTList(), Ops, M->getMemoryVT(),
6857                                    M->getMemOperand());
6858   }
6859   case Intrinsic::amdgcn_ds_fadd: {
6860     MemSDNode *M = cast<MemSDNode>(Op);
6861     unsigned Opc;
6862     switch (IntrID) {
6863     case Intrinsic::amdgcn_ds_fadd:
6864       Opc = ISD::ATOMIC_LOAD_FADD;
6865       break;
6866     }
6867 
6868     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6869                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6870                          M->getMemOperand());
6871   }
6872   case Intrinsic::amdgcn_atomic_inc:
6873   case Intrinsic::amdgcn_atomic_dec:
6874   case Intrinsic::amdgcn_ds_fmin:
6875   case Intrinsic::amdgcn_ds_fmax: {
6876     MemSDNode *M = cast<MemSDNode>(Op);
6877     unsigned Opc;
6878     switch (IntrID) {
6879     case Intrinsic::amdgcn_atomic_inc:
6880       Opc = AMDGPUISD::ATOMIC_INC;
6881       break;
6882     case Intrinsic::amdgcn_atomic_dec:
6883       Opc = AMDGPUISD::ATOMIC_DEC;
6884       break;
6885     case Intrinsic::amdgcn_ds_fmin:
6886       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6887       break;
6888     case Intrinsic::amdgcn_ds_fmax:
6889       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6890       break;
6891     default:
6892       llvm_unreachable("Unknown intrinsic!");
6893     }
6894     SDValue Ops[] = {
6895       M->getOperand(0), // Chain
6896       M->getOperand(2), // Ptr
6897       M->getOperand(3)  // Value
6898     };
6899 
6900     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6901                                    M->getMemoryVT(), M->getMemOperand());
6902   }
6903   case Intrinsic::amdgcn_buffer_load:
6904   case Intrinsic::amdgcn_buffer_load_format: {
6905     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6906     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6907     unsigned IdxEn = 1;
6908     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6909       IdxEn = Idx->getZExtValue() != 0;
6910     SDValue Ops[] = {
6911       Op.getOperand(0), // Chain
6912       Op.getOperand(2), // rsrc
6913       Op.getOperand(3), // vindex
6914       SDValue(),        // voffset -- will be set by setBufferOffsets
6915       SDValue(),        // soffset -- will be set by setBufferOffsets
6916       SDValue(),        // offset -- will be set by setBufferOffsets
6917       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6918       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6919     };
6920 
6921     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6922     // We don't know the offset if vindex is non-zero, so clear it.
6923     if (IdxEn)
6924       Offset = 0;
6925 
6926     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6927         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6928 
6929     EVT VT = Op.getValueType();
6930     EVT IntVT = VT.changeTypeToInteger();
6931     auto *M = cast<MemSDNode>(Op);
6932     M->getMemOperand()->setOffset(Offset);
6933     EVT LoadVT = Op.getValueType();
6934 
6935     if (LoadVT.getScalarType() == MVT::f16)
6936       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6937                                  M, DAG, Ops);
6938 
6939     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6940     if (LoadVT.getScalarType() == MVT::i8 ||
6941         LoadVT.getScalarType() == MVT::i16)
6942       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6943 
6944     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6945                                M->getMemOperand(), DAG);
6946   }
6947   case Intrinsic::amdgcn_raw_buffer_load:
6948   case Intrinsic::amdgcn_raw_buffer_load_format: {
6949     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6950 
6951     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6952     SDValue Ops[] = {
6953       Op.getOperand(0), // Chain
6954       Op.getOperand(2), // rsrc
6955       DAG.getConstant(0, DL, MVT::i32), // vindex
6956       Offsets.first,    // voffset
6957       Op.getOperand(4), // soffset
6958       Offsets.second,   // offset
6959       Op.getOperand(5), // cachepolicy, swizzled buffer
6960       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6961     };
6962 
6963     auto *M = cast<MemSDNode>(Op);
6964     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6965     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6966   }
6967   case Intrinsic::amdgcn_struct_buffer_load:
6968   case Intrinsic::amdgcn_struct_buffer_load_format: {
6969     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6970 
6971     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6972     SDValue Ops[] = {
6973       Op.getOperand(0), // Chain
6974       Op.getOperand(2), // rsrc
6975       Op.getOperand(3), // vindex
6976       Offsets.first,    // voffset
6977       Op.getOperand(5), // soffset
6978       Offsets.second,   // offset
6979       Op.getOperand(6), // cachepolicy, swizzled buffer
6980       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6981     };
6982 
6983     auto *M = cast<MemSDNode>(Op);
6984     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6985                                                         Ops[2]));
6986     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6987   }
6988   case Intrinsic::amdgcn_tbuffer_load: {
6989     MemSDNode *M = cast<MemSDNode>(Op);
6990     EVT LoadVT = Op.getValueType();
6991 
6992     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6993     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6994     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6995     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6996     unsigned IdxEn = 1;
6997     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6998       IdxEn = Idx->getZExtValue() != 0;
6999     SDValue Ops[] = {
7000       Op.getOperand(0),  // Chain
7001       Op.getOperand(2),  // rsrc
7002       Op.getOperand(3),  // vindex
7003       Op.getOperand(4),  // voffset
7004       Op.getOperand(5),  // soffset
7005       Op.getOperand(6),  // offset
7006       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7007       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7008       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7009     };
7010 
7011     if (LoadVT.getScalarType() == MVT::f16)
7012       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7013                                  M, DAG, Ops);
7014     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7015                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7016                                DAG);
7017   }
7018   case Intrinsic::amdgcn_raw_tbuffer_load: {
7019     MemSDNode *M = cast<MemSDNode>(Op);
7020     EVT LoadVT = Op.getValueType();
7021     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7022 
7023     SDValue Ops[] = {
7024       Op.getOperand(0),  // Chain
7025       Op.getOperand(2),  // rsrc
7026       DAG.getConstant(0, DL, MVT::i32), // vindex
7027       Offsets.first,     // voffset
7028       Op.getOperand(4),  // soffset
7029       Offsets.second,    // offset
7030       Op.getOperand(5),  // format
7031       Op.getOperand(6),  // cachepolicy, swizzled buffer
7032       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7033     };
7034 
7035     if (LoadVT.getScalarType() == MVT::f16)
7036       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7037                                  M, DAG, Ops);
7038     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7039                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7040                                DAG);
7041   }
7042   case Intrinsic::amdgcn_struct_tbuffer_load: {
7043     MemSDNode *M = cast<MemSDNode>(Op);
7044     EVT LoadVT = Op.getValueType();
7045     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7046 
7047     SDValue Ops[] = {
7048       Op.getOperand(0),  // Chain
7049       Op.getOperand(2),  // rsrc
7050       Op.getOperand(3),  // vindex
7051       Offsets.first,     // voffset
7052       Op.getOperand(5),  // soffset
7053       Offsets.second,    // offset
7054       Op.getOperand(6),  // format
7055       Op.getOperand(7),  // cachepolicy, swizzled buffer
7056       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7057     };
7058 
7059     if (LoadVT.getScalarType() == MVT::f16)
7060       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7061                                  M, DAG, Ops);
7062     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7063                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7064                                DAG);
7065   }
7066   case Intrinsic::amdgcn_buffer_atomic_swap:
7067   case Intrinsic::amdgcn_buffer_atomic_add:
7068   case Intrinsic::amdgcn_buffer_atomic_sub:
7069   case Intrinsic::amdgcn_buffer_atomic_csub:
7070   case Intrinsic::amdgcn_buffer_atomic_smin:
7071   case Intrinsic::amdgcn_buffer_atomic_umin:
7072   case Intrinsic::amdgcn_buffer_atomic_smax:
7073   case Intrinsic::amdgcn_buffer_atomic_umax:
7074   case Intrinsic::amdgcn_buffer_atomic_and:
7075   case Intrinsic::amdgcn_buffer_atomic_or:
7076   case Intrinsic::amdgcn_buffer_atomic_xor:
7077   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7078     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7079     unsigned IdxEn = 1;
7080     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7081       IdxEn = Idx->getZExtValue() != 0;
7082     SDValue Ops[] = {
7083       Op.getOperand(0), // Chain
7084       Op.getOperand(2), // vdata
7085       Op.getOperand(3), // rsrc
7086       Op.getOperand(4), // vindex
7087       SDValue(),        // voffset -- will be set by setBufferOffsets
7088       SDValue(),        // soffset -- will be set by setBufferOffsets
7089       SDValue(),        // offset -- will be set by setBufferOffsets
7090       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7091       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7092     };
7093     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7094     // We don't know the offset if vindex is non-zero, so clear it.
7095     if (IdxEn)
7096       Offset = 0;
7097     EVT VT = Op.getValueType();
7098 
7099     auto *M = cast<MemSDNode>(Op);
7100     M->getMemOperand()->setOffset(Offset);
7101     unsigned Opcode = 0;
7102 
7103     switch (IntrID) {
7104     case Intrinsic::amdgcn_buffer_atomic_swap:
7105       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7106       break;
7107     case Intrinsic::amdgcn_buffer_atomic_add:
7108       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7109       break;
7110     case Intrinsic::amdgcn_buffer_atomic_sub:
7111       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7112       break;
7113     case Intrinsic::amdgcn_buffer_atomic_csub:
7114       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7115       break;
7116     case Intrinsic::amdgcn_buffer_atomic_smin:
7117       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7118       break;
7119     case Intrinsic::amdgcn_buffer_atomic_umin:
7120       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7121       break;
7122     case Intrinsic::amdgcn_buffer_atomic_smax:
7123       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7124       break;
7125     case Intrinsic::amdgcn_buffer_atomic_umax:
7126       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7127       break;
7128     case Intrinsic::amdgcn_buffer_atomic_and:
7129       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7130       break;
7131     case Intrinsic::amdgcn_buffer_atomic_or:
7132       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7133       break;
7134     case Intrinsic::amdgcn_buffer_atomic_xor:
7135       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7136       break;
7137     case Intrinsic::amdgcn_buffer_atomic_fadd:
7138       if (!Op.getValue(0).use_empty()) {
7139         DiagnosticInfoUnsupported
7140           NoFpRet(DAG.getMachineFunction().getFunction(),
7141                   "return versions of fp atomics not supported",
7142                   DL.getDebugLoc(), DS_Error);
7143         DAG.getContext()->diagnose(NoFpRet);
7144         return SDValue();
7145       }
7146       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7147       break;
7148     default:
7149       llvm_unreachable("unhandled atomic opcode");
7150     }
7151 
7152     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7153                                    M->getMemOperand());
7154   }
7155   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7156     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7157   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7158     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7159   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7160     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7161   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7162     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7163   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7164     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7165   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7166     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7167   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7168     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7169   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7170     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7171   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7172     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7173   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7174     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7175   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7176     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7177   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7178     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7179   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7180     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7181   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7182     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7183   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7184     return lowerStructBufferAtomicIntrin(Op, DAG,
7185                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7186   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7187     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7188   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7189     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7190   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7191     return lowerStructBufferAtomicIntrin(Op, DAG,
7192                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7193   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7194     return lowerStructBufferAtomicIntrin(Op, DAG,
7195                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7196   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7197     return lowerStructBufferAtomicIntrin(Op, DAG,
7198                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7199   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7200     return lowerStructBufferAtomicIntrin(Op, DAG,
7201                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7202   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7203     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7204   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7205     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7206   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7207     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7208   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7209     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7210   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7211     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7212 
7213   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7214     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7215     unsigned IdxEn = 1;
7216     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7217       IdxEn = Idx->getZExtValue() != 0;
7218     SDValue Ops[] = {
7219       Op.getOperand(0), // Chain
7220       Op.getOperand(2), // src
7221       Op.getOperand(3), // cmp
7222       Op.getOperand(4), // rsrc
7223       Op.getOperand(5), // vindex
7224       SDValue(),        // voffset -- will be set by setBufferOffsets
7225       SDValue(),        // soffset -- will be set by setBufferOffsets
7226       SDValue(),        // offset -- will be set by setBufferOffsets
7227       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7228       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7229     };
7230     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7231     // We don't know the offset if vindex is non-zero, so clear it.
7232     if (IdxEn)
7233       Offset = 0;
7234     EVT VT = Op.getValueType();
7235     auto *M = cast<MemSDNode>(Op);
7236     M->getMemOperand()->setOffset(Offset);
7237 
7238     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7239                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7240   }
7241   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7242     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7243     SDValue Ops[] = {
7244       Op.getOperand(0), // Chain
7245       Op.getOperand(2), // src
7246       Op.getOperand(3), // cmp
7247       Op.getOperand(4), // rsrc
7248       DAG.getConstant(0, DL, MVT::i32), // vindex
7249       Offsets.first,    // voffset
7250       Op.getOperand(6), // soffset
7251       Offsets.second,   // offset
7252       Op.getOperand(7), // cachepolicy
7253       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7254     };
7255     EVT VT = Op.getValueType();
7256     auto *M = cast<MemSDNode>(Op);
7257     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7258 
7259     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7260                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7261   }
7262   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7263     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7264     SDValue Ops[] = {
7265       Op.getOperand(0), // Chain
7266       Op.getOperand(2), // src
7267       Op.getOperand(3), // cmp
7268       Op.getOperand(4), // rsrc
7269       Op.getOperand(5), // vindex
7270       Offsets.first,    // voffset
7271       Op.getOperand(7), // soffset
7272       Offsets.second,   // offset
7273       Op.getOperand(8), // cachepolicy
7274       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7275     };
7276     EVT VT = Op.getValueType();
7277     auto *M = cast<MemSDNode>(Op);
7278     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7279                                                         Ops[4]));
7280 
7281     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7282                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7283   }
7284   case Intrinsic::amdgcn_global_atomic_fadd: {
7285     if (!Op.getValue(0).use_empty()) {
7286       DiagnosticInfoUnsupported
7287         NoFpRet(DAG.getMachineFunction().getFunction(),
7288                 "return versions of fp atomics not supported",
7289                 DL.getDebugLoc(), DS_Error);
7290       DAG.getContext()->diagnose(NoFpRet);
7291       return SDValue();
7292     }
7293     MemSDNode *M = cast<MemSDNode>(Op);
7294     SDValue Ops[] = {
7295       M->getOperand(0), // Chain
7296       M->getOperand(2), // Ptr
7297       M->getOperand(3)  // Value
7298     };
7299 
7300     EVT VT = Op.getOperand(3).getValueType();
7301     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7302                          DAG.getVTList(VT, MVT::Other), Ops,
7303                          M->getMemOperand());
7304   }
7305   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7306     SDLoc DL(Op);
7307     MemSDNode *M = cast<MemSDNode>(Op);
7308     SDValue NodePtr = M->getOperand(2);
7309     SDValue RayExtent = M->getOperand(3);
7310     SDValue RayOrigin = M->getOperand(4);
7311     SDValue RayDir = M->getOperand(5);
7312     SDValue RayInvDir = M->getOperand(6);
7313     SDValue TDescr = M->getOperand(7);
7314 
7315     assert(NodePtr.getValueType() == MVT::i32 ||
7316            NodePtr.getValueType() == MVT::i64);
7317     assert(RayDir.getValueType() == MVT::v4f16 ||
7318            RayDir.getValueType() == MVT::v4f32);
7319 
7320     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7321     bool Is64 = NodePtr.getValueType() == MVT::i64;
7322     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7323                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7324                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7325                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7326 
7327     SmallVector<SDValue, 16> Ops;
7328 
7329     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7330       SmallVector<SDValue, 3> Lanes;
7331       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7332       if (Lanes[0].getValueSizeInBits() == 32) {
7333         for (unsigned I = 0; I < 3; ++I)
7334           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7335       } else {
7336         if (IsAligned) {
7337           Ops.push_back(
7338             DAG.getBitcast(MVT::i32,
7339                            DAG.getBuildVector(MVT::v2f16, DL,
7340                                               { Lanes[0], Lanes[1] })));
7341           Ops.push_back(Lanes[2]);
7342         } else {
7343           SDValue Elt0 = Ops.pop_back_val();
7344           Ops.push_back(
7345             DAG.getBitcast(MVT::i32,
7346                            DAG.getBuildVector(MVT::v2f16, DL,
7347                                               { Elt0, Lanes[0] })));
7348           Ops.push_back(
7349             DAG.getBitcast(MVT::i32,
7350                            DAG.getBuildVector(MVT::v2f16, DL,
7351                                               { Lanes[1], Lanes[2] })));
7352         }
7353       }
7354     };
7355 
7356     if (Is64)
7357       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7358     else
7359       Ops.push_back(NodePtr);
7360 
7361     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7362     packLanes(RayOrigin, true);
7363     packLanes(RayDir, true);
7364     packLanes(RayInvDir, false);
7365     Ops.push_back(TDescr);
7366     if (IsA16)
7367       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7368     Ops.push_back(M->getChain());
7369 
7370     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7371     MachineMemOperand *MemRef = M->getMemOperand();
7372     DAG.setNodeMemRefs(NewNode, {MemRef});
7373     return SDValue(NewNode, 0);
7374   }
7375   default:
7376     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7377             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7378       return lowerImage(Op, ImageDimIntr, DAG);
7379 
7380     return SDValue();
7381   }
7382 }
7383 
7384 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7385 // dwordx4 if on SI.
7386 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7387                                               SDVTList VTList,
7388                                               ArrayRef<SDValue> Ops, EVT MemVT,
7389                                               MachineMemOperand *MMO,
7390                                               SelectionDAG &DAG) const {
7391   EVT VT = VTList.VTs[0];
7392   EVT WidenedVT = VT;
7393   EVT WidenedMemVT = MemVT;
7394   if (!Subtarget->hasDwordx3LoadStores() &&
7395       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7396     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7397                                  WidenedVT.getVectorElementType(), 4);
7398     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7399                                     WidenedMemVT.getVectorElementType(), 4);
7400     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7401   }
7402 
7403   assert(VTList.NumVTs == 2);
7404   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7405 
7406   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7407                                        WidenedMemVT, MMO);
7408   if (WidenedVT != VT) {
7409     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7410                                DAG.getVectorIdxConstant(0, DL));
7411     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7412   }
7413   return NewOp;
7414 }
7415 
7416 SDValue SITargetLowering::handleD16VData(SDValue VData,
7417                                          SelectionDAG &DAG) const {
7418   EVT StoreVT = VData.getValueType();
7419 
7420   // No change for f16 and legal vector D16 types.
7421   if (!StoreVT.isVector())
7422     return VData;
7423 
7424   SDLoc DL(VData);
7425   unsigned NumElements = StoreVT.getVectorNumElements();
7426 
7427   if (Subtarget->hasUnpackedD16VMem()) {
7428     // We need to unpack the packed data to store.
7429     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7430     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7431 
7432     EVT EquivStoreVT =
7433         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7434     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7435     return DAG.UnrollVectorOp(ZExt.getNode());
7436   } else if (NumElements == 3) {
7437     EVT IntStoreVT =
7438         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7439     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7440 
7441     EVT WidenedStoreVT = EVT::getVectorVT(
7442         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7443     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7444                                          WidenedStoreVT.getStoreSizeInBits());
7445     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7446     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7447   }
7448 
7449   assert(isTypeLegal(StoreVT));
7450   return VData;
7451 }
7452 
7453 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7454                                               SelectionDAG &DAG) const {
7455   SDLoc DL(Op);
7456   SDValue Chain = Op.getOperand(0);
7457   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7458   MachineFunction &MF = DAG.getMachineFunction();
7459 
7460   switch (IntrinsicID) {
7461   case Intrinsic::amdgcn_exp_compr: {
7462     SDValue Src0 = Op.getOperand(4);
7463     SDValue Src1 = Op.getOperand(5);
7464     // Hack around illegal type on SI by directly selecting it.
7465     if (isTypeLegal(Src0.getValueType()))
7466       return SDValue();
7467 
7468     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7469     SDValue Undef = DAG.getUNDEF(MVT::f32);
7470     const SDValue Ops[] = {
7471       Op.getOperand(2), // tgt
7472       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7473       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7474       Undef, // src2
7475       Undef, // src3
7476       Op.getOperand(7), // vm
7477       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7478       Op.getOperand(3), // en
7479       Op.getOperand(0) // Chain
7480     };
7481 
7482     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7483     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7484   }
7485   case Intrinsic::amdgcn_s_barrier: {
7486     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7487       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7488       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7489       if (WGSize <= ST.getWavefrontSize())
7490         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7491                                           Op.getOperand(0)), 0);
7492     }
7493     return SDValue();
7494   };
7495   case Intrinsic::amdgcn_tbuffer_store: {
7496     SDValue VData = Op.getOperand(2);
7497     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7498     if (IsD16)
7499       VData = handleD16VData(VData, DAG);
7500     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7501     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7502     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7503     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7504     unsigned IdxEn = 1;
7505     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7506       IdxEn = Idx->getZExtValue() != 0;
7507     SDValue Ops[] = {
7508       Chain,
7509       VData,             // vdata
7510       Op.getOperand(3),  // rsrc
7511       Op.getOperand(4),  // vindex
7512       Op.getOperand(5),  // voffset
7513       Op.getOperand(6),  // soffset
7514       Op.getOperand(7),  // offset
7515       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7516       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7517       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7518     };
7519     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7520                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7521     MemSDNode *M = cast<MemSDNode>(Op);
7522     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7523                                    M->getMemoryVT(), M->getMemOperand());
7524   }
7525 
7526   case Intrinsic::amdgcn_struct_tbuffer_store: {
7527     SDValue VData = Op.getOperand(2);
7528     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7529     if (IsD16)
7530       VData = handleD16VData(VData, DAG);
7531     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7532     SDValue Ops[] = {
7533       Chain,
7534       VData,             // vdata
7535       Op.getOperand(3),  // rsrc
7536       Op.getOperand(4),  // vindex
7537       Offsets.first,     // voffset
7538       Op.getOperand(6),  // soffset
7539       Offsets.second,    // offset
7540       Op.getOperand(7),  // format
7541       Op.getOperand(8),  // cachepolicy, swizzled buffer
7542       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7543     };
7544     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7545                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7546     MemSDNode *M = cast<MemSDNode>(Op);
7547     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7548                                    M->getMemoryVT(), M->getMemOperand());
7549   }
7550 
7551   case Intrinsic::amdgcn_raw_tbuffer_store: {
7552     SDValue VData = Op.getOperand(2);
7553     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7554     if (IsD16)
7555       VData = handleD16VData(VData, DAG);
7556     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7557     SDValue Ops[] = {
7558       Chain,
7559       VData,             // vdata
7560       Op.getOperand(3),  // rsrc
7561       DAG.getConstant(0, DL, MVT::i32), // vindex
7562       Offsets.first,     // voffset
7563       Op.getOperand(5),  // soffset
7564       Offsets.second,    // offset
7565       Op.getOperand(6),  // format
7566       Op.getOperand(7),  // cachepolicy, swizzled buffer
7567       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7568     };
7569     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7570                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7571     MemSDNode *M = cast<MemSDNode>(Op);
7572     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7573                                    M->getMemoryVT(), M->getMemOperand());
7574   }
7575 
7576   case Intrinsic::amdgcn_buffer_store:
7577   case Intrinsic::amdgcn_buffer_store_format: {
7578     SDValue VData = Op.getOperand(2);
7579     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7580     if (IsD16)
7581       VData = handleD16VData(VData, DAG);
7582     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7583     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7584     unsigned IdxEn = 1;
7585     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7586       IdxEn = Idx->getZExtValue() != 0;
7587     SDValue Ops[] = {
7588       Chain,
7589       VData,
7590       Op.getOperand(3), // rsrc
7591       Op.getOperand(4), // vindex
7592       SDValue(), // voffset -- will be set by setBufferOffsets
7593       SDValue(), // soffset -- will be set by setBufferOffsets
7594       SDValue(), // offset -- will be set by setBufferOffsets
7595       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7596       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7597     };
7598     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7599     // We don't know the offset if vindex is non-zero, so clear it.
7600     if (IdxEn)
7601       Offset = 0;
7602     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7603                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7604     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7605     MemSDNode *M = cast<MemSDNode>(Op);
7606     M->getMemOperand()->setOffset(Offset);
7607 
7608     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7609     EVT VDataType = VData.getValueType().getScalarType();
7610     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7611       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7612 
7613     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7614                                    M->getMemoryVT(), M->getMemOperand());
7615   }
7616 
7617   case Intrinsic::amdgcn_raw_buffer_store:
7618   case Intrinsic::amdgcn_raw_buffer_store_format: {
7619     const bool IsFormat =
7620         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7621 
7622     SDValue VData = Op.getOperand(2);
7623     EVT VDataVT = VData.getValueType();
7624     EVT EltType = VDataVT.getScalarType();
7625     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7626     if (IsD16) {
7627       VData = handleD16VData(VData, DAG);
7628       VDataVT = VData.getValueType();
7629     }
7630 
7631     if (!isTypeLegal(VDataVT)) {
7632       VData =
7633           DAG.getNode(ISD::BITCAST, DL,
7634                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7635     }
7636 
7637     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7638     SDValue Ops[] = {
7639       Chain,
7640       VData,
7641       Op.getOperand(3), // rsrc
7642       DAG.getConstant(0, DL, MVT::i32), // vindex
7643       Offsets.first,    // voffset
7644       Op.getOperand(5), // soffset
7645       Offsets.second,   // offset
7646       Op.getOperand(6), // cachepolicy, swizzled buffer
7647       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7648     };
7649     unsigned Opc =
7650         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7651     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7652     MemSDNode *M = cast<MemSDNode>(Op);
7653     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7654 
7655     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7656     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7657       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7658 
7659     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7660                                    M->getMemoryVT(), M->getMemOperand());
7661   }
7662 
7663   case Intrinsic::amdgcn_struct_buffer_store:
7664   case Intrinsic::amdgcn_struct_buffer_store_format: {
7665     const bool IsFormat =
7666         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7667 
7668     SDValue VData = Op.getOperand(2);
7669     EVT VDataVT = VData.getValueType();
7670     EVT EltType = VDataVT.getScalarType();
7671     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7672 
7673     if (IsD16) {
7674       VData = handleD16VData(VData, DAG);
7675       VDataVT = VData.getValueType();
7676     }
7677 
7678     if (!isTypeLegal(VDataVT)) {
7679       VData =
7680           DAG.getNode(ISD::BITCAST, DL,
7681                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7682     }
7683 
7684     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7685     SDValue Ops[] = {
7686       Chain,
7687       VData,
7688       Op.getOperand(3), // rsrc
7689       Op.getOperand(4), // vindex
7690       Offsets.first,    // voffset
7691       Op.getOperand(6), // soffset
7692       Offsets.second,   // offset
7693       Op.getOperand(7), // cachepolicy, swizzled buffer
7694       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7695     };
7696     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7697                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7698     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7699     MemSDNode *M = cast<MemSDNode>(Op);
7700     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7701                                                         Ops[3]));
7702 
7703     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7704     EVT VDataType = VData.getValueType().getScalarType();
7705     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7706       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7707 
7708     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7709                                    M->getMemoryVT(), M->getMemOperand());
7710   }
7711   case Intrinsic::amdgcn_end_cf:
7712     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7713                                       Op->getOperand(2), Chain), 0);
7714 
7715   default: {
7716     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7717             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7718       return lowerImage(Op, ImageDimIntr, DAG);
7719 
7720     return Op;
7721   }
7722   }
7723 }
7724 
7725 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7726 // offset (the offset that is included in bounds checking and swizzling, to be
7727 // split between the instruction's voffset and immoffset fields) and soffset
7728 // (the offset that is excluded from bounds checking and swizzling, to go in
7729 // the instruction's soffset field).  This function takes the first kind of
7730 // offset and figures out how to split it between voffset and immoffset.
7731 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7732     SDValue Offset, SelectionDAG &DAG) const {
7733   SDLoc DL(Offset);
7734   const unsigned MaxImm = 4095;
7735   SDValue N0 = Offset;
7736   ConstantSDNode *C1 = nullptr;
7737 
7738   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7739     N0 = SDValue();
7740   else if (DAG.isBaseWithConstantOffset(N0)) {
7741     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7742     N0 = N0.getOperand(0);
7743   }
7744 
7745   if (C1) {
7746     unsigned ImmOffset = C1->getZExtValue();
7747     // If the immediate value is too big for the immoffset field, put the value
7748     // and -4096 into the immoffset field so that the value that is copied/added
7749     // for the voffset field is a multiple of 4096, and it stands more chance
7750     // of being CSEd with the copy/add for another similar load/store.
7751     // However, do not do that rounding down to a multiple of 4096 if that is a
7752     // negative number, as it appears to be illegal to have a negative offset
7753     // in the vgpr, even if adding the immediate offset makes it positive.
7754     unsigned Overflow = ImmOffset & ~MaxImm;
7755     ImmOffset -= Overflow;
7756     if ((int32_t)Overflow < 0) {
7757       Overflow += ImmOffset;
7758       ImmOffset = 0;
7759     }
7760     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7761     if (Overflow) {
7762       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7763       if (!N0)
7764         N0 = OverflowVal;
7765       else {
7766         SDValue Ops[] = { N0, OverflowVal };
7767         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7768       }
7769     }
7770   }
7771   if (!N0)
7772     N0 = DAG.getConstant(0, DL, MVT::i32);
7773   if (!C1)
7774     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7775   return {N0, SDValue(C1, 0)};
7776 }
7777 
7778 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7779 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7780 // pointed to by Offsets.
7781 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7782                                             SelectionDAG &DAG, SDValue *Offsets,
7783                                             Align Alignment) const {
7784   SDLoc DL(CombinedOffset);
7785   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7786     uint32_t Imm = C->getZExtValue();
7787     uint32_t SOffset, ImmOffset;
7788     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7789                                  Alignment)) {
7790       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7791       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7792       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7793       return SOffset + ImmOffset;
7794     }
7795   }
7796   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7797     SDValue N0 = CombinedOffset.getOperand(0);
7798     SDValue N1 = CombinedOffset.getOperand(1);
7799     uint32_t SOffset, ImmOffset;
7800     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7801     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7802                                                 Subtarget, Alignment)) {
7803       Offsets[0] = N0;
7804       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7805       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7806       return 0;
7807     }
7808   }
7809   Offsets[0] = CombinedOffset;
7810   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7811   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7812   return 0;
7813 }
7814 
7815 // Handle 8 bit and 16 bit buffer loads
7816 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7817                                                      EVT LoadVT, SDLoc DL,
7818                                                      ArrayRef<SDValue> Ops,
7819                                                      MemSDNode *M) const {
7820   EVT IntVT = LoadVT.changeTypeToInteger();
7821   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7822          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7823 
7824   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7825   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7826                                                Ops, IntVT,
7827                                                M->getMemOperand());
7828   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7829   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7830 
7831   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7832 }
7833 
7834 // Handle 8 bit and 16 bit buffer stores
7835 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7836                                                       EVT VDataType, SDLoc DL,
7837                                                       SDValue Ops[],
7838                                                       MemSDNode *M) const {
7839   if (VDataType == MVT::f16)
7840     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7841 
7842   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7843   Ops[1] = BufferStoreExt;
7844   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7845                                  AMDGPUISD::BUFFER_STORE_SHORT;
7846   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7847   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7848                                      M->getMemOperand());
7849 }
7850 
7851 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7852                                  ISD::LoadExtType ExtType, SDValue Op,
7853                                  const SDLoc &SL, EVT VT) {
7854   if (VT.bitsLT(Op.getValueType()))
7855     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7856 
7857   switch (ExtType) {
7858   case ISD::SEXTLOAD:
7859     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7860   case ISD::ZEXTLOAD:
7861     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7862   case ISD::EXTLOAD:
7863     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7864   case ISD::NON_EXTLOAD:
7865     return Op;
7866   }
7867 
7868   llvm_unreachable("invalid ext type");
7869 }
7870 
7871 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7872   SelectionDAG &DAG = DCI.DAG;
7873   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7874     return SDValue();
7875 
7876   // FIXME: Constant loads should all be marked invariant.
7877   unsigned AS = Ld->getAddressSpace();
7878   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7879       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7880       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7881     return SDValue();
7882 
7883   // Don't do this early, since it may interfere with adjacent load merging for
7884   // illegal types. We can avoid losing alignment information for exotic types
7885   // pre-legalize.
7886   EVT MemVT = Ld->getMemoryVT();
7887   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7888       MemVT.getSizeInBits() >= 32)
7889     return SDValue();
7890 
7891   SDLoc SL(Ld);
7892 
7893   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7894          "unexpected vector extload");
7895 
7896   // TODO: Drop only high part of range.
7897   SDValue Ptr = Ld->getBasePtr();
7898   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7899                                 MVT::i32, SL, Ld->getChain(), Ptr,
7900                                 Ld->getOffset(),
7901                                 Ld->getPointerInfo(), MVT::i32,
7902                                 Ld->getAlignment(),
7903                                 Ld->getMemOperand()->getFlags(),
7904                                 Ld->getAAInfo(),
7905                                 nullptr); // Drop ranges
7906 
7907   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7908   if (MemVT.isFloatingPoint()) {
7909     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7910            "unexpected fp extload");
7911     TruncVT = MemVT.changeTypeToInteger();
7912   }
7913 
7914   SDValue Cvt = NewLoad;
7915   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7916     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7917                       DAG.getValueType(TruncVT));
7918   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7919              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7920     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7921   } else {
7922     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7923   }
7924 
7925   EVT VT = Ld->getValueType(0);
7926   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7927 
7928   DCI.AddToWorklist(Cvt.getNode());
7929 
7930   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7931   // the appropriate extension from the 32-bit load.
7932   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7933   DCI.AddToWorklist(Cvt.getNode());
7934 
7935   // Handle conversion back to floating point if necessary.
7936   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7937 
7938   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7939 }
7940 
7941 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7942   SDLoc DL(Op);
7943   LoadSDNode *Load = cast<LoadSDNode>(Op);
7944   ISD::LoadExtType ExtType = Load->getExtensionType();
7945   EVT MemVT = Load->getMemoryVT();
7946 
7947   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7948     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7949       return SDValue();
7950 
7951     // FIXME: Copied from PPC
7952     // First, load into 32 bits, then truncate to 1 bit.
7953 
7954     SDValue Chain = Load->getChain();
7955     SDValue BasePtr = Load->getBasePtr();
7956     MachineMemOperand *MMO = Load->getMemOperand();
7957 
7958     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7959 
7960     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7961                                    BasePtr, RealMemVT, MMO);
7962 
7963     if (!MemVT.isVector()) {
7964       SDValue Ops[] = {
7965         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7966         NewLD.getValue(1)
7967       };
7968 
7969       return DAG.getMergeValues(Ops, DL);
7970     }
7971 
7972     SmallVector<SDValue, 3> Elts;
7973     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7974       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7975                                 DAG.getConstant(I, DL, MVT::i32));
7976 
7977       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7978     }
7979 
7980     SDValue Ops[] = {
7981       DAG.getBuildVector(MemVT, DL, Elts),
7982       NewLD.getValue(1)
7983     };
7984 
7985     return DAG.getMergeValues(Ops, DL);
7986   }
7987 
7988   if (!MemVT.isVector())
7989     return SDValue();
7990 
7991   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7992          "Custom lowering for non-i32 vectors hasn't been implemented.");
7993 
7994   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7995                                       MemVT, *Load->getMemOperand())) {
7996     SDValue Ops[2];
7997     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7998     return DAG.getMergeValues(Ops, DL);
7999   }
8000 
8001   unsigned Alignment = Load->getAlignment();
8002   unsigned AS = Load->getAddressSpace();
8003   if (Subtarget->hasLDSMisalignedBug() &&
8004       AS == AMDGPUAS::FLAT_ADDRESS &&
8005       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8006     return SplitVectorLoad(Op, DAG);
8007   }
8008 
8009   MachineFunction &MF = DAG.getMachineFunction();
8010   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8011   // If there is a possibilty that flat instruction access scratch memory
8012   // then we need to use the same legalization rules we use for private.
8013   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8014       !Subtarget->hasMultiDwordFlatScratchAddressing())
8015     AS = MFI->hasFlatScratchInit() ?
8016          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8017 
8018   unsigned NumElements = MemVT.getVectorNumElements();
8019 
8020   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8021       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8022     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8023       if (MemVT.isPow2VectorType())
8024         return SDValue();
8025       if (NumElements == 3)
8026         return WidenVectorLoad(Op, DAG);
8027       return SplitVectorLoad(Op, DAG);
8028     }
8029     // Non-uniform loads will be selected to MUBUF instructions, so they
8030     // have the same legalization requirements as global and private
8031     // loads.
8032     //
8033   }
8034 
8035   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8036       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8037       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8038     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8039         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8040         Alignment >= 4 && NumElements < 32) {
8041       if (MemVT.isPow2VectorType())
8042         return SDValue();
8043       if (NumElements == 3)
8044         return WidenVectorLoad(Op, DAG);
8045       return SplitVectorLoad(Op, DAG);
8046     }
8047     // Non-uniform loads will be selected to MUBUF instructions, so they
8048     // have the same legalization requirements as global and private
8049     // loads.
8050     //
8051   }
8052   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8053       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8054       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8055       AS == AMDGPUAS::FLAT_ADDRESS) {
8056     if (NumElements > 4)
8057       return SplitVectorLoad(Op, DAG);
8058     // v3 loads not supported on SI.
8059     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8060       return WidenVectorLoad(Op, DAG);
8061     // v3 and v4 loads are supported for private and global memory.
8062     return SDValue();
8063   }
8064   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8065     // Depending on the setting of the private_element_size field in the
8066     // resource descriptor, we can only make private accesses up to a certain
8067     // size.
8068     switch (Subtarget->getMaxPrivateElementSize()) {
8069     case 4: {
8070       SDValue Ops[2];
8071       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8072       return DAG.getMergeValues(Ops, DL);
8073     }
8074     case 8:
8075       if (NumElements > 2)
8076         return SplitVectorLoad(Op, DAG);
8077       return SDValue();
8078     case 16:
8079       // Same as global/flat
8080       if (NumElements > 4)
8081         return SplitVectorLoad(Op, DAG);
8082       // v3 loads not supported on SI.
8083       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8084         return WidenVectorLoad(Op, DAG);
8085       return SDValue();
8086     default:
8087       llvm_unreachable("unsupported private_element_size");
8088     }
8089   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8090     // Use ds_read_b128 or ds_read_b96 when possible.
8091     if (Subtarget->hasDS96AndDS128() &&
8092         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8093          MemVT.getStoreSize() == 12) &&
8094         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8095                                            Load->getAlign()))
8096       return SDValue();
8097 
8098     if (NumElements > 2)
8099       return SplitVectorLoad(Op, DAG);
8100 
8101     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8102     // address is negative, then the instruction is incorrectly treated as
8103     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8104     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8105     // load later in the SILoadStoreOptimizer.
8106     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8107         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8108         Load->getAlignment() < 8) {
8109       return SplitVectorLoad(Op, DAG);
8110     }
8111   }
8112   return SDValue();
8113 }
8114 
8115 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8116   EVT VT = Op.getValueType();
8117   assert(VT.getSizeInBits() == 64);
8118 
8119   SDLoc DL(Op);
8120   SDValue Cond = Op.getOperand(0);
8121 
8122   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8123   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8124 
8125   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8126   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8127 
8128   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8129   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8130 
8131   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8132 
8133   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8134   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8135 
8136   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8137 
8138   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8139   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8140 }
8141 
8142 // Catch division cases where we can use shortcuts with rcp and rsq
8143 // instructions.
8144 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8145                                               SelectionDAG &DAG) const {
8146   SDLoc SL(Op);
8147   SDValue LHS = Op.getOperand(0);
8148   SDValue RHS = Op.getOperand(1);
8149   EVT VT = Op.getValueType();
8150   const SDNodeFlags Flags = Op->getFlags();
8151 
8152   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
8153                             Flags.hasApproximateFuncs();
8154 
8155   // Without !fpmath accuracy information, we can't do more because we don't
8156   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8157   if (!AllowInaccurateRcp)
8158     return SDValue();
8159 
8160   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8161     if (CLHS->isExactlyValue(1.0)) {
8162       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8163       // the CI documentation has a worst case error of 1 ulp.
8164       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8165       // use it as long as we aren't trying to use denormals.
8166       //
8167       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8168 
8169       // 1.0 / sqrt(x) -> rsq(x)
8170 
8171       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8172       // error seems really high at 2^29 ULP.
8173       if (RHS.getOpcode() == ISD::FSQRT)
8174         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8175 
8176       // 1.0 / x -> rcp(x)
8177       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8178     }
8179 
8180     // Same as for 1.0, but expand the sign out of the constant.
8181     if (CLHS->isExactlyValue(-1.0)) {
8182       // -1.0 / x -> rcp (fneg x)
8183       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8184       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8185     }
8186   }
8187 
8188   // Turn into multiply by the reciprocal.
8189   // x / y -> x * (1.0 / y)
8190   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8191   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8192 }
8193 
8194 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8195                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8196                           SDNodeFlags Flags) {
8197   if (GlueChain->getNumValues() <= 1) {
8198     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8199   }
8200 
8201   assert(GlueChain->getNumValues() == 3);
8202 
8203   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8204   switch (Opcode) {
8205   default: llvm_unreachable("no chain equivalent for opcode");
8206   case ISD::FMUL:
8207     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8208     break;
8209   }
8210 
8211   return DAG.getNode(Opcode, SL, VTList,
8212                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8213                      Flags);
8214 }
8215 
8216 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8217                            EVT VT, SDValue A, SDValue B, SDValue C,
8218                            SDValue GlueChain, SDNodeFlags Flags) {
8219   if (GlueChain->getNumValues() <= 1) {
8220     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8221   }
8222 
8223   assert(GlueChain->getNumValues() == 3);
8224 
8225   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8226   switch (Opcode) {
8227   default: llvm_unreachable("no chain equivalent for opcode");
8228   case ISD::FMA:
8229     Opcode = AMDGPUISD::FMA_W_CHAIN;
8230     break;
8231   }
8232 
8233   return DAG.getNode(Opcode, SL, VTList,
8234                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8235                      Flags);
8236 }
8237 
8238 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8239   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8240     return FastLowered;
8241 
8242   SDLoc SL(Op);
8243   SDValue Src0 = Op.getOperand(0);
8244   SDValue Src1 = Op.getOperand(1);
8245 
8246   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8247   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8248 
8249   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8250   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8251 
8252   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8253   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8254 
8255   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8256 }
8257 
8258 // Faster 2.5 ULP division that does not support denormals.
8259 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8260   SDLoc SL(Op);
8261   SDValue LHS = Op.getOperand(1);
8262   SDValue RHS = Op.getOperand(2);
8263 
8264   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8265 
8266   const APFloat K0Val(BitsToFloat(0x6f800000));
8267   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8268 
8269   const APFloat K1Val(BitsToFloat(0x2f800000));
8270   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8271 
8272   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8273 
8274   EVT SetCCVT =
8275     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8276 
8277   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8278 
8279   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8280 
8281   // TODO: Should this propagate fast-math-flags?
8282   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8283 
8284   // rcp does not support denormals.
8285   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8286 
8287   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8288 
8289   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8290 }
8291 
8292 // Returns immediate value for setting the F32 denorm mode when using the
8293 // S_DENORM_MODE instruction.
8294 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8295                                           const SDLoc &SL, const GCNSubtarget *ST) {
8296   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8297   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8298                                 ? FP_DENORM_FLUSH_NONE
8299                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8300 
8301   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8302   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8303 }
8304 
8305 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8306   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8307     return FastLowered;
8308 
8309   // The selection matcher assumes anything with a chain selecting to a
8310   // mayRaiseFPException machine instruction. Since we're introducing a chain
8311   // here, we need to explicitly report nofpexcept for the regular fdiv
8312   // lowering.
8313   SDNodeFlags Flags = Op->getFlags();
8314   Flags.setNoFPExcept(true);
8315 
8316   SDLoc SL(Op);
8317   SDValue LHS = Op.getOperand(0);
8318   SDValue RHS = Op.getOperand(1);
8319 
8320   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8321 
8322   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8323 
8324   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8325                                           {RHS, RHS, LHS}, Flags);
8326   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8327                                         {LHS, RHS, LHS}, Flags);
8328 
8329   // Denominator is scaled to not be denormal, so using rcp is ok.
8330   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8331                                   DenominatorScaled, Flags);
8332   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8333                                      DenominatorScaled, Flags);
8334 
8335   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8336                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8337                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8338   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8339 
8340   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8341 
8342   if (!HasFP32Denormals) {
8343     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8344     // lowering. The chain dependence is insufficient, and we need glue. We do
8345     // not need the glue variants in a strictfp function.
8346 
8347     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8348 
8349     SDNode *EnableDenorm;
8350     if (Subtarget->hasDenormModeInst()) {
8351       const SDValue EnableDenormValue =
8352           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8353 
8354       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8355                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8356     } else {
8357       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8358                                                         SL, MVT::i32);
8359       EnableDenorm =
8360           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8361                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8362     }
8363 
8364     SDValue Ops[3] = {
8365       NegDivScale0,
8366       SDValue(EnableDenorm, 0),
8367       SDValue(EnableDenorm, 1)
8368     };
8369 
8370     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8371   }
8372 
8373   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8374                              ApproxRcp, One, NegDivScale0, Flags);
8375 
8376   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8377                              ApproxRcp, Fma0, Flags);
8378 
8379   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8380                            Fma1, Fma1, Flags);
8381 
8382   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8383                              NumeratorScaled, Mul, Flags);
8384 
8385   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8386                              Fma2, Fma1, Mul, Fma2, Flags);
8387 
8388   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8389                              NumeratorScaled, Fma3, Flags);
8390 
8391   if (!HasFP32Denormals) {
8392     SDNode *DisableDenorm;
8393     if (Subtarget->hasDenormModeInst()) {
8394       const SDValue DisableDenormValue =
8395           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8396 
8397       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8398                                   Fma4.getValue(1), DisableDenormValue,
8399                                   Fma4.getValue(2)).getNode();
8400     } else {
8401       const SDValue DisableDenormValue =
8402           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8403 
8404       DisableDenorm = DAG.getMachineNode(
8405           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8406           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8407     }
8408 
8409     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8410                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8411     DAG.setRoot(OutputChain);
8412   }
8413 
8414   SDValue Scale = NumeratorScaled.getValue(1);
8415   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8416                              {Fma4, Fma1, Fma3, Scale}, Flags);
8417 
8418   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8419 }
8420 
8421 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8422   if (DAG.getTarget().Options.UnsafeFPMath)
8423     return lowerFastUnsafeFDIV(Op, DAG);
8424 
8425   SDLoc SL(Op);
8426   SDValue X = Op.getOperand(0);
8427   SDValue Y = Op.getOperand(1);
8428 
8429   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8430 
8431   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8432 
8433   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8434 
8435   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8436 
8437   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8438 
8439   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8440 
8441   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8442 
8443   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8444 
8445   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8446 
8447   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8448   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8449 
8450   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8451                              NegDivScale0, Mul, DivScale1);
8452 
8453   SDValue Scale;
8454 
8455   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8456     // Workaround a hardware bug on SI where the condition output from div_scale
8457     // is not usable.
8458 
8459     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8460 
8461     // Figure out if the scale to use for div_fmas.
8462     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8463     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8464     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8465     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8466 
8467     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8468     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8469 
8470     SDValue Scale0Hi
8471       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8472     SDValue Scale1Hi
8473       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8474 
8475     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8476     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8477     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8478   } else {
8479     Scale = DivScale1.getValue(1);
8480   }
8481 
8482   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8483                              Fma4, Fma3, Mul, Scale);
8484 
8485   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8486 }
8487 
8488 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8489   EVT VT = Op.getValueType();
8490 
8491   if (VT == MVT::f32)
8492     return LowerFDIV32(Op, DAG);
8493 
8494   if (VT == MVT::f64)
8495     return LowerFDIV64(Op, DAG);
8496 
8497   if (VT == MVT::f16)
8498     return LowerFDIV16(Op, DAG);
8499 
8500   llvm_unreachable("Unexpected type for fdiv");
8501 }
8502 
8503 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8504   SDLoc DL(Op);
8505   StoreSDNode *Store = cast<StoreSDNode>(Op);
8506   EVT VT = Store->getMemoryVT();
8507 
8508   if (VT == MVT::i1) {
8509     return DAG.getTruncStore(Store->getChain(), DL,
8510        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8511        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8512   }
8513 
8514   assert(VT.isVector() &&
8515          Store->getValue().getValueType().getScalarType() == MVT::i32);
8516 
8517   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8518                                       VT, *Store->getMemOperand())) {
8519     return expandUnalignedStore(Store, DAG);
8520   }
8521 
8522   unsigned AS = Store->getAddressSpace();
8523   if (Subtarget->hasLDSMisalignedBug() &&
8524       AS == AMDGPUAS::FLAT_ADDRESS &&
8525       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8526     return SplitVectorStore(Op, DAG);
8527   }
8528 
8529   MachineFunction &MF = DAG.getMachineFunction();
8530   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8531   // If there is a possibilty that flat instruction access scratch memory
8532   // then we need to use the same legalization rules we use for private.
8533   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8534       !Subtarget->hasMultiDwordFlatScratchAddressing())
8535     AS = MFI->hasFlatScratchInit() ?
8536          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8537 
8538   unsigned NumElements = VT.getVectorNumElements();
8539   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8540       AS == AMDGPUAS::FLAT_ADDRESS) {
8541     if (NumElements > 4)
8542       return SplitVectorStore(Op, DAG);
8543     // v3 stores not supported on SI.
8544     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8545       return SplitVectorStore(Op, DAG);
8546     return SDValue();
8547   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8548     switch (Subtarget->getMaxPrivateElementSize()) {
8549     case 4:
8550       return scalarizeVectorStore(Store, DAG);
8551     case 8:
8552       if (NumElements > 2)
8553         return SplitVectorStore(Op, DAG);
8554       return SDValue();
8555     case 16:
8556       if (NumElements > 4 || NumElements == 3)
8557         return SplitVectorStore(Op, DAG);
8558       return SDValue();
8559     default:
8560       llvm_unreachable("unsupported private_element_size");
8561     }
8562   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8563     // Use ds_write_b128 or ds_write_b96 when possible.
8564     if (Subtarget->hasDS96AndDS128() &&
8565         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8566          (VT.getStoreSize() == 12)) &&
8567         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8568                                            Store->getAlign()))
8569       return SDValue();
8570 
8571     if (NumElements > 2)
8572       return SplitVectorStore(Op, DAG);
8573 
8574     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8575     // address is negative, then the instruction is incorrectly treated as
8576     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8577     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8578     // store later in the SILoadStoreOptimizer.
8579     if (!Subtarget->hasUsableDSOffset() &&
8580         NumElements == 2 && VT.getStoreSize() == 8 &&
8581         Store->getAlignment() < 8) {
8582       return SplitVectorStore(Op, DAG);
8583     }
8584 
8585     return SDValue();
8586   } else {
8587     llvm_unreachable("unhandled address space");
8588   }
8589 }
8590 
8591 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8592   SDLoc DL(Op);
8593   EVT VT = Op.getValueType();
8594   SDValue Arg = Op.getOperand(0);
8595   SDValue TrigVal;
8596 
8597   // Propagate fast-math flags so that the multiply we introduce can be folded
8598   // if Arg is already the result of a multiply by constant.
8599   auto Flags = Op->getFlags();
8600 
8601   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8602 
8603   if (Subtarget->hasTrigReducedRange()) {
8604     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8605     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8606   } else {
8607     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8608   }
8609 
8610   switch (Op.getOpcode()) {
8611   case ISD::FCOS:
8612     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8613   case ISD::FSIN:
8614     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8615   default:
8616     llvm_unreachable("Wrong trig opcode");
8617   }
8618 }
8619 
8620 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8621   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8622   assert(AtomicNode->isCompareAndSwap());
8623   unsigned AS = AtomicNode->getAddressSpace();
8624 
8625   // No custom lowering required for local address space
8626   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8627     return Op;
8628 
8629   // Non-local address space requires custom lowering for atomic compare
8630   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8631   SDLoc DL(Op);
8632   SDValue ChainIn = Op.getOperand(0);
8633   SDValue Addr = Op.getOperand(1);
8634   SDValue Old = Op.getOperand(2);
8635   SDValue New = Op.getOperand(3);
8636   EVT VT = Op.getValueType();
8637   MVT SimpleVT = VT.getSimpleVT();
8638   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8639 
8640   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8641   SDValue Ops[] = { ChainIn, Addr, NewOld };
8642 
8643   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8644                                  Ops, VT, AtomicNode->getMemOperand());
8645 }
8646 
8647 //===----------------------------------------------------------------------===//
8648 // Custom DAG optimizations
8649 //===----------------------------------------------------------------------===//
8650 
8651 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8652                                                      DAGCombinerInfo &DCI) const {
8653   EVT VT = N->getValueType(0);
8654   EVT ScalarVT = VT.getScalarType();
8655   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8656     return SDValue();
8657 
8658   SelectionDAG &DAG = DCI.DAG;
8659   SDLoc DL(N);
8660 
8661   SDValue Src = N->getOperand(0);
8662   EVT SrcVT = Src.getValueType();
8663 
8664   // TODO: We could try to match extracting the higher bytes, which would be
8665   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8666   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8667   // about in practice.
8668   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8669     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8670       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8671       DCI.AddToWorklist(Cvt.getNode());
8672 
8673       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8674       if (ScalarVT != MVT::f32) {
8675         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8676                           DAG.getTargetConstant(0, DL, MVT::i32));
8677       }
8678       return Cvt;
8679     }
8680   }
8681 
8682   return SDValue();
8683 }
8684 
8685 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8686 
8687 // This is a variant of
8688 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8689 //
8690 // The normal DAG combiner will do this, but only if the add has one use since
8691 // that would increase the number of instructions.
8692 //
8693 // This prevents us from seeing a constant offset that can be folded into a
8694 // memory instruction's addressing mode. If we know the resulting add offset of
8695 // a pointer can be folded into an addressing offset, we can replace the pointer
8696 // operand with the add of new constant offset. This eliminates one of the uses,
8697 // and may allow the remaining use to also be simplified.
8698 //
8699 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8700                                                unsigned AddrSpace,
8701                                                EVT MemVT,
8702                                                DAGCombinerInfo &DCI) const {
8703   SDValue N0 = N->getOperand(0);
8704   SDValue N1 = N->getOperand(1);
8705 
8706   // We only do this to handle cases where it's profitable when there are
8707   // multiple uses of the add, so defer to the standard combine.
8708   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8709       N0->hasOneUse())
8710     return SDValue();
8711 
8712   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8713   if (!CN1)
8714     return SDValue();
8715 
8716   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8717   if (!CAdd)
8718     return SDValue();
8719 
8720   // If the resulting offset is too large, we can't fold it into the addressing
8721   // mode offset.
8722   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8723   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8724 
8725   AddrMode AM;
8726   AM.HasBaseReg = true;
8727   AM.BaseOffs = Offset.getSExtValue();
8728   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8729     return SDValue();
8730 
8731   SelectionDAG &DAG = DCI.DAG;
8732   SDLoc SL(N);
8733   EVT VT = N->getValueType(0);
8734 
8735   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8736   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8737 
8738   SDNodeFlags Flags;
8739   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8740                           (N0.getOpcode() == ISD::OR ||
8741                            N0->getFlags().hasNoUnsignedWrap()));
8742 
8743   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8744 }
8745 
8746 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8747 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8748 /// specific intrinsic, but they all place the pointer operand first.
8749 static unsigned getBasePtrIndex(const MemSDNode *N) {
8750   switch (N->getOpcode()) {
8751   case ISD::STORE:
8752   case ISD::INTRINSIC_W_CHAIN:
8753   case ISD::INTRINSIC_VOID:
8754     return 2;
8755   default:
8756     return 1;
8757   }
8758 }
8759 
8760 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8761                                                   DAGCombinerInfo &DCI) const {
8762   SelectionDAG &DAG = DCI.DAG;
8763   SDLoc SL(N);
8764 
8765   unsigned PtrIdx = getBasePtrIndex(N);
8766   SDValue Ptr = N->getOperand(PtrIdx);
8767 
8768   // TODO: We could also do this for multiplies.
8769   if (Ptr.getOpcode() == ISD::SHL) {
8770     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8771                                           N->getMemoryVT(), DCI);
8772     if (NewPtr) {
8773       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8774 
8775       NewOps[PtrIdx] = NewPtr;
8776       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8777     }
8778   }
8779 
8780   return SDValue();
8781 }
8782 
8783 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8784   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8785          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8786          (Opc == ISD::XOR && Val == 0);
8787 }
8788 
8789 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8790 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8791 // integer combine opportunities since most 64-bit operations are decomposed
8792 // this way.  TODO: We won't want this for SALU especially if it is an inline
8793 // immediate.
8794 SDValue SITargetLowering::splitBinaryBitConstantOp(
8795   DAGCombinerInfo &DCI,
8796   const SDLoc &SL,
8797   unsigned Opc, SDValue LHS,
8798   const ConstantSDNode *CRHS) const {
8799   uint64_t Val = CRHS->getZExtValue();
8800   uint32_t ValLo = Lo_32(Val);
8801   uint32_t ValHi = Hi_32(Val);
8802   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8803 
8804     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8805          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8806         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8807     // If we need to materialize a 64-bit immediate, it will be split up later
8808     // anyway. Avoid creating the harder to understand 64-bit immediate
8809     // materialization.
8810     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8811   }
8812 
8813   return SDValue();
8814 }
8815 
8816 // Returns true if argument is a boolean value which is not serialized into
8817 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8818 static bool isBoolSGPR(SDValue V) {
8819   if (V.getValueType() != MVT::i1)
8820     return false;
8821   switch (V.getOpcode()) {
8822   default: break;
8823   case ISD::SETCC:
8824   case ISD::AND:
8825   case ISD::OR:
8826   case ISD::XOR:
8827   case AMDGPUISD::FP_CLASS:
8828     return true;
8829   }
8830   return false;
8831 }
8832 
8833 // If a constant has all zeroes or all ones within each byte return it.
8834 // Otherwise return 0.
8835 static uint32_t getConstantPermuteMask(uint32_t C) {
8836   // 0xff for any zero byte in the mask
8837   uint32_t ZeroByteMask = 0;
8838   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8839   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8840   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8841   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8842   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8843   if ((NonZeroByteMask & C) != NonZeroByteMask)
8844     return 0; // Partial bytes selected.
8845   return C;
8846 }
8847 
8848 // Check if a node selects whole bytes from its operand 0 starting at a byte
8849 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8850 // or -1 if not succeeded.
8851 // Note byte select encoding:
8852 // value 0-3 selects corresponding source byte;
8853 // value 0xc selects zero;
8854 // value 0xff selects 0xff.
8855 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8856   assert(V.getValueSizeInBits() == 32);
8857 
8858   if (V.getNumOperands() != 2)
8859     return ~0;
8860 
8861   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8862   if (!N1)
8863     return ~0;
8864 
8865   uint32_t C = N1->getZExtValue();
8866 
8867   switch (V.getOpcode()) {
8868   default:
8869     break;
8870   case ISD::AND:
8871     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8872       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8873     }
8874     break;
8875 
8876   case ISD::OR:
8877     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8878       return (0x03020100 & ~ConstMask) | ConstMask;
8879     }
8880     break;
8881 
8882   case ISD::SHL:
8883     if (C % 8)
8884       return ~0;
8885 
8886     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8887 
8888   case ISD::SRL:
8889     if (C % 8)
8890       return ~0;
8891 
8892     return uint32_t(0x0c0c0c0c03020100ull >> C);
8893   }
8894 
8895   return ~0;
8896 }
8897 
8898 SDValue SITargetLowering::performAndCombine(SDNode *N,
8899                                             DAGCombinerInfo &DCI) const {
8900   if (DCI.isBeforeLegalize())
8901     return SDValue();
8902 
8903   SelectionDAG &DAG = DCI.DAG;
8904   EVT VT = N->getValueType(0);
8905   SDValue LHS = N->getOperand(0);
8906   SDValue RHS = N->getOperand(1);
8907 
8908 
8909   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8910   if (VT == MVT::i64 && CRHS) {
8911     if (SDValue Split
8912         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8913       return Split;
8914   }
8915 
8916   if (CRHS && VT == MVT::i32) {
8917     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8918     // nb = number of trailing zeroes in mask
8919     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8920     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8921     uint64_t Mask = CRHS->getZExtValue();
8922     unsigned Bits = countPopulation(Mask);
8923     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8924         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8925       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8926         unsigned Shift = CShift->getZExtValue();
8927         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8928         unsigned Offset = NB + Shift;
8929         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8930           SDLoc SL(N);
8931           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8932                                     LHS->getOperand(0),
8933                                     DAG.getConstant(Offset, SL, MVT::i32),
8934                                     DAG.getConstant(Bits, SL, MVT::i32));
8935           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8936           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8937                                     DAG.getValueType(NarrowVT));
8938           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8939                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8940           return Shl;
8941         }
8942       }
8943     }
8944 
8945     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8946     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8947         isa<ConstantSDNode>(LHS.getOperand(2))) {
8948       uint32_t Sel = getConstantPermuteMask(Mask);
8949       if (!Sel)
8950         return SDValue();
8951 
8952       // Select 0xc for all zero bytes
8953       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8954       SDLoc DL(N);
8955       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8956                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8957     }
8958   }
8959 
8960   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8961   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8962   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8963     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8964     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8965 
8966     SDValue X = LHS.getOperand(0);
8967     SDValue Y = RHS.getOperand(0);
8968     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8969       return SDValue();
8970 
8971     if (LCC == ISD::SETO) {
8972       if (X != LHS.getOperand(1))
8973         return SDValue();
8974 
8975       if (RCC == ISD::SETUNE) {
8976         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8977         if (!C1 || !C1->isInfinity() || C1->isNegative())
8978           return SDValue();
8979 
8980         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8981                               SIInstrFlags::N_SUBNORMAL |
8982                               SIInstrFlags::N_ZERO |
8983                               SIInstrFlags::P_ZERO |
8984                               SIInstrFlags::P_SUBNORMAL |
8985                               SIInstrFlags::P_NORMAL;
8986 
8987         static_assert(((~(SIInstrFlags::S_NAN |
8988                           SIInstrFlags::Q_NAN |
8989                           SIInstrFlags::N_INFINITY |
8990                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8991                       "mask not equal");
8992 
8993         SDLoc DL(N);
8994         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8995                            X, DAG.getConstant(Mask, DL, MVT::i32));
8996       }
8997     }
8998   }
8999 
9000   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9001     std::swap(LHS, RHS);
9002 
9003   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9004       RHS.hasOneUse()) {
9005     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9006     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9007     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9008     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9009     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9010         (RHS.getOperand(0) == LHS.getOperand(0) &&
9011          LHS.getOperand(0) == LHS.getOperand(1))) {
9012       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9013       unsigned NewMask = LCC == ISD::SETO ?
9014         Mask->getZExtValue() & ~OrdMask :
9015         Mask->getZExtValue() & OrdMask;
9016 
9017       SDLoc DL(N);
9018       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9019                          DAG.getConstant(NewMask, DL, MVT::i32));
9020     }
9021   }
9022 
9023   if (VT == MVT::i32 &&
9024       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9025     // and x, (sext cc from i1) => select cc, x, 0
9026     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9027       std::swap(LHS, RHS);
9028     if (isBoolSGPR(RHS.getOperand(0)))
9029       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9030                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9031   }
9032 
9033   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9034   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9035   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9036       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9037     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9038     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9039     if (LHSMask != ~0u && RHSMask != ~0u) {
9040       // Canonicalize the expression in an attempt to have fewer unique masks
9041       // and therefore fewer registers used to hold the masks.
9042       if (LHSMask > RHSMask) {
9043         std::swap(LHSMask, RHSMask);
9044         std::swap(LHS, RHS);
9045       }
9046 
9047       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9048       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9049       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9050       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9051 
9052       // Check of we need to combine values from two sources within a byte.
9053       if (!(LHSUsedLanes & RHSUsedLanes) &&
9054           // If we select high and lower word keep it for SDWA.
9055           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9056           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9057         // Each byte in each mask is either selector mask 0-3, or has higher
9058         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9059         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9060         // mask which is not 0xff wins. By anding both masks we have a correct
9061         // result except that 0x0c shall be corrected to give 0x0c only.
9062         uint32_t Mask = LHSMask & RHSMask;
9063         for (unsigned I = 0; I < 32; I += 8) {
9064           uint32_t ByteSel = 0xff << I;
9065           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9066             Mask &= (0x0c << I) & 0xffffffff;
9067         }
9068 
9069         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9070         // or 0x0c.
9071         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9072         SDLoc DL(N);
9073 
9074         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9075                            LHS.getOperand(0), RHS.getOperand(0),
9076                            DAG.getConstant(Sel, DL, MVT::i32));
9077       }
9078     }
9079   }
9080 
9081   return SDValue();
9082 }
9083 
9084 SDValue SITargetLowering::performOrCombine(SDNode *N,
9085                                            DAGCombinerInfo &DCI) const {
9086   SelectionDAG &DAG = DCI.DAG;
9087   SDValue LHS = N->getOperand(0);
9088   SDValue RHS = N->getOperand(1);
9089 
9090   EVT VT = N->getValueType(0);
9091   if (VT == MVT::i1) {
9092     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9093     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9094         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9095       SDValue Src = LHS.getOperand(0);
9096       if (Src != RHS.getOperand(0))
9097         return SDValue();
9098 
9099       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9100       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9101       if (!CLHS || !CRHS)
9102         return SDValue();
9103 
9104       // Only 10 bits are used.
9105       static const uint32_t MaxMask = 0x3ff;
9106 
9107       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9108       SDLoc DL(N);
9109       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9110                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9111     }
9112 
9113     return SDValue();
9114   }
9115 
9116   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9117   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9118       LHS.getOpcode() == AMDGPUISD::PERM &&
9119       isa<ConstantSDNode>(LHS.getOperand(2))) {
9120     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9121     if (!Sel)
9122       return SDValue();
9123 
9124     Sel |= LHS.getConstantOperandVal(2);
9125     SDLoc DL(N);
9126     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9127                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9128   }
9129 
9130   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9131   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9132   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9133       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9134     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9135     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9136     if (LHSMask != ~0u && RHSMask != ~0u) {
9137       // Canonicalize the expression in an attempt to have fewer unique masks
9138       // and therefore fewer registers used to hold the masks.
9139       if (LHSMask > RHSMask) {
9140         std::swap(LHSMask, RHSMask);
9141         std::swap(LHS, RHS);
9142       }
9143 
9144       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9145       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9146       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9147       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9148 
9149       // Check of we need to combine values from two sources within a byte.
9150       if (!(LHSUsedLanes & RHSUsedLanes) &&
9151           // If we select high and lower word keep it for SDWA.
9152           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9153           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9154         // Kill zero bytes selected by other mask. Zero value is 0xc.
9155         LHSMask &= ~RHSUsedLanes;
9156         RHSMask &= ~LHSUsedLanes;
9157         // Add 4 to each active LHS lane
9158         LHSMask |= LHSUsedLanes & 0x04040404;
9159         // Combine masks
9160         uint32_t Sel = LHSMask | RHSMask;
9161         SDLoc DL(N);
9162 
9163         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9164                            LHS.getOperand(0), RHS.getOperand(0),
9165                            DAG.getConstant(Sel, DL, MVT::i32));
9166       }
9167     }
9168   }
9169 
9170   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9171     return SDValue();
9172 
9173   // TODO: This could be a generic combine with a predicate for extracting the
9174   // high half of an integer being free.
9175 
9176   // (or i64:x, (zero_extend i32:y)) ->
9177   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9178   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9179       RHS.getOpcode() != ISD::ZERO_EXTEND)
9180     std::swap(LHS, RHS);
9181 
9182   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9183     SDValue ExtSrc = RHS.getOperand(0);
9184     EVT SrcVT = ExtSrc.getValueType();
9185     if (SrcVT == MVT::i32) {
9186       SDLoc SL(N);
9187       SDValue LowLHS, HiBits;
9188       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9189       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9190 
9191       DCI.AddToWorklist(LowOr.getNode());
9192       DCI.AddToWorklist(HiBits.getNode());
9193 
9194       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9195                                 LowOr, HiBits);
9196       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9197     }
9198   }
9199 
9200   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9201   if (CRHS) {
9202     if (SDValue Split
9203           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9204       return Split;
9205   }
9206 
9207   return SDValue();
9208 }
9209 
9210 SDValue SITargetLowering::performXorCombine(SDNode *N,
9211                                             DAGCombinerInfo &DCI) const {
9212   EVT VT = N->getValueType(0);
9213   if (VT != MVT::i64)
9214     return SDValue();
9215 
9216   SDValue LHS = N->getOperand(0);
9217   SDValue RHS = N->getOperand(1);
9218 
9219   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9220   if (CRHS) {
9221     if (SDValue Split
9222           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9223       return Split;
9224   }
9225 
9226   return SDValue();
9227 }
9228 
9229 // Instructions that will be lowered with a final instruction that zeros the
9230 // high result bits.
9231 // XXX - probably only need to list legal operations.
9232 static bool fp16SrcZerosHighBits(unsigned Opc) {
9233   switch (Opc) {
9234   case ISD::FADD:
9235   case ISD::FSUB:
9236   case ISD::FMUL:
9237   case ISD::FDIV:
9238   case ISD::FREM:
9239   case ISD::FMA:
9240   case ISD::FMAD:
9241   case ISD::FCANONICALIZE:
9242   case ISD::FP_ROUND:
9243   case ISD::UINT_TO_FP:
9244   case ISD::SINT_TO_FP:
9245   case ISD::FABS:
9246     // Fabs is lowered to a bit operation, but it's an and which will clear the
9247     // high bits anyway.
9248   case ISD::FSQRT:
9249   case ISD::FSIN:
9250   case ISD::FCOS:
9251   case ISD::FPOWI:
9252   case ISD::FPOW:
9253   case ISD::FLOG:
9254   case ISD::FLOG2:
9255   case ISD::FLOG10:
9256   case ISD::FEXP:
9257   case ISD::FEXP2:
9258   case ISD::FCEIL:
9259   case ISD::FTRUNC:
9260   case ISD::FRINT:
9261   case ISD::FNEARBYINT:
9262   case ISD::FROUND:
9263   case ISD::FFLOOR:
9264   case ISD::FMINNUM:
9265   case ISD::FMAXNUM:
9266   case AMDGPUISD::FRACT:
9267   case AMDGPUISD::CLAMP:
9268   case AMDGPUISD::COS_HW:
9269   case AMDGPUISD::SIN_HW:
9270   case AMDGPUISD::FMIN3:
9271   case AMDGPUISD::FMAX3:
9272   case AMDGPUISD::FMED3:
9273   case AMDGPUISD::FMAD_FTZ:
9274   case AMDGPUISD::RCP:
9275   case AMDGPUISD::RSQ:
9276   case AMDGPUISD::RCP_IFLAG:
9277   case AMDGPUISD::LDEXP:
9278     return true;
9279   default:
9280     // fcopysign, select and others may be lowered to 32-bit bit operations
9281     // which don't zero the high bits.
9282     return false;
9283   }
9284 }
9285 
9286 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9287                                                    DAGCombinerInfo &DCI) const {
9288   if (!Subtarget->has16BitInsts() ||
9289       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9290     return SDValue();
9291 
9292   EVT VT = N->getValueType(0);
9293   if (VT != MVT::i32)
9294     return SDValue();
9295 
9296   SDValue Src = N->getOperand(0);
9297   if (Src.getValueType() != MVT::i16)
9298     return SDValue();
9299 
9300   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9301   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9302   if (Src.getOpcode() == ISD::BITCAST) {
9303     SDValue BCSrc = Src.getOperand(0);
9304     if (BCSrc.getValueType() == MVT::f16 &&
9305         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9306       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9307   }
9308 
9309   return SDValue();
9310 }
9311 
9312 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9313                                                         DAGCombinerInfo &DCI)
9314                                                         const {
9315   SDValue Src = N->getOperand(0);
9316   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9317 
9318   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9319       VTSign->getVT() == MVT::i8) ||
9320       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9321       VTSign->getVT() == MVT::i16)) &&
9322       Src.hasOneUse()) {
9323     auto *M = cast<MemSDNode>(Src);
9324     SDValue Ops[] = {
9325       Src.getOperand(0), // Chain
9326       Src.getOperand(1), // rsrc
9327       Src.getOperand(2), // vindex
9328       Src.getOperand(3), // voffset
9329       Src.getOperand(4), // soffset
9330       Src.getOperand(5), // offset
9331       Src.getOperand(6),
9332       Src.getOperand(7)
9333     };
9334     // replace with BUFFER_LOAD_BYTE/SHORT
9335     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9336                                          Src.getOperand(0).getValueType());
9337     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9338                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9339     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9340                                                           ResList,
9341                                                           Ops, M->getMemoryVT(),
9342                                                           M->getMemOperand());
9343     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9344                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9345   }
9346   return SDValue();
9347 }
9348 
9349 SDValue SITargetLowering::performClassCombine(SDNode *N,
9350                                               DAGCombinerInfo &DCI) const {
9351   SelectionDAG &DAG = DCI.DAG;
9352   SDValue Mask = N->getOperand(1);
9353 
9354   // fp_class x, 0 -> false
9355   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9356     if (CMask->isNullValue())
9357       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9358   }
9359 
9360   if (N->getOperand(0).isUndef())
9361     return DAG.getUNDEF(MVT::i1);
9362 
9363   return SDValue();
9364 }
9365 
9366 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9367                                             DAGCombinerInfo &DCI) const {
9368   EVT VT = N->getValueType(0);
9369   SDValue N0 = N->getOperand(0);
9370 
9371   if (N0.isUndef())
9372     return N0;
9373 
9374   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9375                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9376     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9377                            N->getFlags());
9378   }
9379 
9380   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9381     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9382                            N0.getOperand(0), N->getFlags());
9383   }
9384 
9385   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9386 }
9387 
9388 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9389                                        unsigned MaxDepth) const {
9390   unsigned Opcode = Op.getOpcode();
9391   if (Opcode == ISD::FCANONICALIZE)
9392     return true;
9393 
9394   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9395     auto F = CFP->getValueAPF();
9396     if (F.isNaN() && F.isSignaling())
9397       return false;
9398     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9399   }
9400 
9401   // If source is a result of another standard FP operation it is already in
9402   // canonical form.
9403   if (MaxDepth == 0)
9404     return false;
9405 
9406   switch (Opcode) {
9407   // These will flush denorms if required.
9408   case ISD::FADD:
9409   case ISD::FSUB:
9410   case ISD::FMUL:
9411   case ISD::FCEIL:
9412   case ISD::FFLOOR:
9413   case ISD::FMA:
9414   case ISD::FMAD:
9415   case ISD::FSQRT:
9416   case ISD::FDIV:
9417   case ISD::FREM:
9418   case ISD::FP_ROUND:
9419   case ISD::FP_EXTEND:
9420   case AMDGPUISD::FMUL_LEGACY:
9421   case AMDGPUISD::FMAD_FTZ:
9422   case AMDGPUISD::RCP:
9423   case AMDGPUISD::RSQ:
9424   case AMDGPUISD::RSQ_CLAMP:
9425   case AMDGPUISD::RCP_LEGACY:
9426   case AMDGPUISD::RCP_IFLAG:
9427   case AMDGPUISD::DIV_SCALE:
9428   case AMDGPUISD::DIV_FMAS:
9429   case AMDGPUISD::DIV_FIXUP:
9430   case AMDGPUISD::FRACT:
9431   case AMDGPUISD::LDEXP:
9432   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9433   case AMDGPUISD::CVT_F32_UBYTE0:
9434   case AMDGPUISD::CVT_F32_UBYTE1:
9435   case AMDGPUISD::CVT_F32_UBYTE2:
9436   case AMDGPUISD::CVT_F32_UBYTE3:
9437     return true;
9438 
9439   // It can/will be lowered or combined as a bit operation.
9440   // Need to check their input recursively to handle.
9441   case ISD::FNEG:
9442   case ISD::FABS:
9443   case ISD::FCOPYSIGN:
9444     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9445 
9446   case ISD::FSIN:
9447   case ISD::FCOS:
9448   case ISD::FSINCOS:
9449     return Op.getValueType().getScalarType() != MVT::f16;
9450 
9451   case ISD::FMINNUM:
9452   case ISD::FMAXNUM:
9453   case ISD::FMINNUM_IEEE:
9454   case ISD::FMAXNUM_IEEE:
9455   case AMDGPUISD::CLAMP:
9456   case AMDGPUISD::FMED3:
9457   case AMDGPUISD::FMAX3:
9458   case AMDGPUISD::FMIN3: {
9459     // FIXME: Shouldn't treat the generic operations different based these.
9460     // However, we aren't really required to flush the result from
9461     // minnum/maxnum..
9462 
9463     // snans will be quieted, so we only need to worry about denormals.
9464     if (Subtarget->supportsMinMaxDenormModes() ||
9465         denormalsEnabledForType(DAG, Op.getValueType()))
9466       return true;
9467 
9468     // Flushing may be required.
9469     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9470     // targets need to check their input recursively.
9471 
9472     // FIXME: Does this apply with clamp? It's implemented with max.
9473     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9474       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9475         return false;
9476     }
9477 
9478     return true;
9479   }
9480   case ISD::SELECT: {
9481     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9482            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9483   }
9484   case ISD::BUILD_VECTOR: {
9485     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9486       SDValue SrcOp = Op.getOperand(i);
9487       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9488         return false;
9489     }
9490 
9491     return true;
9492   }
9493   case ISD::EXTRACT_VECTOR_ELT:
9494   case ISD::EXTRACT_SUBVECTOR: {
9495     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9496   }
9497   case ISD::INSERT_VECTOR_ELT: {
9498     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9499            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9500   }
9501   case ISD::UNDEF:
9502     // Could be anything.
9503     return false;
9504 
9505   case ISD::BITCAST: {
9506     // Hack round the mess we make when legalizing extract_vector_elt
9507     SDValue Src = Op.getOperand(0);
9508     if (Src.getValueType() == MVT::i16 &&
9509         Src.getOpcode() == ISD::TRUNCATE) {
9510       SDValue TruncSrc = Src.getOperand(0);
9511       if (TruncSrc.getValueType() == MVT::i32 &&
9512           TruncSrc.getOpcode() == ISD::BITCAST &&
9513           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9514         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9515       }
9516     }
9517 
9518     return false;
9519   }
9520   case ISD::INTRINSIC_WO_CHAIN: {
9521     unsigned IntrinsicID
9522       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9523     // TODO: Handle more intrinsics
9524     switch (IntrinsicID) {
9525     case Intrinsic::amdgcn_cvt_pkrtz:
9526     case Intrinsic::amdgcn_cubeid:
9527     case Intrinsic::amdgcn_frexp_mant:
9528     case Intrinsic::amdgcn_fdot2:
9529     case Intrinsic::amdgcn_rcp:
9530     case Intrinsic::amdgcn_rsq:
9531     case Intrinsic::amdgcn_rsq_clamp:
9532     case Intrinsic::amdgcn_rcp_legacy:
9533     case Intrinsic::amdgcn_rsq_legacy:
9534     case Intrinsic::amdgcn_trig_preop:
9535       return true;
9536     default:
9537       break;
9538     }
9539 
9540     LLVM_FALLTHROUGH;
9541   }
9542   default:
9543     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9544            DAG.isKnownNeverSNaN(Op);
9545   }
9546 
9547   llvm_unreachable("invalid operation");
9548 }
9549 
9550 // Constant fold canonicalize.
9551 SDValue SITargetLowering::getCanonicalConstantFP(
9552   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9553   // Flush denormals to 0 if not enabled.
9554   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9555     return DAG.getConstantFP(0.0, SL, VT);
9556 
9557   if (C.isNaN()) {
9558     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9559     if (C.isSignaling()) {
9560       // Quiet a signaling NaN.
9561       // FIXME: Is this supposed to preserve payload bits?
9562       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9563     }
9564 
9565     // Make sure it is the canonical NaN bitpattern.
9566     //
9567     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9568     // immediate?
9569     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9570       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9571   }
9572 
9573   // Already canonical.
9574   return DAG.getConstantFP(C, SL, VT);
9575 }
9576 
9577 static bool vectorEltWillFoldAway(SDValue Op) {
9578   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9579 }
9580 
9581 SDValue SITargetLowering::performFCanonicalizeCombine(
9582   SDNode *N,
9583   DAGCombinerInfo &DCI) const {
9584   SelectionDAG &DAG = DCI.DAG;
9585   SDValue N0 = N->getOperand(0);
9586   EVT VT = N->getValueType(0);
9587 
9588   // fcanonicalize undef -> qnan
9589   if (N0.isUndef()) {
9590     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9591     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9592   }
9593 
9594   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9595     EVT VT = N->getValueType(0);
9596     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9597   }
9598 
9599   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9600   //                                                   (fcanonicalize k)
9601   //
9602   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9603 
9604   // TODO: This could be better with wider vectors that will be split to v2f16,
9605   // and to consider uses since there aren't that many packed operations.
9606   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9607       isTypeLegal(MVT::v2f16)) {
9608     SDLoc SL(N);
9609     SDValue NewElts[2];
9610     SDValue Lo = N0.getOperand(0);
9611     SDValue Hi = N0.getOperand(1);
9612     EVT EltVT = Lo.getValueType();
9613 
9614     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9615       for (unsigned I = 0; I != 2; ++I) {
9616         SDValue Op = N0.getOperand(I);
9617         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9618           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9619                                               CFP->getValueAPF());
9620         } else if (Op.isUndef()) {
9621           // Handled below based on what the other operand is.
9622           NewElts[I] = Op;
9623         } else {
9624           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9625         }
9626       }
9627 
9628       // If one half is undef, and one is constant, perfer a splat vector rather
9629       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9630       // cheaper to use and may be free with a packed operation.
9631       if (NewElts[0].isUndef()) {
9632         if (isa<ConstantFPSDNode>(NewElts[1]))
9633           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9634             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9635       }
9636 
9637       if (NewElts[1].isUndef()) {
9638         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9639           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9640       }
9641 
9642       return DAG.getBuildVector(VT, SL, NewElts);
9643     }
9644   }
9645 
9646   unsigned SrcOpc = N0.getOpcode();
9647 
9648   // If it's free to do so, push canonicalizes further up the source, which may
9649   // find a canonical source.
9650   //
9651   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9652   // sNaNs.
9653   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9654     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9655     if (CRHS && N0.hasOneUse()) {
9656       SDLoc SL(N);
9657       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9658                                    N0.getOperand(0));
9659       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9660       DCI.AddToWorklist(Canon0.getNode());
9661 
9662       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9663     }
9664   }
9665 
9666   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9667 }
9668 
9669 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9670   switch (Opc) {
9671   case ISD::FMAXNUM:
9672   case ISD::FMAXNUM_IEEE:
9673     return AMDGPUISD::FMAX3;
9674   case ISD::SMAX:
9675     return AMDGPUISD::SMAX3;
9676   case ISD::UMAX:
9677     return AMDGPUISD::UMAX3;
9678   case ISD::FMINNUM:
9679   case ISD::FMINNUM_IEEE:
9680     return AMDGPUISD::FMIN3;
9681   case ISD::SMIN:
9682     return AMDGPUISD::SMIN3;
9683   case ISD::UMIN:
9684     return AMDGPUISD::UMIN3;
9685   default:
9686     llvm_unreachable("Not a min/max opcode");
9687   }
9688 }
9689 
9690 SDValue SITargetLowering::performIntMed3ImmCombine(
9691   SelectionDAG &DAG, const SDLoc &SL,
9692   SDValue Op0, SDValue Op1, bool Signed) const {
9693   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9694   if (!K1)
9695     return SDValue();
9696 
9697   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9698   if (!K0)
9699     return SDValue();
9700 
9701   if (Signed) {
9702     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9703       return SDValue();
9704   } else {
9705     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9706       return SDValue();
9707   }
9708 
9709   EVT VT = K0->getValueType(0);
9710   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9711   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9712     return DAG.getNode(Med3Opc, SL, VT,
9713                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9714   }
9715 
9716   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9717   MVT NVT = MVT::i32;
9718   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9719 
9720   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9721   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9722   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9723 
9724   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9725   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9726 }
9727 
9728 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9729   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9730     return C;
9731 
9732   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9733     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9734       return C;
9735   }
9736 
9737   return nullptr;
9738 }
9739 
9740 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9741                                                   const SDLoc &SL,
9742                                                   SDValue Op0,
9743                                                   SDValue Op1) const {
9744   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9745   if (!K1)
9746     return SDValue();
9747 
9748   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9749   if (!K0)
9750     return SDValue();
9751 
9752   // Ordered >= (although NaN inputs should have folded away by now).
9753   if (K0->getValueAPF() > K1->getValueAPF())
9754     return SDValue();
9755 
9756   const MachineFunction &MF = DAG.getMachineFunction();
9757   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9758 
9759   // TODO: Check IEEE bit enabled?
9760   EVT VT = Op0.getValueType();
9761   if (Info->getMode().DX10Clamp) {
9762     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9763     // hardware fmed3 behavior converting to a min.
9764     // FIXME: Should this be allowing -0.0?
9765     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9766       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9767   }
9768 
9769   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9770   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9771     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9772     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9773     // then give the other result, which is different from med3 with a NaN
9774     // input.
9775     SDValue Var = Op0.getOperand(0);
9776     if (!DAG.isKnownNeverSNaN(Var))
9777       return SDValue();
9778 
9779     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9780 
9781     if ((!K0->hasOneUse() ||
9782          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9783         (!K1->hasOneUse() ||
9784          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9785       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9786                          Var, SDValue(K0, 0), SDValue(K1, 0));
9787     }
9788   }
9789 
9790   return SDValue();
9791 }
9792 
9793 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9794                                                DAGCombinerInfo &DCI) const {
9795   SelectionDAG &DAG = DCI.DAG;
9796 
9797   EVT VT = N->getValueType(0);
9798   unsigned Opc = N->getOpcode();
9799   SDValue Op0 = N->getOperand(0);
9800   SDValue Op1 = N->getOperand(1);
9801 
9802   // Only do this if the inner op has one use since this will just increases
9803   // register pressure for no benefit.
9804 
9805   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9806       !VT.isVector() &&
9807       (VT == MVT::i32 || VT == MVT::f32 ||
9808        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9809     // max(max(a, b), c) -> max3(a, b, c)
9810     // min(min(a, b), c) -> min3(a, b, c)
9811     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9812       SDLoc DL(N);
9813       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9814                          DL,
9815                          N->getValueType(0),
9816                          Op0.getOperand(0),
9817                          Op0.getOperand(1),
9818                          Op1);
9819     }
9820 
9821     // Try commuted.
9822     // max(a, max(b, c)) -> max3(a, b, c)
9823     // min(a, min(b, c)) -> min3(a, b, c)
9824     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9825       SDLoc DL(N);
9826       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9827                          DL,
9828                          N->getValueType(0),
9829                          Op0,
9830                          Op1.getOperand(0),
9831                          Op1.getOperand(1));
9832     }
9833   }
9834 
9835   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9836   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9837     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9838       return Med3;
9839   }
9840 
9841   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9842     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9843       return Med3;
9844   }
9845 
9846   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9847   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9848        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9849        (Opc == AMDGPUISD::FMIN_LEGACY &&
9850         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9851       (VT == MVT::f32 || VT == MVT::f64 ||
9852        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9853        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9854       Op0.hasOneUse()) {
9855     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9856       return Res;
9857   }
9858 
9859   return SDValue();
9860 }
9861 
9862 static bool isClampZeroToOne(SDValue A, SDValue B) {
9863   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9864     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9865       // FIXME: Should this be allowing -0.0?
9866       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9867              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9868     }
9869   }
9870 
9871   return false;
9872 }
9873 
9874 // FIXME: Should only worry about snans for version with chain.
9875 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9876                                               DAGCombinerInfo &DCI) const {
9877   EVT VT = N->getValueType(0);
9878   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9879   // NaNs. With a NaN input, the order of the operands may change the result.
9880 
9881   SelectionDAG &DAG = DCI.DAG;
9882   SDLoc SL(N);
9883 
9884   SDValue Src0 = N->getOperand(0);
9885   SDValue Src1 = N->getOperand(1);
9886   SDValue Src2 = N->getOperand(2);
9887 
9888   if (isClampZeroToOne(Src0, Src1)) {
9889     // const_a, const_b, x -> clamp is safe in all cases including signaling
9890     // nans.
9891     // FIXME: Should this be allowing -0.0?
9892     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9893   }
9894 
9895   const MachineFunction &MF = DAG.getMachineFunction();
9896   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9897 
9898   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9899   // handling no dx10-clamp?
9900   if (Info->getMode().DX10Clamp) {
9901     // If NaNs is clamped to 0, we are free to reorder the inputs.
9902 
9903     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9904       std::swap(Src0, Src1);
9905 
9906     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9907       std::swap(Src1, Src2);
9908 
9909     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9910       std::swap(Src0, Src1);
9911 
9912     if (isClampZeroToOne(Src1, Src2))
9913       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9914   }
9915 
9916   return SDValue();
9917 }
9918 
9919 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9920                                                  DAGCombinerInfo &DCI) const {
9921   SDValue Src0 = N->getOperand(0);
9922   SDValue Src1 = N->getOperand(1);
9923   if (Src0.isUndef() && Src1.isUndef())
9924     return DCI.DAG.getUNDEF(N->getValueType(0));
9925   return SDValue();
9926 }
9927 
9928 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9929 // expanded into a set of cmp/select instructions.
9930 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9931                                                 unsigned NumElem,
9932                                                 bool IsDivergentIdx) {
9933   if (UseDivergentRegisterIndexing)
9934     return false;
9935 
9936   unsigned VecSize = EltSize * NumElem;
9937 
9938   // Sub-dword vectors of size 2 dword or less have better implementation.
9939   if (VecSize <= 64 && EltSize < 32)
9940     return false;
9941 
9942   // Always expand the rest of sub-dword instructions, otherwise it will be
9943   // lowered via memory.
9944   if (EltSize < 32)
9945     return true;
9946 
9947   // Always do this if var-idx is divergent, otherwise it will become a loop.
9948   if (IsDivergentIdx)
9949     return true;
9950 
9951   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9952   unsigned NumInsts = NumElem /* Number of compares */ +
9953                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9954   return NumInsts <= 16;
9955 }
9956 
9957 static bool shouldExpandVectorDynExt(SDNode *N) {
9958   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9959   if (isa<ConstantSDNode>(Idx))
9960     return false;
9961 
9962   SDValue Vec = N->getOperand(0);
9963   EVT VecVT = Vec.getValueType();
9964   EVT EltVT = VecVT.getVectorElementType();
9965   unsigned EltSize = EltVT.getSizeInBits();
9966   unsigned NumElem = VecVT.getVectorNumElements();
9967 
9968   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9969                                                     Idx->isDivergent());
9970 }
9971 
9972 SDValue SITargetLowering::performExtractVectorEltCombine(
9973   SDNode *N, DAGCombinerInfo &DCI) const {
9974   SDValue Vec = N->getOperand(0);
9975   SelectionDAG &DAG = DCI.DAG;
9976 
9977   EVT VecVT = Vec.getValueType();
9978   EVT EltVT = VecVT.getVectorElementType();
9979 
9980   if ((Vec.getOpcode() == ISD::FNEG ||
9981        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9982     SDLoc SL(N);
9983     EVT EltVT = N->getValueType(0);
9984     SDValue Idx = N->getOperand(1);
9985     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9986                               Vec.getOperand(0), Idx);
9987     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9988   }
9989 
9990   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9991   //    =>
9992   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9993   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9994   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9995   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9996     SDLoc SL(N);
9997     EVT EltVT = N->getValueType(0);
9998     SDValue Idx = N->getOperand(1);
9999     unsigned Opc = Vec.getOpcode();
10000 
10001     switch(Opc) {
10002     default:
10003       break;
10004       // TODO: Support other binary operations.
10005     case ISD::FADD:
10006     case ISD::FSUB:
10007     case ISD::FMUL:
10008     case ISD::ADD:
10009     case ISD::UMIN:
10010     case ISD::UMAX:
10011     case ISD::SMIN:
10012     case ISD::SMAX:
10013     case ISD::FMAXNUM:
10014     case ISD::FMINNUM:
10015     case ISD::FMAXNUM_IEEE:
10016     case ISD::FMINNUM_IEEE: {
10017       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10018                                  Vec.getOperand(0), Idx);
10019       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10020                                  Vec.getOperand(1), Idx);
10021 
10022       DCI.AddToWorklist(Elt0.getNode());
10023       DCI.AddToWorklist(Elt1.getNode());
10024       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10025     }
10026     }
10027   }
10028 
10029   unsigned VecSize = VecVT.getSizeInBits();
10030   unsigned EltSize = EltVT.getSizeInBits();
10031 
10032   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10033   if (::shouldExpandVectorDynExt(N)) {
10034     SDLoc SL(N);
10035     SDValue Idx = N->getOperand(1);
10036     SDValue V;
10037     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10038       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10039       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10040       if (I == 0)
10041         V = Elt;
10042       else
10043         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10044     }
10045     return V;
10046   }
10047 
10048   if (!DCI.isBeforeLegalize())
10049     return SDValue();
10050 
10051   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10052   // elements. This exposes more load reduction opportunities by replacing
10053   // multiple small extract_vector_elements with a single 32-bit extract.
10054   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10055   if (isa<MemSDNode>(Vec) &&
10056       EltSize <= 16 &&
10057       EltVT.isByteSized() &&
10058       VecSize > 32 &&
10059       VecSize % 32 == 0 &&
10060       Idx) {
10061     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10062 
10063     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10064     unsigned EltIdx = BitIndex / 32;
10065     unsigned LeftoverBitIdx = BitIndex % 32;
10066     SDLoc SL(N);
10067 
10068     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10069     DCI.AddToWorklist(Cast.getNode());
10070 
10071     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10072                               DAG.getConstant(EltIdx, SL, MVT::i32));
10073     DCI.AddToWorklist(Elt.getNode());
10074     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10075                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10076     DCI.AddToWorklist(Srl.getNode());
10077 
10078     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10079     DCI.AddToWorklist(Trunc.getNode());
10080     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10081   }
10082 
10083   return SDValue();
10084 }
10085 
10086 SDValue
10087 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10088                                                 DAGCombinerInfo &DCI) const {
10089   SDValue Vec = N->getOperand(0);
10090   SDValue Idx = N->getOperand(2);
10091   EVT VecVT = Vec.getValueType();
10092   EVT EltVT = VecVT.getVectorElementType();
10093 
10094   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10095   // => BUILD_VECTOR n x select (e, const-idx)
10096   if (!::shouldExpandVectorDynExt(N))
10097     return SDValue();
10098 
10099   SelectionDAG &DAG = DCI.DAG;
10100   SDLoc SL(N);
10101   SDValue Ins = N->getOperand(1);
10102   EVT IdxVT = Idx.getValueType();
10103 
10104   SmallVector<SDValue, 16> Ops;
10105   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10106     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10107     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10108     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10109     Ops.push_back(V);
10110   }
10111 
10112   return DAG.getBuildVector(VecVT, SL, Ops);
10113 }
10114 
10115 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10116                                           const SDNode *N0,
10117                                           const SDNode *N1) const {
10118   EVT VT = N0->getValueType(0);
10119 
10120   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10121   // support denormals ever.
10122   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10123        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10124         getSubtarget()->hasMadF16())) &&
10125        isOperationLegal(ISD::FMAD, VT))
10126     return ISD::FMAD;
10127 
10128   const TargetOptions &Options = DAG.getTarget().Options;
10129   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10130        (N0->getFlags().hasAllowContract() &&
10131         N1->getFlags().hasAllowContract())) &&
10132       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10133     return ISD::FMA;
10134   }
10135 
10136   return 0;
10137 }
10138 
10139 // For a reassociatable opcode perform:
10140 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10141 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10142                                                SelectionDAG &DAG) const {
10143   EVT VT = N->getValueType(0);
10144   if (VT != MVT::i32 && VT != MVT::i64)
10145     return SDValue();
10146 
10147   unsigned Opc = N->getOpcode();
10148   SDValue Op0 = N->getOperand(0);
10149   SDValue Op1 = N->getOperand(1);
10150 
10151   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10152     return SDValue();
10153 
10154   if (Op0->isDivergent())
10155     std::swap(Op0, Op1);
10156 
10157   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10158     return SDValue();
10159 
10160   SDValue Op2 = Op1.getOperand(1);
10161   Op1 = Op1.getOperand(0);
10162   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10163     return SDValue();
10164 
10165   if (Op1->isDivergent())
10166     std::swap(Op1, Op2);
10167 
10168   // If either operand is constant this will conflict with
10169   // DAGCombiner::ReassociateOps().
10170   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10171       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10172     return SDValue();
10173 
10174   SDLoc SL(N);
10175   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10176   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10177 }
10178 
10179 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10180                            EVT VT,
10181                            SDValue N0, SDValue N1, SDValue N2,
10182                            bool Signed) {
10183   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10184   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10185   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10186   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10187 }
10188 
10189 SDValue SITargetLowering::performAddCombine(SDNode *N,
10190                                             DAGCombinerInfo &DCI) const {
10191   SelectionDAG &DAG = DCI.DAG;
10192   EVT VT = N->getValueType(0);
10193   SDLoc SL(N);
10194   SDValue LHS = N->getOperand(0);
10195   SDValue RHS = N->getOperand(1);
10196 
10197   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10198       && Subtarget->hasMad64_32() &&
10199       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10200       VT.getScalarSizeInBits() <= 64) {
10201     if (LHS.getOpcode() != ISD::MUL)
10202       std::swap(LHS, RHS);
10203 
10204     SDValue MulLHS = LHS.getOperand(0);
10205     SDValue MulRHS = LHS.getOperand(1);
10206     SDValue AddRHS = RHS;
10207 
10208     // TODO: Maybe restrict if SGPR inputs.
10209     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10210         numBitsUnsigned(MulRHS, DAG) <= 32) {
10211       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10212       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10213       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10214       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10215     }
10216 
10217     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10218       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10219       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10220       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10221       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10222     }
10223 
10224     return SDValue();
10225   }
10226 
10227   if (SDValue V = reassociateScalarOps(N, DAG)) {
10228     return V;
10229   }
10230 
10231   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10232     return SDValue();
10233 
10234   // add x, zext (setcc) => addcarry x, 0, setcc
10235   // add x, sext (setcc) => subcarry x, 0, setcc
10236   unsigned Opc = LHS.getOpcode();
10237   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10238       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10239     std::swap(RHS, LHS);
10240 
10241   Opc = RHS.getOpcode();
10242   switch (Opc) {
10243   default: break;
10244   case ISD::ZERO_EXTEND:
10245   case ISD::SIGN_EXTEND:
10246   case ISD::ANY_EXTEND: {
10247     auto Cond = RHS.getOperand(0);
10248     // If this won't be a real VOPC output, we would still need to insert an
10249     // extra instruction anyway.
10250     if (!isBoolSGPR(Cond))
10251       break;
10252     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10253     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10254     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10255     return DAG.getNode(Opc, SL, VTList, Args);
10256   }
10257   case ISD::ADDCARRY: {
10258     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10259     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10260     if (!C || C->getZExtValue() != 0) break;
10261     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10262     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10263   }
10264   }
10265   return SDValue();
10266 }
10267 
10268 SDValue SITargetLowering::performSubCombine(SDNode *N,
10269                                             DAGCombinerInfo &DCI) const {
10270   SelectionDAG &DAG = DCI.DAG;
10271   EVT VT = N->getValueType(0);
10272 
10273   if (VT != MVT::i32)
10274     return SDValue();
10275 
10276   SDLoc SL(N);
10277   SDValue LHS = N->getOperand(0);
10278   SDValue RHS = N->getOperand(1);
10279 
10280   // sub x, zext (setcc) => subcarry x, 0, setcc
10281   // sub x, sext (setcc) => addcarry x, 0, setcc
10282   unsigned Opc = RHS.getOpcode();
10283   switch (Opc) {
10284   default: break;
10285   case ISD::ZERO_EXTEND:
10286   case ISD::SIGN_EXTEND:
10287   case ISD::ANY_EXTEND: {
10288     auto Cond = RHS.getOperand(0);
10289     // If this won't be a real VOPC output, we would still need to insert an
10290     // extra instruction anyway.
10291     if (!isBoolSGPR(Cond))
10292       break;
10293     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10294     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10295     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10296     return DAG.getNode(Opc, SL, VTList, Args);
10297   }
10298   }
10299 
10300   if (LHS.getOpcode() == ISD::SUBCARRY) {
10301     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10302     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10303     if (!C || !C->isNullValue())
10304       return SDValue();
10305     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10306     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10307   }
10308   return SDValue();
10309 }
10310 
10311 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10312   DAGCombinerInfo &DCI) const {
10313 
10314   if (N->getValueType(0) != MVT::i32)
10315     return SDValue();
10316 
10317   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10318   if (!C || C->getZExtValue() != 0)
10319     return SDValue();
10320 
10321   SelectionDAG &DAG = DCI.DAG;
10322   SDValue LHS = N->getOperand(0);
10323 
10324   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10325   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10326   unsigned LHSOpc = LHS.getOpcode();
10327   unsigned Opc = N->getOpcode();
10328   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10329       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10330     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10331     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10332   }
10333   return SDValue();
10334 }
10335 
10336 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10337                                              DAGCombinerInfo &DCI) const {
10338   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10339     return SDValue();
10340 
10341   SelectionDAG &DAG = DCI.DAG;
10342   EVT VT = N->getValueType(0);
10343 
10344   SDLoc SL(N);
10345   SDValue LHS = N->getOperand(0);
10346   SDValue RHS = N->getOperand(1);
10347 
10348   // These should really be instruction patterns, but writing patterns with
10349   // source modiifiers is a pain.
10350 
10351   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10352   if (LHS.getOpcode() == ISD::FADD) {
10353     SDValue A = LHS.getOperand(0);
10354     if (A == LHS.getOperand(1)) {
10355       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10356       if (FusedOp != 0) {
10357         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10358         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10359       }
10360     }
10361   }
10362 
10363   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10364   if (RHS.getOpcode() == ISD::FADD) {
10365     SDValue A = RHS.getOperand(0);
10366     if (A == RHS.getOperand(1)) {
10367       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10368       if (FusedOp != 0) {
10369         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10370         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10371       }
10372     }
10373   }
10374 
10375   return SDValue();
10376 }
10377 
10378 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10379                                              DAGCombinerInfo &DCI) const {
10380   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10381     return SDValue();
10382 
10383   SelectionDAG &DAG = DCI.DAG;
10384   SDLoc SL(N);
10385   EVT VT = N->getValueType(0);
10386   assert(!VT.isVector());
10387 
10388   // Try to get the fneg to fold into the source modifier. This undoes generic
10389   // DAG combines and folds them into the mad.
10390   //
10391   // Only do this if we are not trying to support denormals. v_mad_f32 does
10392   // not support denormals ever.
10393   SDValue LHS = N->getOperand(0);
10394   SDValue RHS = N->getOperand(1);
10395   if (LHS.getOpcode() == ISD::FADD) {
10396     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10397     SDValue A = LHS.getOperand(0);
10398     if (A == LHS.getOperand(1)) {
10399       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10400       if (FusedOp != 0){
10401         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10402         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10403 
10404         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10405       }
10406     }
10407   }
10408 
10409   if (RHS.getOpcode() == ISD::FADD) {
10410     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10411 
10412     SDValue A = RHS.getOperand(0);
10413     if (A == RHS.getOperand(1)) {
10414       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10415       if (FusedOp != 0){
10416         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10417         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10418       }
10419     }
10420   }
10421 
10422   return SDValue();
10423 }
10424 
10425 SDValue SITargetLowering::performFMACombine(SDNode *N,
10426                                             DAGCombinerInfo &DCI) const {
10427   SelectionDAG &DAG = DCI.DAG;
10428   EVT VT = N->getValueType(0);
10429   SDLoc SL(N);
10430 
10431   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10432     return SDValue();
10433 
10434   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10435   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10436   SDValue Op1 = N->getOperand(0);
10437   SDValue Op2 = N->getOperand(1);
10438   SDValue FMA = N->getOperand(2);
10439 
10440   if (FMA.getOpcode() != ISD::FMA ||
10441       Op1.getOpcode() != ISD::FP_EXTEND ||
10442       Op2.getOpcode() != ISD::FP_EXTEND)
10443     return SDValue();
10444 
10445   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10446   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10447   // is sufficient to allow generaing fdot2.
10448   const TargetOptions &Options = DAG.getTarget().Options;
10449   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10450       (N->getFlags().hasAllowContract() &&
10451        FMA->getFlags().hasAllowContract())) {
10452     Op1 = Op1.getOperand(0);
10453     Op2 = Op2.getOperand(0);
10454     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10455         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10456       return SDValue();
10457 
10458     SDValue Vec1 = Op1.getOperand(0);
10459     SDValue Idx1 = Op1.getOperand(1);
10460     SDValue Vec2 = Op2.getOperand(0);
10461 
10462     SDValue FMAOp1 = FMA.getOperand(0);
10463     SDValue FMAOp2 = FMA.getOperand(1);
10464     SDValue FMAAcc = FMA.getOperand(2);
10465 
10466     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10467         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10468       return SDValue();
10469 
10470     FMAOp1 = FMAOp1.getOperand(0);
10471     FMAOp2 = FMAOp2.getOperand(0);
10472     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10473         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10474       return SDValue();
10475 
10476     SDValue Vec3 = FMAOp1.getOperand(0);
10477     SDValue Vec4 = FMAOp2.getOperand(0);
10478     SDValue Idx2 = FMAOp1.getOperand(1);
10479 
10480     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10481         // Idx1 and Idx2 cannot be the same.
10482         Idx1 == Idx2)
10483       return SDValue();
10484 
10485     if (Vec1 == Vec2 || Vec3 == Vec4)
10486       return SDValue();
10487 
10488     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10489       return SDValue();
10490 
10491     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10492         (Vec1 == Vec4 && Vec2 == Vec3)) {
10493       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10494                          DAG.getTargetConstant(0, SL, MVT::i1));
10495     }
10496   }
10497   return SDValue();
10498 }
10499 
10500 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10501                                               DAGCombinerInfo &DCI) const {
10502   SelectionDAG &DAG = DCI.DAG;
10503   SDLoc SL(N);
10504 
10505   SDValue LHS = N->getOperand(0);
10506   SDValue RHS = N->getOperand(1);
10507   EVT VT = LHS.getValueType();
10508   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10509 
10510   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10511   if (!CRHS) {
10512     CRHS = dyn_cast<ConstantSDNode>(LHS);
10513     if (CRHS) {
10514       std::swap(LHS, RHS);
10515       CC = getSetCCSwappedOperands(CC);
10516     }
10517   }
10518 
10519   if (CRHS) {
10520     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10521         isBoolSGPR(LHS.getOperand(0))) {
10522       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10523       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10524       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10525       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10526       if ((CRHS->isAllOnesValue() &&
10527            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10528           (CRHS->isNullValue() &&
10529            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10530         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10531                            DAG.getConstant(-1, SL, MVT::i1));
10532       if ((CRHS->isAllOnesValue() &&
10533            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10534           (CRHS->isNullValue() &&
10535            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10536         return LHS.getOperand(0);
10537     }
10538 
10539     uint64_t CRHSVal = CRHS->getZExtValue();
10540     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10541         LHS.getOpcode() == ISD::SELECT &&
10542         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10543         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10544         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10545         isBoolSGPR(LHS.getOperand(0))) {
10546       // Given CT != FT:
10547       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10548       // setcc (select cc, CT, CF), CF, ne => cc
10549       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10550       // setcc (select cc, CT, CF), CT, eq => cc
10551       uint64_t CT = LHS.getConstantOperandVal(1);
10552       uint64_t CF = LHS.getConstantOperandVal(2);
10553 
10554       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10555           (CT == CRHSVal && CC == ISD::SETNE))
10556         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10557                            DAG.getConstant(-1, SL, MVT::i1));
10558       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10559           (CT == CRHSVal && CC == ISD::SETEQ))
10560         return LHS.getOperand(0);
10561     }
10562   }
10563 
10564   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10565                                            VT != MVT::f16))
10566     return SDValue();
10567 
10568   // Match isinf/isfinite pattern
10569   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10570   // (fcmp one (fabs x), inf) -> (fp_class x,
10571   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10572   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10573     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10574     if (!CRHS)
10575       return SDValue();
10576 
10577     const APFloat &APF = CRHS->getValueAPF();
10578     if (APF.isInfinity() && !APF.isNegative()) {
10579       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10580                                  SIInstrFlags::N_INFINITY;
10581       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10582                                     SIInstrFlags::P_ZERO |
10583                                     SIInstrFlags::N_NORMAL |
10584                                     SIInstrFlags::P_NORMAL |
10585                                     SIInstrFlags::N_SUBNORMAL |
10586                                     SIInstrFlags::P_SUBNORMAL;
10587       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10588       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10589                          DAG.getConstant(Mask, SL, MVT::i32));
10590     }
10591   }
10592 
10593   return SDValue();
10594 }
10595 
10596 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10597                                                      DAGCombinerInfo &DCI) const {
10598   SelectionDAG &DAG = DCI.DAG;
10599   SDLoc SL(N);
10600   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10601 
10602   SDValue Src = N->getOperand(0);
10603   SDValue Shift = N->getOperand(0);
10604 
10605   // TODO: Extend type shouldn't matter (assuming legal types).
10606   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10607     Shift = Shift.getOperand(0);
10608 
10609   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10610     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10611     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10612     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10613     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10614     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10615     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10616       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10617                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10618 
10619       unsigned ShiftOffset = 8 * Offset;
10620       if (Shift.getOpcode() == ISD::SHL)
10621         ShiftOffset -= C->getZExtValue();
10622       else
10623         ShiftOffset += C->getZExtValue();
10624 
10625       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10626         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10627                            MVT::f32, Shift);
10628       }
10629     }
10630   }
10631 
10632   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10633   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10634   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10635     // We simplified Src. If this node is not dead, visit it again so it is
10636     // folded properly.
10637     if (N->getOpcode() != ISD::DELETED_NODE)
10638       DCI.AddToWorklist(N);
10639     return SDValue(N, 0);
10640   }
10641 
10642   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10643   if (SDValue DemandedSrc =
10644           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10645     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10646 
10647   return SDValue();
10648 }
10649 
10650 SDValue SITargetLowering::performClampCombine(SDNode *N,
10651                                               DAGCombinerInfo &DCI) const {
10652   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10653   if (!CSrc)
10654     return SDValue();
10655 
10656   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10657   const APFloat &F = CSrc->getValueAPF();
10658   APFloat Zero = APFloat::getZero(F.getSemantics());
10659   if (F < Zero ||
10660       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10661     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10662   }
10663 
10664   APFloat One(F.getSemantics(), "1.0");
10665   if (F > One)
10666     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10667 
10668   return SDValue(CSrc, 0);
10669 }
10670 
10671 
10672 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10673                                             DAGCombinerInfo &DCI) const {
10674   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10675     return SDValue();
10676   switch (N->getOpcode()) {
10677   case ISD::ADD:
10678     return performAddCombine(N, DCI);
10679   case ISD::SUB:
10680     return performSubCombine(N, DCI);
10681   case ISD::ADDCARRY:
10682   case ISD::SUBCARRY:
10683     return performAddCarrySubCarryCombine(N, DCI);
10684   case ISD::FADD:
10685     return performFAddCombine(N, DCI);
10686   case ISD::FSUB:
10687     return performFSubCombine(N, DCI);
10688   case ISD::SETCC:
10689     return performSetCCCombine(N, DCI);
10690   case ISD::FMAXNUM:
10691   case ISD::FMINNUM:
10692   case ISD::FMAXNUM_IEEE:
10693   case ISD::FMINNUM_IEEE:
10694   case ISD::SMAX:
10695   case ISD::SMIN:
10696   case ISD::UMAX:
10697   case ISD::UMIN:
10698   case AMDGPUISD::FMIN_LEGACY:
10699   case AMDGPUISD::FMAX_LEGACY:
10700     return performMinMaxCombine(N, DCI);
10701   case ISD::FMA:
10702     return performFMACombine(N, DCI);
10703   case ISD::AND:
10704     return performAndCombine(N, DCI);
10705   case ISD::OR:
10706     return performOrCombine(N, DCI);
10707   case ISD::XOR:
10708     return performXorCombine(N, DCI);
10709   case ISD::ZERO_EXTEND:
10710     return performZeroExtendCombine(N, DCI);
10711   case ISD::SIGN_EXTEND_INREG:
10712     return performSignExtendInRegCombine(N , DCI);
10713   case AMDGPUISD::FP_CLASS:
10714     return performClassCombine(N, DCI);
10715   case ISD::FCANONICALIZE:
10716     return performFCanonicalizeCombine(N, DCI);
10717   case AMDGPUISD::RCP:
10718     return performRcpCombine(N, DCI);
10719   case AMDGPUISD::FRACT:
10720   case AMDGPUISD::RSQ:
10721   case AMDGPUISD::RCP_LEGACY:
10722   case AMDGPUISD::RCP_IFLAG:
10723   case AMDGPUISD::RSQ_CLAMP:
10724   case AMDGPUISD::LDEXP: {
10725     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10726     SDValue Src = N->getOperand(0);
10727     if (Src.isUndef())
10728       return Src;
10729     break;
10730   }
10731   case ISD::SINT_TO_FP:
10732   case ISD::UINT_TO_FP:
10733     return performUCharToFloatCombine(N, DCI);
10734   case AMDGPUISD::CVT_F32_UBYTE0:
10735   case AMDGPUISD::CVT_F32_UBYTE1:
10736   case AMDGPUISD::CVT_F32_UBYTE2:
10737   case AMDGPUISD::CVT_F32_UBYTE3:
10738     return performCvtF32UByteNCombine(N, DCI);
10739   case AMDGPUISD::FMED3:
10740     return performFMed3Combine(N, DCI);
10741   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10742     return performCvtPkRTZCombine(N, DCI);
10743   case AMDGPUISD::CLAMP:
10744     return performClampCombine(N, DCI);
10745   case ISD::SCALAR_TO_VECTOR: {
10746     SelectionDAG &DAG = DCI.DAG;
10747     EVT VT = N->getValueType(0);
10748 
10749     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10750     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10751       SDLoc SL(N);
10752       SDValue Src = N->getOperand(0);
10753       EVT EltVT = Src.getValueType();
10754       if (EltVT == MVT::f16)
10755         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10756 
10757       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10758       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10759     }
10760 
10761     break;
10762   }
10763   case ISD::EXTRACT_VECTOR_ELT:
10764     return performExtractVectorEltCombine(N, DCI);
10765   case ISD::INSERT_VECTOR_ELT:
10766     return performInsertVectorEltCombine(N, DCI);
10767   case ISD::LOAD: {
10768     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10769       return Widended;
10770     LLVM_FALLTHROUGH;
10771   }
10772   default: {
10773     if (!DCI.isBeforeLegalize()) {
10774       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10775         return performMemSDNodeCombine(MemNode, DCI);
10776     }
10777 
10778     break;
10779   }
10780   }
10781 
10782   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10783 }
10784 
10785 /// Helper function for adjustWritemask
10786 static unsigned SubIdx2Lane(unsigned Idx) {
10787   switch (Idx) {
10788   default: return 0;
10789   case AMDGPU::sub0: return 0;
10790   case AMDGPU::sub1: return 1;
10791   case AMDGPU::sub2: return 2;
10792   case AMDGPU::sub3: return 3;
10793   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10794   }
10795 }
10796 
10797 /// Adjust the writemask of MIMG instructions
10798 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10799                                           SelectionDAG &DAG) const {
10800   unsigned Opcode = Node->getMachineOpcode();
10801 
10802   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10803   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10804   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10805     return Node; // not implemented for D16
10806 
10807   SDNode *Users[5] = { nullptr };
10808   unsigned Lane = 0;
10809   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10810   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10811   unsigned NewDmask = 0;
10812   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10813   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10814   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10815                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10816   unsigned TFCLane = 0;
10817   bool HasChain = Node->getNumValues() > 1;
10818 
10819   if (OldDmask == 0) {
10820     // These are folded out, but on the chance it happens don't assert.
10821     return Node;
10822   }
10823 
10824   unsigned OldBitsSet = countPopulation(OldDmask);
10825   // Work out which is the TFE/LWE lane if that is enabled.
10826   if (UsesTFC) {
10827     TFCLane = OldBitsSet;
10828   }
10829 
10830   // Try to figure out the used register components
10831   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10832        I != E; ++I) {
10833 
10834     // Don't look at users of the chain.
10835     if (I.getUse().getResNo() != 0)
10836       continue;
10837 
10838     // Abort if we can't understand the usage
10839     if (!I->isMachineOpcode() ||
10840         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10841       return Node;
10842 
10843     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10844     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10845     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10846     // set, etc.
10847     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10848 
10849     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10850     if (UsesTFC && Lane == TFCLane) {
10851       Users[Lane] = *I;
10852     } else {
10853       // Set which texture component corresponds to the lane.
10854       unsigned Comp;
10855       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10856         Comp = countTrailingZeros(Dmask);
10857         Dmask &= ~(1 << Comp);
10858       }
10859 
10860       // Abort if we have more than one user per component.
10861       if (Users[Lane])
10862         return Node;
10863 
10864       Users[Lane] = *I;
10865       NewDmask |= 1 << Comp;
10866     }
10867   }
10868 
10869   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10870   bool NoChannels = !NewDmask;
10871   if (NoChannels) {
10872     if (!UsesTFC) {
10873       // No uses of the result and not using TFC. Then do nothing.
10874       return Node;
10875     }
10876     // If the original dmask has one channel - then nothing to do
10877     if (OldBitsSet == 1)
10878       return Node;
10879     // Use an arbitrary dmask - required for the instruction to work
10880     NewDmask = 1;
10881   }
10882   // Abort if there's no change
10883   if (NewDmask == OldDmask)
10884     return Node;
10885 
10886   unsigned BitsSet = countPopulation(NewDmask);
10887 
10888   // Check for TFE or LWE - increase the number of channels by one to account
10889   // for the extra return value
10890   // This will need adjustment for D16 if this is also included in
10891   // adjustWriteMask (this function) but at present D16 are excluded.
10892   unsigned NewChannels = BitsSet + UsesTFC;
10893 
10894   int NewOpcode =
10895       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10896   assert(NewOpcode != -1 &&
10897          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10898          "failed to find equivalent MIMG op");
10899 
10900   // Adjust the writemask in the node
10901   SmallVector<SDValue, 12> Ops;
10902   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10903   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10904   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10905 
10906   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10907 
10908   MVT ResultVT = NewChannels == 1 ?
10909     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10910                            NewChannels == 5 ? 8 : NewChannels);
10911   SDVTList NewVTList = HasChain ?
10912     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10913 
10914 
10915   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10916                                               NewVTList, Ops);
10917 
10918   if (HasChain) {
10919     // Update chain.
10920     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10921     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10922   }
10923 
10924   if (NewChannels == 1) {
10925     assert(Node->hasNUsesOfValue(1, 0));
10926     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10927                                       SDLoc(Node), Users[Lane]->getValueType(0),
10928                                       SDValue(NewNode, 0));
10929     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10930     return nullptr;
10931   }
10932 
10933   // Update the users of the node with the new indices
10934   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10935     SDNode *User = Users[i];
10936     if (!User) {
10937       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10938       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10939       if (i || !NoChannels)
10940         continue;
10941     } else {
10942       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10943       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10944     }
10945 
10946     switch (Idx) {
10947     default: break;
10948     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10949     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10950     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10951     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10952     }
10953   }
10954 
10955   DAG.RemoveDeadNode(Node);
10956   return nullptr;
10957 }
10958 
10959 static bool isFrameIndexOp(SDValue Op) {
10960   if (Op.getOpcode() == ISD::AssertZext)
10961     Op = Op.getOperand(0);
10962 
10963   return isa<FrameIndexSDNode>(Op);
10964 }
10965 
10966 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10967 /// with frame index operands.
10968 /// LLVM assumes that inputs are to these instructions are registers.
10969 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10970                                                         SelectionDAG &DAG) const {
10971   if (Node->getOpcode() == ISD::CopyToReg) {
10972     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10973     SDValue SrcVal = Node->getOperand(2);
10974 
10975     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10976     // to try understanding copies to physical registers.
10977     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
10978       SDLoc SL(Node);
10979       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10980       SDValue VReg = DAG.getRegister(
10981         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10982 
10983       SDNode *Glued = Node->getGluedNode();
10984       SDValue ToVReg
10985         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10986                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10987       SDValue ToResultReg
10988         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10989                            VReg, ToVReg.getValue(1));
10990       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10991       DAG.RemoveDeadNode(Node);
10992       return ToResultReg.getNode();
10993     }
10994   }
10995 
10996   SmallVector<SDValue, 8> Ops;
10997   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10998     if (!isFrameIndexOp(Node->getOperand(i))) {
10999       Ops.push_back(Node->getOperand(i));
11000       continue;
11001     }
11002 
11003     SDLoc DL(Node);
11004     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11005                                      Node->getOperand(i).getValueType(),
11006                                      Node->getOperand(i)), 0));
11007   }
11008 
11009   return DAG.UpdateNodeOperands(Node, Ops);
11010 }
11011 
11012 /// Fold the instructions after selecting them.
11013 /// Returns null if users were already updated.
11014 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11015                                           SelectionDAG &DAG) const {
11016   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11017   unsigned Opcode = Node->getMachineOpcode();
11018 
11019   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11020       !TII->isGather4(Opcode) &&
11021       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11022     return adjustWritemask(Node, DAG);
11023   }
11024 
11025   if (Opcode == AMDGPU::INSERT_SUBREG ||
11026       Opcode == AMDGPU::REG_SEQUENCE) {
11027     legalizeTargetIndependentNode(Node, DAG);
11028     return Node;
11029   }
11030 
11031   switch (Opcode) {
11032   case AMDGPU::V_DIV_SCALE_F32:
11033   case AMDGPU::V_DIV_SCALE_F64: {
11034     // Satisfy the operand register constraint when one of the inputs is
11035     // undefined. Ordinarily each undef value will have its own implicit_def of
11036     // a vreg, so force these to use a single register.
11037     SDValue Src0 = Node->getOperand(0);
11038     SDValue Src1 = Node->getOperand(1);
11039     SDValue Src2 = Node->getOperand(2);
11040 
11041     if ((Src0.isMachineOpcode() &&
11042          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11043         (Src0 == Src1 || Src0 == Src2))
11044       break;
11045 
11046     MVT VT = Src0.getValueType().getSimpleVT();
11047     const TargetRegisterClass *RC =
11048         getRegClassFor(VT, Src0.getNode()->isDivergent());
11049 
11050     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11051     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11052 
11053     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11054                                       UndefReg, Src0, SDValue());
11055 
11056     // src0 must be the same register as src1 or src2, even if the value is
11057     // undefined, so make sure we don't violate this constraint.
11058     if (Src0.isMachineOpcode() &&
11059         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11060       if (Src1.isMachineOpcode() &&
11061           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11062         Src0 = Src1;
11063       else if (Src2.isMachineOpcode() &&
11064                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11065         Src0 = Src2;
11066       else {
11067         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11068         Src0 = UndefReg;
11069         Src1 = UndefReg;
11070       }
11071     } else
11072       break;
11073 
11074     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
11075     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
11076       Ops.push_back(Node->getOperand(I));
11077 
11078     Ops.push_back(ImpDef.getValue(1));
11079     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11080   }
11081   default:
11082     break;
11083   }
11084 
11085   return Node;
11086 }
11087 
11088 /// Assign the register class depending on the number of
11089 /// bits set in the writemask
11090 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11091                                                      SDNode *Node) const {
11092   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11093 
11094   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11095 
11096   if (TII->isVOP3(MI.getOpcode())) {
11097     // Make sure constant bus requirements are respected.
11098     TII->legalizeOperandsVOP3(MRI, MI);
11099 
11100     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11101     // This saves a chain-copy of registers and better ballance register
11102     // use between vgpr and agpr as agpr tuples tend to be big.
11103     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11104       unsigned Opc = MI.getOpcode();
11105       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11106       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11107                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11108         if (I == -1)
11109           break;
11110         MachineOperand &Op = MI.getOperand(I);
11111         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11112              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11113             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11114           continue;
11115         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11116         if (!Src || !Src->isCopy() ||
11117             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11118           continue;
11119         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11120         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11121         // All uses of agpr64 and agpr32 can also accept vgpr except for
11122         // v_accvgpr_read, but we do not produce agpr reads during selection,
11123         // so no use checks are needed.
11124         MRI.setRegClass(Op.getReg(), NewRC);
11125       }
11126     }
11127 
11128     return;
11129   }
11130 
11131   // Replace unused atomics with the no return version.
11132   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11133   if (NoRetAtomicOp != -1) {
11134     if (!Node->hasAnyUseOfValue(0)) {
11135       MI.setDesc(TII->get(NoRetAtomicOp));
11136       MI.RemoveOperand(0);
11137       return;
11138     }
11139 
11140     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11141     // instruction, because the return type of these instructions is a vec2 of
11142     // the memory type, so it can be tied to the input operand.
11143     // This means these instructions always have a use, so we need to add a
11144     // special case to check if the atomic has only one extract_subreg use,
11145     // which itself has no uses.
11146     if ((Node->hasNUsesOfValue(1, 0) &&
11147          Node->use_begin()->isMachineOpcode() &&
11148          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11149          !Node->use_begin()->hasAnyUseOfValue(0))) {
11150       Register Def = MI.getOperand(0).getReg();
11151 
11152       // Change this into a noret atomic.
11153       MI.setDesc(TII->get(NoRetAtomicOp));
11154       MI.RemoveOperand(0);
11155 
11156       // If we only remove the def operand from the atomic instruction, the
11157       // extract_subreg will be left with a use of a vreg without a def.
11158       // So we need to insert an implicit_def to avoid machine verifier
11159       // errors.
11160       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11161               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11162     }
11163     return;
11164   }
11165 }
11166 
11167 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11168                               uint64_t Val) {
11169   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11170   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11171 }
11172 
11173 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11174                                                 const SDLoc &DL,
11175                                                 SDValue Ptr) const {
11176   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11177 
11178   // Build the half of the subregister with the constants before building the
11179   // full 128-bit register. If we are building multiple resource descriptors,
11180   // this will allow CSEing of the 2-component register.
11181   const SDValue Ops0[] = {
11182     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11183     buildSMovImm32(DAG, DL, 0),
11184     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11185     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11186     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11187   };
11188 
11189   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11190                                                 MVT::v2i32, Ops0), 0);
11191 
11192   // Combine the constants and the pointer.
11193   const SDValue Ops1[] = {
11194     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11195     Ptr,
11196     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11197     SubRegHi,
11198     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11199   };
11200 
11201   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11202 }
11203 
11204 /// Return a resource descriptor with the 'Add TID' bit enabled
11205 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11206 ///        of the resource descriptor) to create an offset, which is added to
11207 ///        the resource pointer.
11208 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11209                                            SDValue Ptr, uint32_t RsrcDword1,
11210                                            uint64_t RsrcDword2And3) const {
11211   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11212   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11213   if (RsrcDword1) {
11214     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11215                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11216                     0);
11217   }
11218 
11219   SDValue DataLo = buildSMovImm32(DAG, DL,
11220                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11221   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11222 
11223   const SDValue Ops[] = {
11224     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11225     PtrLo,
11226     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11227     PtrHi,
11228     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11229     DataLo,
11230     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11231     DataHi,
11232     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11233   };
11234 
11235   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11236 }
11237 
11238 //===----------------------------------------------------------------------===//
11239 //                         SI Inline Assembly Support
11240 //===----------------------------------------------------------------------===//
11241 
11242 std::pair<unsigned, const TargetRegisterClass *>
11243 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11244                                                StringRef Constraint,
11245                                                MVT VT) const {
11246   const TargetRegisterClass *RC = nullptr;
11247   if (Constraint.size() == 1) {
11248     const unsigned BitWidth = VT.getSizeInBits();
11249     switch (Constraint[0]) {
11250     default:
11251       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11252     case 's':
11253     case 'r':
11254       switch (BitWidth) {
11255       case 16:
11256         RC = &AMDGPU::SReg_32RegClass;
11257         break;
11258       case 64:
11259         RC = &AMDGPU::SGPR_64RegClass;
11260         break;
11261       default:
11262         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11263         if (!RC)
11264           return std::make_pair(0U, nullptr);
11265         break;
11266       }
11267       break;
11268     case 'v':
11269       switch (BitWidth) {
11270       case 16:
11271         RC = &AMDGPU::VGPR_32RegClass;
11272         break;
11273       default:
11274         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11275         if (!RC)
11276           return std::make_pair(0U, nullptr);
11277         break;
11278       }
11279       break;
11280     case 'a':
11281       if (!Subtarget->hasMAIInsts())
11282         break;
11283       switch (BitWidth) {
11284       case 16:
11285         RC = &AMDGPU::AGPR_32RegClass;
11286         break;
11287       default:
11288         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11289         if (!RC)
11290           return std::make_pair(0U, nullptr);
11291         break;
11292       }
11293       break;
11294     }
11295     // We actually support i128, i16 and f16 as inline parameters
11296     // even if they are not reported as legal
11297     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11298                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11299       return std::make_pair(0U, RC);
11300   }
11301 
11302   if (Constraint.size() > 1) {
11303     if (Constraint[1] == 'v') {
11304       RC = &AMDGPU::VGPR_32RegClass;
11305     } else if (Constraint[1] == 's') {
11306       RC = &AMDGPU::SGPR_32RegClass;
11307     } else if (Constraint[1] == 'a') {
11308       RC = &AMDGPU::AGPR_32RegClass;
11309     }
11310 
11311     if (RC) {
11312       uint32_t Idx;
11313       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11314       if (!Failed && Idx < RC->getNumRegs())
11315         return std::make_pair(RC->getRegister(Idx), RC);
11316     }
11317   }
11318 
11319   // FIXME: Returns VS_32 for physical SGPR constraints
11320   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11321 }
11322 
11323 static bool isImmConstraint(StringRef Constraint) {
11324   if (Constraint.size() == 1) {
11325     switch (Constraint[0]) {
11326     default: break;
11327     case 'I':
11328     case 'J':
11329     case 'A':
11330     case 'B':
11331     case 'C':
11332       return true;
11333     }
11334   } else if (Constraint == "DA" ||
11335              Constraint == "DB") {
11336     return true;
11337   }
11338   return false;
11339 }
11340 
11341 SITargetLowering::ConstraintType
11342 SITargetLowering::getConstraintType(StringRef Constraint) const {
11343   if (Constraint.size() == 1) {
11344     switch (Constraint[0]) {
11345     default: break;
11346     case 's':
11347     case 'v':
11348     case 'a':
11349       return C_RegisterClass;
11350     }
11351   }
11352   if (isImmConstraint(Constraint)) {
11353     return C_Other;
11354   }
11355   return TargetLowering::getConstraintType(Constraint);
11356 }
11357 
11358 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11359   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11360     Val = Val & maskTrailingOnes<uint64_t>(Size);
11361   }
11362   return Val;
11363 }
11364 
11365 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11366                                                     std::string &Constraint,
11367                                                     std::vector<SDValue> &Ops,
11368                                                     SelectionDAG &DAG) const {
11369   if (isImmConstraint(Constraint)) {
11370     uint64_t Val;
11371     if (getAsmOperandConstVal(Op, Val) &&
11372         checkAsmConstraintVal(Op, Constraint, Val)) {
11373       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11374       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11375     }
11376   } else {
11377     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11378   }
11379 }
11380 
11381 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11382   unsigned Size = Op.getScalarValueSizeInBits();
11383   if (Size > 64)
11384     return false;
11385 
11386   if (Size == 16 && !Subtarget->has16BitInsts())
11387     return false;
11388 
11389   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11390     Val = C->getSExtValue();
11391     return true;
11392   }
11393   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11394     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11395     return true;
11396   }
11397   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11398     if (Size != 16 || Op.getNumOperands() != 2)
11399       return false;
11400     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11401       return false;
11402     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11403       Val = C->getSExtValue();
11404       return true;
11405     }
11406     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11407       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11408       return true;
11409     }
11410   }
11411 
11412   return false;
11413 }
11414 
11415 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11416                                              const std::string &Constraint,
11417                                              uint64_t Val) const {
11418   if (Constraint.size() == 1) {
11419     switch (Constraint[0]) {
11420     case 'I':
11421       return AMDGPU::isInlinableIntLiteral(Val);
11422     case 'J':
11423       return isInt<16>(Val);
11424     case 'A':
11425       return checkAsmConstraintValA(Op, Val);
11426     case 'B':
11427       return isInt<32>(Val);
11428     case 'C':
11429       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11430              AMDGPU::isInlinableIntLiteral(Val);
11431     default:
11432       break;
11433     }
11434   } else if (Constraint.size() == 2) {
11435     if (Constraint == "DA") {
11436       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11437       int64_t LoBits = static_cast<int32_t>(Val);
11438       return checkAsmConstraintValA(Op, HiBits, 32) &&
11439              checkAsmConstraintValA(Op, LoBits, 32);
11440     }
11441     if (Constraint == "DB") {
11442       return true;
11443     }
11444   }
11445   llvm_unreachable("Invalid asm constraint");
11446 }
11447 
11448 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11449                                               uint64_t Val,
11450                                               unsigned MaxSize) const {
11451   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11452   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11453   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11454       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11455       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11456     return true;
11457   }
11458   return false;
11459 }
11460 
11461 // Figure out which registers should be reserved for stack access. Only after
11462 // the function is legalized do we know all of the non-spill stack objects or if
11463 // calls are present.
11464 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11465   MachineRegisterInfo &MRI = MF.getRegInfo();
11466   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11467   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11468   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11469 
11470   if (Info->isEntryFunction()) {
11471     // Callable functions have fixed registers used for stack access.
11472     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11473   }
11474 
11475   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11476                              Info->getStackPtrOffsetReg()));
11477   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11478     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11479 
11480   // We need to worry about replacing the default register with itself in case
11481   // of MIR testcases missing the MFI.
11482   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11483     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11484 
11485   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11486     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11487 
11488   Info->limitOccupancy(MF);
11489 
11490   if (ST.isWave32() && !MF.empty()) {
11491     // Add VCC_HI def because many instructions marked as imp-use VCC where
11492     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11493     // having a use of undef.
11494 
11495     const SIInstrInfo *TII = ST.getInstrInfo();
11496     DebugLoc DL;
11497 
11498     MachineBasicBlock &MBB = MF.front();
11499     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11500     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11501 
11502     for (auto &MBB : MF) {
11503       for (auto &MI : MBB) {
11504         TII->fixImplicitOperands(MI);
11505       }
11506     }
11507   }
11508 
11509   TargetLoweringBase::finalizeLowering(MF);
11510 
11511   // Allocate a VGPR for future SGPR Spill if
11512   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11513   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11514   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11515       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11516     Info->reserveVGPRforSGPRSpills(MF);
11517 }
11518 
11519 void SITargetLowering::computeKnownBitsForFrameIndex(
11520   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11521   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11522 
11523   // Set the high bits to zero based on the maximum allowed scratch size per
11524   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11525   // calculation won't overflow, so assume the sign bit is never set.
11526   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11527 }
11528 
11529 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11530                                    KnownBits &Known, unsigned Dim) {
11531   unsigned MaxValue =
11532       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11533   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11534 }
11535 
11536 void SITargetLowering::computeKnownBitsForTargetInstr(
11537     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11538     const MachineRegisterInfo &MRI, unsigned Depth) const {
11539   const MachineInstr *MI = MRI.getVRegDef(R);
11540   switch (MI->getOpcode()) {
11541   case AMDGPU::G_INTRINSIC: {
11542     switch (MI->getIntrinsicID()) {
11543     case Intrinsic::amdgcn_workitem_id_x:
11544       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11545       break;
11546     case Intrinsic::amdgcn_workitem_id_y:
11547       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11548       break;
11549     case Intrinsic::amdgcn_workitem_id_z:
11550       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11551       break;
11552     case Intrinsic::amdgcn_mbcnt_lo:
11553     case Intrinsic::amdgcn_mbcnt_hi: {
11554       // These return at most the wavefront size - 1.
11555       unsigned Size = MRI.getType(R).getSizeInBits();
11556       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11557       break;
11558     }
11559     case Intrinsic::amdgcn_groupstaticsize: {
11560       // We can report everything over the maximum size as 0. We can't report
11561       // based on the actual size because we don't know if it's accurate or not
11562       // at any given point.
11563       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11564       break;
11565     }
11566     default:
11567       break;
11568     }
11569   }
11570   }
11571 }
11572 
11573 Align SITargetLowering::computeKnownAlignForTargetInstr(
11574   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11575   unsigned Depth) const {
11576   const MachineInstr *MI = MRI.getVRegDef(R);
11577   switch (MI->getOpcode()) {
11578   case AMDGPU::G_INTRINSIC:
11579   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11580     // FIXME: Can this move to generic code? What about the case where the call
11581     // site specifies a lower alignment?
11582     Intrinsic::ID IID = MI->getIntrinsicID();
11583     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11584     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11585     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11586       return *RetAlign;
11587     return Align(1);
11588   }
11589   default:
11590     return Align(1);
11591   }
11592 }
11593 
11594 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11595   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11596   const Align CacheLineAlign = Align(64);
11597 
11598   // Pre-GFX10 target did not benefit from loop alignment
11599   if (!ML || DisableLoopAlignment ||
11600       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11601       getSubtarget()->hasInstFwdPrefetchBug())
11602     return PrefAlign;
11603 
11604   // On GFX10 I$ is 4 x 64 bytes cache lines.
11605   // By default prefetcher keeps one cache line behind and reads two ahead.
11606   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11607   // behind and one ahead.
11608   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11609   // If loop fits 64 bytes it always spans no more than two cache lines and
11610   // does not need an alignment.
11611   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11612   // Else if loop is less or equal 192 bytes we need two lines behind.
11613 
11614   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11615   const MachineBasicBlock *Header = ML->getHeader();
11616   if (Header->getAlignment() != PrefAlign)
11617     return Header->getAlignment(); // Already processed.
11618 
11619   unsigned LoopSize = 0;
11620   for (const MachineBasicBlock *MBB : ML->blocks()) {
11621     // If inner loop block is aligned assume in average half of the alignment
11622     // size to be added as nops.
11623     if (MBB != Header)
11624       LoopSize += MBB->getAlignment().value() / 2;
11625 
11626     for (const MachineInstr &MI : *MBB) {
11627       LoopSize += TII->getInstSizeInBytes(MI);
11628       if (LoopSize > 192)
11629         return PrefAlign;
11630     }
11631   }
11632 
11633   if (LoopSize <= 64)
11634     return PrefAlign;
11635 
11636   if (LoopSize <= 128)
11637     return CacheLineAlign;
11638 
11639   // If any of parent loops is surrounded by prefetch instructions do not
11640   // insert new for inner loop, which would reset parent's settings.
11641   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11642     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11643       auto I = Exit->getFirstNonDebugInstr();
11644       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11645         return CacheLineAlign;
11646     }
11647   }
11648 
11649   MachineBasicBlock *Pre = ML->getLoopPreheader();
11650   MachineBasicBlock *Exit = ML->getExitBlock();
11651 
11652   if (Pre && Exit) {
11653     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11654             TII->get(AMDGPU::S_INST_PREFETCH))
11655       .addImm(1); // prefetch 2 lines behind PC
11656 
11657     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11658             TII->get(AMDGPU::S_INST_PREFETCH))
11659       .addImm(2); // prefetch 1 line behind PC
11660   }
11661 
11662   return CacheLineAlign;
11663 }
11664 
11665 LLVM_ATTRIBUTE_UNUSED
11666 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11667   assert(N->getOpcode() == ISD::CopyFromReg);
11668   do {
11669     // Follow the chain until we find an INLINEASM node.
11670     N = N->getOperand(0).getNode();
11671     if (N->getOpcode() == ISD::INLINEASM ||
11672         N->getOpcode() == ISD::INLINEASM_BR)
11673       return true;
11674   } while (N->getOpcode() == ISD::CopyFromReg);
11675   return false;
11676 }
11677 
11678 bool SITargetLowering::isSDNodeSourceOfDivergence(
11679     const SDNode *N, FunctionLoweringInfo *FLI,
11680     LegacyDivergenceAnalysis *KDA) const {
11681   switch (N->getOpcode()) {
11682   case ISD::CopyFromReg: {
11683     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11684     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11685     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11686     Register Reg = R->getReg();
11687 
11688     // FIXME: Why does this need to consider isLiveIn?
11689     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11690       return !TRI->isSGPRReg(MRI, Reg);
11691 
11692     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11693       return KDA->isDivergent(V);
11694 
11695     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11696     return !TRI->isSGPRReg(MRI, Reg);
11697   }
11698   case ISD::LOAD: {
11699     const LoadSDNode *L = cast<LoadSDNode>(N);
11700     unsigned AS = L->getAddressSpace();
11701     // A flat load may access private memory.
11702     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11703   }
11704   case ISD::CALLSEQ_END:
11705     return true;
11706   case ISD::INTRINSIC_WO_CHAIN:
11707     return AMDGPU::isIntrinsicSourceOfDivergence(
11708         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11709   case ISD::INTRINSIC_W_CHAIN:
11710     return AMDGPU::isIntrinsicSourceOfDivergence(
11711         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11712   }
11713   return false;
11714 }
11715 
11716 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11717                                                EVT VT) const {
11718   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11719   case MVT::f32:
11720     return hasFP32Denormals(DAG.getMachineFunction());
11721   case MVT::f64:
11722   case MVT::f16:
11723     return hasFP64FP16Denormals(DAG.getMachineFunction());
11724   default:
11725     return false;
11726   }
11727 }
11728 
11729 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11730                                                     const SelectionDAG &DAG,
11731                                                     bool SNaN,
11732                                                     unsigned Depth) const {
11733   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11734     const MachineFunction &MF = DAG.getMachineFunction();
11735     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11736 
11737     if (Info->getMode().DX10Clamp)
11738       return true; // Clamped to 0.
11739     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11740   }
11741 
11742   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11743                                                             SNaN, Depth);
11744 }
11745 
11746 // Global FP atomic instructions have a hardcoded FP mode and do not support
11747 // FP32 denormals, and only support v2f16 denormals.
11748 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
11749   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
11750   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
11751   if (&Flt == &APFloat::IEEEsingle())
11752     return DenormMode == DenormalMode::getPreserveSign();
11753   return DenormMode == DenormalMode::getIEEE();
11754 }
11755 
11756 TargetLowering::AtomicExpansionKind
11757 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11758   switch (RMW->getOperation()) {
11759   case AtomicRMWInst::FAdd: {
11760     Type *Ty = RMW->getType();
11761 
11762     // We don't have a way to support 16-bit atomics now, so just leave them
11763     // as-is.
11764     if (Ty->isHalfTy())
11765       return AtomicExpansionKind::None;
11766 
11767     if (!Ty->isFloatTy())
11768       return AtomicExpansionKind::CmpXChg;
11769 
11770     // TODO: Do have these for flat. Older targets also had them for buffers.
11771     unsigned AS = RMW->getPointerAddressSpace();
11772 
11773     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11774       if (!fpModeMatchesGlobalFPAtomicMode(RMW))
11775         return AtomicExpansionKind::CmpXChg;
11776 
11777       return RMW->use_empty() ? AtomicExpansionKind::None :
11778                                 AtomicExpansionKind::CmpXChg;
11779     }
11780 
11781     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
11782     // to round-to-nearest-even.
11783     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11784       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11785   }
11786   default:
11787     break;
11788   }
11789 
11790   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11791 }
11792 
11793 const TargetRegisterClass *
11794 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11795   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11796   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11797   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11798     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11799                                                : &AMDGPU::SReg_32RegClass;
11800   if (!TRI->isSGPRClass(RC) && !isDivergent)
11801     return TRI->getEquivalentSGPRClass(RC);
11802   else if (TRI->isSGPRClass(RC) && isDivergent)
11803     return TRI->getEquivalentVGPRClass(RC);
11804 
11805   return RC;
11806 }
11807 
11808 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11809 // uniform values (as produced by the mask results of control flow intrinsics)
11810 // used outside of divergent blocks. The phi users need to also be treated as
11811 // always uniform.
11812 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11813                       unsigned WaveSize) {
11814   // FIXME: We asssume we never cast the mask results of a control flow
11815   // intrinsic.
11816   // Early exit if the type won't be consistent as a compile time hack.
11817   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11818   if (!IT || IT->getBitWidth() != WaveSize)
11819     return false;
11820 
11821   if (!isa<Instruction>(V))
11822     return false;
11823   if (!Visited.insert(V).second)
11824     return false;
11825   bool Result = false;
11826   for (auto U : V->users()) {
11827     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11828       if (V == U->getOperand(1)) {
11829         switch (Intrinsic->getIntrinsicID()) {
11830         default:
11831           Result = false;
11832           break;
11833         case Intrinsic::amdgcn_if_break:
11834         case Intrinsic::amdgcn_if:
11835         case Intrinsic::amdgcn_else:
11836           Result = true;
11837           break;
11838         }
11839       }
11840       if (V == U->getOperand(0)) {
11841         switch (Intrinsic->getIntrinsicID()) {
11842         default:
11843           Result = false;
11844           break;
11845         case Intrinsic::amdgcn_end_cf:
11846         case Intrinsic::amdgcn_loop:
11847           Result = true;
11848           break;
11849         }
11850       }
11851     } else {
11852       Result = hasCFUser(U, Visited, WaveSize);
11853     }
11854     if (Result)
11855       break;
11856   }
11857   return Result;
11858 }
11859 
11860 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11861                                                const Value *V) const {
11862   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11863     if (CI->isInlineAsm()) {
11864       // FIXME: This cannot give a correct answer. This should only trigger in
11865       // the case where inline asm returns mixed SGPR and VGPR results, used
11866       // outside the defining block. We don't have a specific result to
11867       // consider, so this assumes if any value is SGPR, the overall register
11868       // also needs to be SGPR.
11869       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11870       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11871           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11872       for (auto &TC : TargetConstraints) {
11873         if (TC.Type == InlineAsm::isOutput) {
11874           ComputeConstraintToUse(TC, SDValue());
11875           unsigned AssignedReg;
11876           const TargetRegisterClass *RC;
11877           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11878               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11879           if (RC) {
11880             MachineRegisterInfo &MRI = MF.getRegInfo();
11881             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11882               return true;
11883             else if (SIRI->isSGPRClass(RC))
11884               return true;
11885           }
11886         }
11887       }
11888     }
11889   }
11890   SmallPtrSet<const Value *, 16> Visited;
11891   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11892 }
11893 
11894 std::pair<int, MVT>
11895 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11896                                           Type *Ty) const {
11897   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11898   auto Size = DL.getTypeSizeInBits(Ty);
11899   // Maximum load or store can handle 8 dwords for scalar and 4 for
11900   // vector ALU. Let's assume anything above 8 dwords is expensive
11901   // even if legal.
11902   if (Size <= 256)
11903     return Cost;
11904 
11905   Cost.first = (Size + 255) / 256;
11906   return Cost;
11907 }
11908