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 (!SIInstrInfo::isLegalMUBUFImmOffset(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->hasUnalignedDSAccess() &&
1437         Subtarget->hasUnalignedAccessMode() &&
1438         !Subtarget->hasLDSMisalignedBug()) {
1439       if (IsFast)
1440         *IsFast = Alignment != Align(2);
1441       return true;
1442     }
1443 
1444     if (Size == 64) {
1445       // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1446       // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1447       // with adjacent offsets.
1448       bool AlignedBy4 = Alignment >= Align(4);
1449       if (IsFast)
1450         *IsFast = AlignedBy4;
1451 
1452       return AlignedBy4;
1453     }
1454     if (Size == 96) {
1455       // ds_read/write_b96 require 16-byte alignment on gfx8 and older.
1456       bool Aligned = Alignment >= Align(16);
1457       if (IsFast)
1458         *IsFast = Aligned;
1459 
1460       return Aligned;
1461     }
1462     if (Size == 128) {
1463       // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we
1464       // can do a 8 byte aligned, 16 byte access in a single operation using
1465       // ds_read2/write2_b64.
1466       bool Aligned = Alignment >= Align(8);
1467       if (IsFast)
1468         *IsFast = Aligned;
1469 
1470       return Aligned;
1471     }
1472   }
1473 
1474   // FIXME: We have to be conservative here and assume that flat operations
1475   // will access scratch.  If we had access to the IR function, then we
1476   // could determine if any private memory was used in the function.
1477   if (!Subtarget->hasUnalignedScratchAccess() &&
1478       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1479        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1480     bool AlignedBy4 = Alignment >= Align(4);
1481     if (IsFast)
1482       *IsFast = AlignedBy4;
1483 
1484     return AlignedBy4;
1485   }
1486 
1487   if (Subtarget->hasUnalignedBufferAccess() &&
1488       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1489         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1490     // If we have an uniform constant load, it still requires using a slow
1491     // buffer instruction if unaligned.
1492     if (IsFast) {
1493       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1494       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1495       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1496                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1497         Alignment >= Align(4) : Alignment != Align(2);
1498     }
1499 
1500     return true;
1501   }
1502 
1503   // Smaller than dword value must be aligned.
1504   if (Size < 32)
1505     return false;
1506 
1507   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1508   // byte-address are ignored, thus forcing Dword alignment.
1509   // This applies to private, global, and constant memory.
1510   if (IsFast)
1511     *IsFast = true;
1512 
1513   return Size >= 32 && Alignment >= Align(4);
1514 }
1515 
1516 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1517     EVT VT, unsigned AddrSpace, unsigned Alignment,
1518     MachineMemOperand::Flags Flags, bool *IsFast) const {
1519   if (IsFast)
1520     *IsFast = false;
1521 
1522   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1523   // which isn't a simple VT.
1524   // Until MVT is extended to handle this, simply check for the size and
1525   // rely on the condition below: allow accesses if the size is a multiple of 4.
1526   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1527                            VT.getStoreSize() > 16)) {
1528     return false;
1529   }
1530 
1531   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1532                                             Align(Alignment), Flags, IsFast);
1533 }
1534 
1535 EVT SITargetLowering::getOptimalMemOpType(
1536     const MemOp &Op, const AttributeList &FuncAttributes) const {
1537   // FIXME: Should account for address space here.
1538 
1539   // The default fallback uses the private pointer size as a guess for a type to
1540   // use. Make sure we switch these to 64-bit accesses.
1541 
1542   if (Op.size() >= 16 &&
1543       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1544     return MVT::v4i32;
1545 
1546   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1547     return MVT::v2i32;
1548 
1549   // Use the default.
1550   return MVT::Other;
1551 }
1552 
1553 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1554   const MemSDNode *MemNode = cast<MemSDNode>(N);
1555   const Value *Ptr = MemNode->getMemOperand()->getValue();
1556   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1557   return I && I->getMetadata("amdgpu.noclobber");
1558 }
1559 
1560 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1561                                            unsigned DestAS) const {
1562   // Flat -> private/local is a simple truncate.
1563   // Flat -> global is no-op
1564   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1565     return true;
1566 
1567   const GCNTargetMachine &TM =
1568       static_cast<const GCNTargetMachine &>(getTargetMachine());
1569   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1570 }
1571 
1572 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1573   const MemSDNode *MemNode = cast<MemSDNode>(N);
1574 
1575   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1576 }
1577 
1578 TargetLoweringBase::LegalizeTypeAction
1579 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1580   int NumElts = VT.getVectorNumElements();
1581   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1582     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1583   return TargetLoweringBase::getPreferredVectorAction(VT);
1584 }
1585 
1586 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1587                                                          Type *Ty) const {
1588   // FIXME: Could be smarter if called for vector constants.
1589   return true;
1590 }
1591 
1592 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1593   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1594     switch (Op) {
1595     case ISD::LOAD:
1596     case ISD::STORE:
1597 
1598     // These operations are done with 32-bit instructions anyway.
1599     case ISD::AND:
1600     case ISD::OR:
1601     case ISD::XOR:
1602     case ISD::SELECT:
1603       // TODO: Extensions?
1604       return true;
1605     default:
1606       return false;
1607     }
1608   }
1609 
1610   // SimplifySetCC uses this function to determine whether or not it should
1611   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1612   if (VT == MVT::i1 && Op == ISD::SETCC)
1613     return false;
1614 
1615   return TargetLowering::isTypeDesirableForOp(Op, VT);
1616 }
1617 
1618 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1619                                                    const SDLoc &SL,
1620                                                    SDValue Chain,
1621                                                    uint64_t Offset) const {
1622   const DataLayout &DL = DAG.getDataLayout();
1623   MachineFunction &MF = DAG.getMachineFunction();
1624   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1625 
1626   const ArgDescriptor *InputPtrReg;
1627   const TargetRegisterClass *RC;
1628   LLT ArgTy;
1629 
1630   std::tie(InputPtrReg, RC, ArgTy) =
1631       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1632 
1633   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1634   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1635   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1636     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1637 
1638   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1639 }
1640 
1641 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1642                                             const SDLoc &SL) const {
1643   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1644                                                FIRST_IMPLICIT);
1645   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1646 }
1647 
1648 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1649                                          const SDLoc &SL, SDValue Val,
1650                                          bool Signed,
1651                                          const ISD::InputArg *Arg) const {
1652   // First, if it is a widened vector, narrow it.
1653   if (VT.isVector() &&
1654       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1655     EVT NarrowedVT =
1656         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1657                          VT.getVectorNumElements());
1658     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1659                       DAG.getConstant(0, SL, MVT::i32));
1660   }
1661 
1662   // Then convert the vector elements or scalar value.
1663   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1664       VT.bitsLT(MemVT)) {
1665     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1666     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1667   }
1668 
1669   if (MemVT.isFloatingPoint())
1670     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1671   else if (Signed)
1672     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1673   else
1674     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1675 
1676   return Val;
1677 }
1678 
1679 SDValue SITargetLowering::lowerKernargMemParameter(
1680     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1681     uint64_t Offset, Align Alignment, bool Signed,
1682     const ISD::InputArg *Arg) const {
1683   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1684 
1685   // Try to avoid using an extload by loading earlier than the argument address,
1686   // and extracting the relevant bits. The load should hopefully be merged with
1687   // the previous argument.
1688   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1689     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1690     int64_t AlignDownOffset = alignDown(Offset, 4);
1691     int64_t OffsetDiff = Offset - AlignDownOffset;
1692 
1693     EVT IntVT = MemVT.changeTypeToInteger();
1694 
1695     // TODO: If we passed in the base kernel offset we could have a better
1696     // alignment than 4, but we don't really need it.
1697     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1698     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1699                                MachineMemOperand::MODereferenceable |
1700                                    MachineMemOperand::MOInvariant);
1701 
1702     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1703     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1704 
1705     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1706     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1707     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1708 
1709 
1710     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1711   }
1712 
1713   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1714   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1715                              MachineMemOperand::MODereferenceable |
1716                                  MachineMemOperand::MOInvariant);
1717 
1718   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1719   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1720 }
1721 
1722 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1723                                               const SDLoc &SL, SDValue Chain,
1724                                               const ISD::InputArg &Arg) const {
1725   MachineFunction &MF = DAG.getMachineFunction();
1726   MachineFrameInfo &MFI = MF.getFrameInfo();
1727 
1728   if (Arg.Flags.isByVal()) {
1729     unsigned Size = Arg.Flags.getByValSize();
1730     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1731     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1732   }
1733 
1734   unsigned ArgOffset = VA.getLocMemOffset();
1735   unsigned ArgSize = VA.getValVT().getStoreSize();
1736 
1737   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1738 
1739   // Create load nodes to retrieve arguments from the stack.
1740   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1741   SDValue ArgValue;
1742 
1743   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1744   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1745   MVT MemVT = VA.getValVT();
1746 
1747   switch (VA.getLocInfo()) {
1748   default:
1749     break;
1750   case CCValAssign::BCvt:
1751     MemVT = VA.getLocVT();
1752     break;
1753   case CCValAssign::SExt:
1754     ExtType = ISD::SEXTLOAD;
1755     break;
1756   case CCValAssign::ZExt:
1757     ExtType = ISD::ZEXTLOAD;
1758     break;
1759   case CCValAssign::AExt:
1760     ExtType = ISD::EXTLOAD;
1761     break;
1762   }
1763 
1764   ArgValue = DAG.getExtLoad(
1765     ExtType, SL, VA.getLocVT(), Chain, FIN,
1766     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1767     MemVT);
1768   return ArgValue;
1769 }
1770 
1771 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1772   const SIMachineFunctionInfo &MFI,
1773   EVT VT,
1774   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1775   const ArgDescriptor *Reg;
1776   const TargetRegisterClass *RC;
1777   LLT Ty;
1778 
1779   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1780   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1781 }
1782 
1783 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1784                                    CallingConv::ID CallConv,
1785                                    ArrayRef<ISD::InputArg> Ins,
1786                                    BitVector &Skipped,
1787                                    FunctionType *FType,
1788                                    SIMachineFunctionInfo *Info) {
1789   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1790     const ISD::InputArg *Arg = &Ins[I];
1791 
1792     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1793            "vector type argument should have been split");
1794 
1795     // First check if it's a PS input addr.
1796     if (CallConv == CallingConv::AMDGPU_PS &&
1797         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1798       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1799 
1800       // Inconveniently only the first part of the split is marked as isSplit,
1801       // so skip to the end. We only want to increment PSInputNum once for the
1802       // entire split argument.
1803       if (Arg->Flags.isSplit()) {
1804         while (!Arg->Flags.isSplitEnd()) {
1805           assert((!Arg->VT.isVector() ||
1806                   Arg->VT.getScalarSizeInBits() == 16) &&
1807                  "unexpected vector split in ps argument type");
1808           if (!SkipArg)
1809             Splits.push_back(*Arg);
1810           Arg = &Ins[++I];
1811         }
1812       }
1813 
1814       if (SkipArg) {
1815         // We can safely skip PS inputs.
1816         Skipped.set(Arg->getOrigArgIndex());
1817         ++PSInputNum;
1818         continue;
1819       }
1820 
1821       Info->markPSInputAllocated(PSInputNum);
1822       if (Arg->Used)
1823         Info->markPSInputEnabled(PSInputNum);
1824 
1825       ++PSInputNum;
1826     }
1827 
1828     Splits.push_back(*Arg);
1829   }
1830 }
1831 
1832 // Allocate special inputs passed in VGPRs.
1833 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1834                                                       MachineFunction &MF,
1835                                                       const SIRegisterInfo &TRI,
1836                                                       SIMachineFunctionInfo &Info) const {
1837   const LLT S32 = LLT::scalar(32);
1838   MachineRegisterInfo &MRI = MF.getRegInfo();
1839 
1840   if (Info.hasWorkItemIDX()) {
1841     Register Reg = AMDGPU::VGPR0;
1842     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1843 
1844     CCInfo.AllocateReg(Reg);
1845     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1846   }
1847 
1848   if (Info.hasWorkItemIDY()) {
1849     Register Reg = AMDGPU::VGPR1;
1850     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1851 
1852     CCInfo.AllocateReg(Reg);
1853     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1854   }
1855 
1856   if (Info.hasWorkItemIDZ()) {
1857     Register Reg = AMDGPU::VGPR2;
1858     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1859 
1860     CCInfo.AllocateReg(Reg);
1861     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1862   }
1863 }
1864 
1865 // Try to allocate a VGPR at the end of the argument list, or if no argument
1866 // VGPRs are left allocating a stack slot.
1867 // If \p Mask is is given it indicates bitfield position in the register.
1868 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1869 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1870                                          ArgDescriptor Arg = ArgDescriptor()) {
1871   if (Arg.isSet())
1872     return ArgDescriptor::createArg(Arg, Mask);
1873 
1874   ArrayRef<MCPhysReg> ArgVGPRs
1875     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1876   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1877   if (RegIdx == ArgVGPRs.size()) {
1878     // Spill to stack required.
1879     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1880 
1881     return ArgDescriptor::createStack(Offset, Mask);
1882   }
1883 
1884   unsigned Reg = ArgVGPRs[RegIdx];
1885   Reg = CCInfo.AllocateReg(Reg);
1886   assert(Reg != AMDGPU::NoRegister);
1887 
1888   MachineFunction &MF = CCInfo.getMachineFunction();
1889   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1890   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1891   return ArgDescriptor::createRegister(Reg, Mask);
1892 }
1893 
1894 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1895                                              const TargetRegisterClass *RC,
1896                                              unsigned NumArgRegs) {
1897   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1898   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1899   if (RegIdx == ArgSGPRs.size())
1900     report_fatal_error("ran out of SGPRs for arguments");
1901 
1902   unsigned Reg = ArgSGPRs[RegIdx];
1903   Reg = CCInfo.AllocateReg(Reg);
1904   assert(Reg != AMDGPU::NoRegister);
1905 
1906   MachineFunction &MF = CCInfo.getMachineFunction();
1907   MF.addLiveIn(Reg, RC);
1908   return ArgDescriptor::createRegister(Reg);
1909 }
1910 
1911 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1912   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1913 }
1914 
1915 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1916   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1917 }
1918 
1919 /// Allocate implicit function VGPR arguments at the end of allocated user
1920 /// arguments.
1921 void SITargetLowering::allocateSpecialInputVGPRs(
1922   CCState &CCInfo, MachineFunction &MF,
1923   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1924   const unsigned Mask = 0x3ff;
1925   ArgDescriptor Arg;
1926 
1927   if (Info.hasWorkItemIDX()) {
1928     Arg = allocateVGPR32Input(CCInfo, Mask);
1929     Info.setWorkItemIDX(Arg);
1930   }
1931 
1932   if (Info.hasWorkItemIDY()) {
1933     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1934     Info.setWorkItemIDY(Arg);
1935   }
1936 
1937   if (Info.hasWorkItemIDZ())
1938     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1939 }
1940 
1941 /// Allocate implicit function VGPR arguments in fixed registers.
1942 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1943   CCState &CCInfo, MachineFunction &MF,
1944   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1945   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1946   if (!Reg)
1947     report_fatal_error("failed to allocated VGPR for implicit arguments");
1948 
1949   const unsigned Mask = 0x3ff;
1950   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1951   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1952   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1953 }
1954 
1955 void SITargetLowering::allocateSpecialInputSGPRs(
1956   CCState &CCInfo,
1957   MachineFunction &MF,
1958   const SIRegisterInfo &TRI,
1959   SIMachineFunctionInfo &Info) const {
1960   auto &ArgInfo = Info.getArgInfo();
1961 
1962   // TODO: Unify handling with private memory pointers.
1963 
1964   if (Info.hasDispatchPtr())
1965     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1966 
1967   if (Info.hasQueuePtr())
1968     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1969 
1970   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1971   // constant offset from the kernarg segment.
1972   if (Info.hasImplicitArgPtr())
1973     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1974 
1975   if (Info.hasDispatchID())
1976     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1977 
1978   // flat_scratch_init is not applicable for non-kernel functions.
1979 
1980   if (Info.hasWorkGroupIDX())
1981     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1982 
1983   if (Info.hasWorkGroupIDY())
1984     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1985 
1986   if (Info.hasWorkGroupIDZ())
1987     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1988 }
1989 
1990 // Allocate special inputs passed in user SGPRs.
1991 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1992                                             MachineFunction &MF,
1993                                             const SIRegisterInfo &TRI,
1994                                             SIMachineFunctionInfo &Info) const {
1995   if (Info.hasImplicitBufferPtr()) {
1996     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1997     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1998     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1999   }
2000 
2001   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2002   if (Info.hasPrivateSegmentBuffer()) {
2003     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2004     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2005     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2006   }
2007 
2008   if (Info.hasDispatchPtr()) {
2009     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2010     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2011     CCInfo.AllocateReg(DispatchPtrReg);
2012   }
2013 
2014   if (Info.hasQueuePtr()) {
2015     Register QueuePtrReg = Info.addQueuePtr(TRI);
2016     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2017     CCInfo.AllocateReg(QueuePtrReg);
2018   }
2019 
2020   if (Info.hasKernargSegmentPtr()) {
2021     MachineRegisterInfo &MRI = MF.getRegInfo();
2022     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2023     CCInfo.AllocateReg(InputPtrReg);
2024 
2025     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2026     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2027   }
2028 
2029   if (Info.hasDispatchID()) {
2030     Register DispatchIDReg = Info.addDispatchID(TRI);
2031     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2032     CCInfo.AllocateReg(DispatchIDReg);
2033   }
2034 
2035   if (Info.hasFlatScratchInit()) {
2036     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2037     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2038     CCInfo.AllocateReg(FlatScratchInitReg);
2039   }
2040 
2041   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2042   // these from the dispatch pointer.
2043 }
2044 
2045 // Allocate special input registers that are initialized per-wave.
2046 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2047                                            MachineFunction &MF,
2048                                            SIMachineFunctionInfo &Info,
2049                                            CallingConv::ID CallConv,
2050                                            bool IsShader) const {
2051   if (Info.hasWorkGroupIDX()) {
2052     Register Reg = Info.addWorkGroupIDX();
2053     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2054     CCInfo.AllocateReg(Reg);
2055   }
2056 
2057   if (Info.hasWorkGroupIDY()) {
2058     Register Reg = Info.addWorkGroupIDY();
2059     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2060     CCInfo.AllocateReg(Reg);
2061   }
2062 
2063   if (Info.hasWorkGroupIDZ()) {
2064     Register Reg = Info.addWorkGroupIDZ();
2065     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2066     CCInfo.AllocateReg(Reg);
2067   }
2068 
2069   if (Info.hasWorkGroupInfo()) {
2070     Register Reg = Info.addWorkGroupInfo();
2071     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2072     CCInfo.AllocateReg(Reg);
2073   }
2074 
2075   if (Info.hasPrivateSegmentWaveByteOffset()) {
2076     // Scratch wave offset passed in system SGPR.
2077     unsigned PrivateSegmentWaveByteOffsetReg;
2078 
2079     if (IsShader) {
2080       PrivateSegmentWaveByteOffsetReg =
2081         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2082 
2083       // This is true if the scratch wave byte offset doesn't have a fixed
2084       // location.
2085       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2086         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2087         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2088       }
2089     } else
2090       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2091 
2092     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2093     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2094   }
2095 }
2096 
2097 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2098                                      MachineFunction &MF,
2099                                      const SIRegisterInfo &TRI,
2100                                      SIMachineFunctionInfo &Info) {
2101   // Now that we've figured out where the scratch register inputs are, see if
2102   // should reserve the arguments and use them directly.
2103   MachineFrameInfo &MFI = MF.getFrameInfo();
2104   bool HasStackObjects = MFI.hasStackObjects();
2105   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2106 
2107   // Record that we know we have non-spill stack objects so we don't need to
2108   // check all stack objects later.
2109   if (HasStackObjects)
2110     Info.setHasNonSpillStackObjects(true);
2111 
2112   // Everything live out of a block is spilled with fast regalloc, so it's
2113   // almost certain that spilling will be required.
2114   if (TM.getOptLevel() == CodeGenOpt::None)
2115     HasStackObjects = true;
2116 
2117   // For now assume stack access is needed in any callee functions, so we need
2118   // the scratch registers to pass in.
2119   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2120 
2121   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2122     // If we have stack objects, we unquestionably need the private buffer
2123     // resource. For the Code Object V2 ABI, this will be the first 4 user
2124     // SGPR inputs. We can reserve those and use them directly.
2125 
2126     Register PrivateSegmentBufferReg =
2127         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2128     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2129   } else {
2130     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2131     // We tentatively reserve the last registers (skipping the last registers
2132     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2133     // we'll replace these with the ones immediately after those which were
2134     // really allocated. In the prologue copies will be inserted from the
2135     // argument to these reserved registers.
2136 
2137     // Without HSA, relocations are used for the scratch pointer and the
2138     // buffer resource setup is always inserted in the prologue. Scratch wave
2139     // offset is still in an input SGPR.
2140     Info.setScratchRSrcReg(ReservedBufferReg);
2141   }
2142 
2143   MachineRegisterInfo &MRI = MF.getRegInfo();
2144 
2145   // For entry functions we have to set up the stack pointer if we use it,
2146   // whereas non-entry functions get this "for free". This means there is no
2147   // intrinsic advantage to using S32 over S34 in cases where we do not have
2148   // calls but do need a frame pointer (i.e. if we are requested to have one
2149   // because frame pointer elimination is disabled). To keep things simple we
2150   // only ever use S32 as the call ABI stack pointer, and so using it does not
2151   // imply we need a separate frame pointer.
2152   //
2153   // Try to use s32 as the SP, but move it if it would interfere with input
2154   // arguments. This won't work with calls though.
2155   //
2156   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2157   // registers.
2158   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2159     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2160   } else {
2161     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2162 
2163     if (MFI.hasCalls())
2164       report_fatal_error("call in graphics shader with too many input SGPRs");
2165 
2166     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2167       if (!MRI.isLiveIn(Reg)) {
2168         Info.setStackPtrOffsetReg(Reg);
2169         break;
2170       }
2171     }
2172 
2173     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2174       report_fatal_error("failed to find register for SP");
2175   }
2176 
2177   // hasFP should be accurate for entry functions even before the frame is
2178   // finalized, because it does not rely on the known stack size, only
2179   // properties like whether variable sized objects are present.
2180   if (ST.getFrameLowering()->hasFP(MF)) {
2181     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2182   }
2183 }
2184 
2185 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2186   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2187   return !Info->isEntryFunction();
2188 }
2189 
2190 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2191 
2192 }
2193 
2194 void SITargetLowering::insertCopiesSplitCSR(
2195   MachineBasicBlock *Entry,
2196   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2197   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2198 
2199   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2200   if (!IStart)
2201     return;
2202 
2203   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2204   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2205   MachineBasicBlock::iterator MBBI = Entry->begin();
2206   for (const MCPhysReg *I = IStart; *I; ++I) {
2207     const TargetRegisterClass *RC = nullptr;
2208     if (AMDGPU::SReg_64RegClass.contains(*I))
2209       RC = &AMDGPU::SGPR_64RegClass;
2210     else if (AMDGPU::SReg_32RegClass.contains(*I))
2211       RC = &AMDGPU::SGPR_32RegClass;
2212     else
2213       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2214 
2215     Register NewVR = MRI->createVirtualRegister(RC);
2216     // Create copy from CSR to a virtual register.
2217     Entry->addLiveIn(*I);
2218     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2219       .addReg(*I);
2220 
2221     // Insert the copy-back instructions right before the terminator.
2222     for (auto *Exit : Exits)
2223       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2224               TII->get(TargetOpcode::COPY), *I)
2225         .addReg(NewVR);
2226   }
2227 }
2228 
2229 SDValue SITargetLowering::LowerFormalArguments(
2230     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2231     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2232     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2233   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2234 
2235   MachineFunction &MF = DAG.getMachineFunction();
2236   const Function &Fn = MF.getFunction();
2237   FunctionType *FType = MF.getFunction().getFunctionType();
2238   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2239 
2240   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2241     DiagnosticInfoUnsupported NoGraphicsHSA(
2242         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2243     DAG.getContext()->diagnose(NoGraphicsHSA);
2244     return DAG.getEntryNode();
2245   }
2246 
2247   SmallVector<ISD::InputArg, 16> Splits;
2248   SmallVector<CCValAssign, 16> ArgLocs;
2249   BitVector Skipped(Ins.size());
2250   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2251                  *DAG.getContext());
2252 
2253   bool IsShader = AMDGPU::isShader(CallConv);
2254   bool IsKernel = AMDGPU::isKernel(CallConv);
2255   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2256 
2257   if (IsShader) {
2258     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2259 
2260     // At least one interpolation mode must be enabled or else the GPU will
2261     // hang.
2262     //
2263     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2264     // set PSInputAddr, the user wants to enable some bits after the compilation
2265     // based on run-time states. Since we can't know what the final PSInputEna
2266     // will look like, so we shouldn't do anything here and the user should take
2267     // responsibility for the correct programming.
2268     //
2269     // Otherwise, the following restrictions apply:
2270     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2271     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2272     //   enabled too.
2273     if (CallConv == CallingConv::AMDGPU_PS) {
2274       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2275            ((Info->getPSInputAddr() & 0xF) == 0 &&
2276             Info->isPSInputAllocated(11))) {
2277         CCInfo.AllocateReg(AMDGPU::VGPR0);
2278         CCInfo.AllocateReg(AMDGPU::VGPR1);
2279         Info->markPSInputAllocated(0);
2280         Info->markPSInputEnabled(0);
2281       }
2282       if (Subtarget->isAmdPalOS()) {
2283         // For isAmdPalOS, the user does not enable some bits after compilation
2284         // based on run-time states; the register values being generated here are
2285         // the final ones set in hardware. Therefore we need to apply the
2286         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2287         // a bit is set in PSInputAddr but not PSInputEnable is where the
2288         // frontend set up an input arg for a particular interpolation mode, but
2289         // nothing uses that input arg. Really we should have an earlier pass
2290         // that removes such an arg.)
2291         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2292         if ((PsInputBits & 0x7F) == 0 ||
2293             ((PsInputBits & 0xF) == 0 &&
2294              (PsInputBits >> 11 & 1)))
2295           Info->markPSInputEnabled(
2296               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2297       }
2298     }
2299 
2300     assert(!Info->hasDispatchPtr() &&
2301            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2302            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2303            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2304            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2305            !Info->hasWorkItemIDZ());
2306   } else if (IsKernel) {
2307     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2308   } else {
2309     Splits.append(Ins.begin(), Ins.end());
2310   }
2311 
2312   if (IsEntryFunc) {
2313     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2314     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2315   } else {
2316     // For the fixed ABI, pass workitem IDs in the last argument register.
2317     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2318       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2319   }
2320 
2321   if (IsKernel) {
2322     analyzeFormalArgumentsCompute(CCInfo, Ins);
2323   } else {
2324     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2325     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2326   }
2327 
2328   SmallVector<SDValue, 16> Chains;
2329 
2330   // FIXME: This is the minimum kernel argument alignment. We should improve
2331   // this to the maximum alignment of the arguments.
2332   //
2333   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2334   // kern arg offset.
2335   const Align KernelArgBaseAlign = Align(16);
2336 
2337   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2338     const ISD::InputArg &Arg = Ins[i];
2339     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2340       InVals.push_back(DAG.getUNDEF(Arg.VT));
2341       continue;
2342     }
2343 
2344     CCValAssign &VA = ArgLocs[ArgIdx++];
2345     MVT VT = VA.getLocVT();
2346 
2347     if (IsEntryFunc && VA.isMemLoc()) {
2348       VT = Ins[i].VT;
2349       EVT MemVT = VA.getLocVT();
2350 
2351       const uint64_t Offset = VA.getLocMemOffset();
2352       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2353 
2354       if (Arg.Flags.isByRef()) {
2355         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2356 
2357         const GCNTargetMachine &TM =
2358             static_cast<const GCNTargetMachine &>(getTargetMachine());
2359         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2360                                     Arg.Flags.getPointerAddrSpace())) {
2361           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2362                                      Arg.Flags.getPointerAddrSpace());
2363         }
2364 
2365         InVals.push_back(Ptr);
2366         continue;
2367       }
2368 
2369       SDValue Arg = lowerKernargMemParameter(
2370         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2371       Chains.push_back(Arg.getValue(1));
2372 
2373       auto *ParamTy =
2374         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2375       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2376           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2377                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2378         // On SI local pointers are just offsets into LDS, so they are always
2379         // less than 16-bits.  On CI and newer they could potentially be
2380         // real pointers, so we can't guarantee their size.
2381         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2382                           DAG.getValueType(MVT::i16));
2383       }
2384 
2385       InVals.push_back(Arg);
2386       continue;
2387     } else if (!IsEntryFunc && VA.isMemLoc()) {
2388       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2389       InVals.push_back(Val);
2390       if (!Arg.Flags.isByVal())
2391         Chains.push_back(Val.getValue(1));
2392       continue;
2393     }
2394 
2395     assert(VA.isRegLoc() && "Parameter must be in a register!");
2396 
2397     Register Reg = VA.getLocReg();
2398     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2399     EVT ValVT = VA.getValVT();
2400 
2401     Reg = MF.addLiveIn(Reg, RC);
2402     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2403 
2404     if (Arg.Flags.isSRet()) {
2405       // The return object should be reasonably addressable.
2406 
2407       // FIXME: This helps when the return is a real sret. If it is a
2408       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2409       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2410       unsigned NumBits
2411         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2412       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2413         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2414     }
2415 
2416     // If this is an 8 or 16-bit value, it is really passed promoted
2417     // to 32 bits. Insert an assert[sz]ext to capture this, then
2418     // truncate to the right size.
2419     switch (VA.getLocInfo()) {
2420     case CCValAssign::Full:
2421       break;
2422     case CCValAssign::BCvt:
2423       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2424       break;
2425     case CCValAssign::SExt:
2426       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2427                         DAG.getValueType(ValVT));
2428       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2429       break;
2430     case CCValAssign::ZExt:
2431       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2432                         DAG.getValueType(ValVT));
2433       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2434       break;
2435     case CCValAssign::AExt:
2436       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2437       break;
2438     default:
2439       llvm_unreachable("Unknown loc info!");
2440     }
2441 
2442     InVals.push_back(Val);
2443   }
2444 
2445   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2446     // Special inputs come after user arguments.
2447     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2448   }
2449 
2450   // Start adding system SGPRs.
2451   if (IsEntryFunc) {
2452     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2453   } else {
2454     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2455     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2456   }
2457 
2458   auto &ArgUsageInfo =
2459     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2460   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2461 
2462   unsigned StackArgSize = CCInfo.getNextStackOffset();
2463   Info->setBytesInStackArgArea(StackArgSize);
2464 
2465   return Chains.empty() ? Chain :
2466     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2467 }
2468 
2469 // TODO: If return values can't fit in registers, we should return as many as
2470 // possible in registers before passing on stack.
2471 bool SITargetLowering::CanLowerReturn(
2472   CallingConv::ID CallConv,
2473   MachineFunction &MF, bool IsVarArg,
2474   const SmallVectorImpl<ISD::OutputArg> &Outs,
2475   LLVMContext &Context) const {
2476   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2477   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2478   // for shaders. Vector types should be explicitly handled by CC.
2479   if (AMDGPU::isEntryFunctionCC(CallConv))
2480     return true;
2481 
2482   SmallVector<CCValAssign, 16> RVLocs;
2483   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2484   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2485 }
2486 
2487 SDValue
2488 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2489                               bool isVarArg,
2490                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2491                               const SmallVectorImpl<SDValue> &OutVals,
2492                               const SDLoc &DL, SelectionDAG &DAG) const {
2493   MachineFunction &MF = DAG.getMachineFunction();
2494   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2495 
2496   if (AMDGPU::isKernel(CallConv)) {
2497     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2498                                              OutVals, DL, DAG);
2499   }
2500 
2501   bool IsShader = AMDGPU::isShader(CallConv);
2502 
2503   Info->setIfReturnsVoid(Outs.empty());
2504   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2505 
2506   // CCValAssign - represent the assignment of the return value to a location.
2507   SmallVector<CCValAssign, 48> RVLocs;
2508   SmallVector<ISD::OutputArg, 48> Splits;
2509 
2510   // CCState - Info about the registers and stack slots.
2511   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2512                  *DAG.getContext());
2513 
2514   // Analyze outgoing return values.
2515   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2516 
2517   SDValue Flag;
2518   SmallVector<SDValue, 48> RetOps;
2519   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2520 
2521   // Add return address for callable functions.
2522   if (!Info->isEntryFunction()) {
2523     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2524     SDValue ReturnAddrReg = CreateLiveInRegister(
2525       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2526 
2527     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2528         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2529         MVT::i64);
2530     Chain =
2531         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2532     Flag = Chain.getValue(1);
2533     RetOps.push_back(ReturnAddrVirtualReg);
2534   }
2535 
2536   // Copy the result values into the output registers.
2537   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2538        ++I, ++RealRVLocIdx) {
2539     CCValAssign &VA = RVLocs[I];
2540     assert(VA.isRegLoc() && "Can only return in registers!");
2541     // TODO: Partially return in registers if return values don't fit.
2542     SDValue Arg = OutVals[RealRVLocIdx];
2543 
2544     // Copied from other backends.
2545     switch (VA.getLocInfo()) {
2546     case CCValAssign::Full:
2547       break;
2548     case CCValAssign::BCvt:
2549       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2550       break;
2551     case CCValAssign::SExt:
2552       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2553       break;
2554     case CCValAssign::ZExt:
2555       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2556       break;
2557     case CCValAssign::AExt:
2558       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2559       break;
2560     default:
2561       llvm_unreachable("Unknown loc info!");
2562     }
2563 
2564     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2565     Flag = Chain.getValue(1);
2566     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2567   }
2568 
2569   // FIXME: Does sret work properly?
2570   if (!Info->isEntryFunction()) {
2571     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2572     const MCPhysReg *I =
2573       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2574     if (I) {
2575       for (; *I; ++I) {
2576         if (AMDGPU::SReg_64RegClass.contains(*I))
2577           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2578         else if (AMDGPU::SReg_32RegClass.contains(*I))
2579           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2580         else
2581           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2582       }
2583     }
2584   }
2585 
2586   // Update chain and glue.
2587   RetOps[0] = Chain;
2588   if (Flag.getNode())
2589     RetOps.push_back(Flag);
2590 
2591   unsigned Opc = AMDGPUISD::ENDPGM;
2592   if (!IsWaveEnd)
2593     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2594   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2595 }
2596 
2597 SDValue SITargetLowering::LowerCallResult(
2598     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2599     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2600     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2601     SDValue ThisVal) const {
2602   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2603 
2604   // Assign locations to each value returned by this call.
2605   SmallVector<CCValAssign, 16> RVLocs;
2606   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2607                  *DAG.getContext());
2608   CCInfo.AnalyzeCallResult(Ins, RetCC);
2609 
2610   // Copy all of the result registers out of their specified physreg.
2611   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2612     CCValAssign VA = RVLocs[i];
2613     SDValue Val;
2614 
2615     if (VA.isRegLoc()) {
2616       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2617       Chain = Val.getValue(1);
2618       InFlag = Val.getValue(2);
2619     } else if (VA.isMemLoc()) {
2620       report_fatal_error("TODO: return values in memory");
2621     } else
2622       llvm_unreachable("unknown argument location type");
2623 
2624     switch (VA.getLocInfo()) {
2625     case CCValAssign::Full:
2626       break;
2627     case CCValAssign::BCvt:
2628       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2629       break;
2630     case CCValAssign::ZExt:
2631       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2632                         DAG.getValueType(VA.getValVT()));
2633       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2634       break;
2635     case CCValAssign::SExt:
2636       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2637                         DAG.getValueType(VA.getValVT()));
2638       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2639       break;
2640     case CCValAssign::AExt:
2641       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2642       break;
2643     default:
2644       llvm_unreachable("Unknown loc info!");
2645     }
2646 
2647     InVals.push_back(Val);
2648   }
2649 
2650   return Chain;
2651 }
2652 
2653 // Add code to pass special inputs required depending on used features separate
2654 // from the explicit user arguments present in the IR.
2655 void SITargetLowering::passSpecialInputs(
2656     CallLoweringInfo &CLI,
2657     CCState &CCInfo,
2658     const SIMachineFunctionInfo &Info,
2659     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2660     SmallVectorImpl<SDValue> &MemOpChains,
2661     SDValue Chain) const {
2662   // If we don't have a call site, this was a call inserted by
2663   // legalization. These can never use special inputs.
2664   if (!CLI.CB)
2665     return;
2666 
2667   SelectionDAG &DAG = CLI.DAG;
2668   const SDLoc &DL = CLI.DL;
2669 
2670   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2671   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2672 
2673   const AMDGPUFunctionArgInfo *CalleeArgInfo
2674     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2675   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2676     auto &ArgUsageInfo =
2677       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2678     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2679   }
2680 
2681   // TODO: Unify with private memory register handling. This is complicated by
2682   // the fact that at least in kernels, the input argument is not necessarily
2683   // in the same location as the input.
2684   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2685     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2686     AMDGPUFunctionArgInfo::QUEUE_PTR,
2687     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2688     AMDGPUFunctionArgInfo::DISPATCH_ID,
2689     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2690     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2691     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2692   };
2693 
2694   for (auto InputID : InputRegs) {
2695     const ArgDescriptor *OutgoingArg;
2696     const TargetRegisterClass *ArgRC;
2697     LLT ArgTy;
2698 
2699     std::tie(OutgoingArg, ArgRC, ArgTy) =
2700         CalleeArgInfo->getPreloadedValue(InputID);
2701     if (!OutgoingArg)
2702       continue;
2703 
2704     const ArgDescriptor *IncomingArg;
2705     const TargetRegisterClass *IncomingArgRC;
2706     LLT Ty;
2707     std::tie(IncomingArg, IncomingArgRC, Ty) =
2708         CallerArgInfo.getPreloadedValue(InputID);
2709     assert(IncomingArgRC == ArgRC);
2710 
2711     // All special arguments are ints for now.
2712     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2713     SDValue InputReg;
2714 
2715     if (IncomingArg) {
2716       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2717     } else {
2718       // The implicit arg ptr is special because it doesn't have a corresponding
2719       // input for kernels, and is computed from the kernarg segment pointer.
2720       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2721       InputReg = getImplicitArgPtr(DAG, DL);
2722     }
2723 
2724     if (OutgoingArg->isRegister()) {
2725       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2726       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2727         report_fatal_error("failed to allocate implicit input argument");
2728     } else {
2729       unsigned SpecialArgOffset =
2730           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2731       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2732                                               SpecialArgOffset);
2733       MemOpChains.push_back(ArgStore);
2734     }
2735   }
2736 
2737   // Pack workitem IDs into a single register or pass it as is if already
2738   // packed.
2739   const ArgDescriptor *OutgoingArg;
2740   const TargetRegisterClass *ArgRC;
2741   LLT Ty;
2742 
2743   std::tie(OutgoingArg, ArgRC, Ty) =
2744       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2745   if (!OutgoingArg)
2746     std::tie(OutgoingArg, ArgRC, Ty) =
2747         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2748   if (!OutgoingArg)
2749     std::tie(OutgoingArg, ArgRC, Ty) =
2750         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2751   if (!OutgoingArg)
2752     return;
2753 
2754   const ArgDescriptor *IncomingArgX = std::get<0>(
2755       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2756   const ArgDescriptor *IncomingArgY = std::get<0>(
2757       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2758   const ArgDescriptor *IncomingArgZ = std::get<0>(
2759       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2760 
2761   SDValue InputReg;
2762   SDLoc SL;
2763 
2764   // If incoming ids are not packed we need to pack them.
2765   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2766     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2767 
2768   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2769     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2770     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2771                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2772     InputReg = InputReg.getNode() ?
2773                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2774   }
2775 
2776   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2777     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2778     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2779                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2780     InputReg = InputReg.getNode() ?
2781                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2782   }
2783 
2784   if (!InputReg.getNode()) {
2785     // Workitem ids are already packed, any of present incoming arguments
2786     // will carry all required fields.
2787     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2788       IncomingArgX ? *IncomingArgX :
2789       IncomingArgY ? *IncomingArgY :
2790                      *IncomingArgZ, ~0u);
2791     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2792   }
2793 
2794   if (OutgoingArg->isRegister()) {
2795     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2796     CCInfo.AllocateReg(OutgoingArg->getRegister());
2797   } else {
2798     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2799     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2800                                             SpecialArgOffset);
2801     MemOpChains.push_back(ArgStore);
2802   }
2803 }
2804 
2805 static bool canGuaranteeTCO(CallingConv::ID CC) {
2806   return CC == CallingConv::Fast;
2807 }
2808 
2809 /// Return true if we might ever do TCO for calls with this calling convention.
2810 static bool mayTailCallThisCC(CallingConv::ID CC) {
2811   switch (CC) {
2812   case CallingConv::C:
2813     return true;
2814   default:
2815     return canGuaranteeTCO(CC);
2816   }
2817 }
2818 
2819 bool SITargetLowering::isEligibleForTailCallOptimization(
2820     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2821     const SmallVectorImpl<ISD::OutputArg> &Outs,
2822     const SmallVectorImpl<SDValue> &OutVals,
2823     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2824   if (!mayTailCallThisCC(CalleeCC))
2825     return false;
2826 
2827   MachineFunction &MF = DAG.getMachineFunction();
2828   const Function &CallerF = MF.getFunction();
2829   CallingConv::ID CallerCC = CallerF.getCallingConv();
2830   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2831   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2832 
2833   // Kernels aren't callable, and don't have a live in return address so it
2834   // doesn't make sense to do a tail call with entry functions.
2835   if (!CallerPreserved)
2836     return false;
2837 
2838   bool CCMatch = CallerCC == CalleeCC;
2839 
2840   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2841     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2842       return true;
2843     return false;
2844   }
2845 
2846   // TODO: Can we handle var args?
2847   if (IsVarArg)
2848     return false;
2849 
2850   for (const Argument &Arg : CallerF.args()) {
2851     if (Arg.hasByValAttr())
2852       return false;
2853   }
2854 
2855   LLVMContext &Ctx = *DAG.getContext();
2856 
2857   // Check that the call results are passed in the same way.
2858   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2859                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2860                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2861     return false;
2862 
2863   // The callee has to preserve all registers the caller needs to preserve.
2864   if (!CCMatch) {
2865     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2866     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2867       return false;
2868   }
2869 
2870   // Nothing more to check if the callee is taking no arguments.
2871   if (Outs.empty())
2872     return true;
2873 
2874   SmallVector<CCValAssign, 16> ArgLocs;
2875   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2876 
2877   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2878 
2879   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2880   // If the stack arguments for this call do not fit into our own save area then
2881   // the call cannot be made tail.
2882   // TODO: Is this really necessary?
2883   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2884     return false;
2885 
2886   const MachineRegisterInfo &MRI = MF.getRegInfo();
2887   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2888 }
2889 
2890 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2891   if (!CI->isTailCall())
2892     return false;
2893 
2894   const Function *ParentFn = CI->getParent()->getParent();
2895   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2896     return false;
2897   return true;
2898 }
2899 
2900 // The wave scratch offset register is used as the global base pointer.
2901 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2902                                     SmallVectorImpl<SDValue> &InVals) const {
2903   SelectionDAG &DAG = CLI.DAG;
2904   const SDLoc &DL = CLI.DL;
2905   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2906   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2907   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2908   SDValue Chain = CLI.Chain;
2909   SDValue Callee = CLI.Callee;
2910   bool &IsTailCall = CLI.IsTailCall;
2911   CallingConv::ID CallConv = CLI.CallConv;
2912   bool IsVarArg = CLI.IsVarArg;
2913   bool IsSibCall = false;
2914   bool IsThisReturn = false;
2915   MachineFunction &MF = DAG.getMachineFunction();
2916 
2917   if (Callee.isUndef() || isNullConstant(Callee)) {
2918     if (!CLI.IsTailCall) {
2919       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2920         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2921     }
2922 
2923     return Chain;
2924   }
2925 
2926   if (IsVarArg) {
2927     return lowerUnhandledCall(CLI, InVals,
2928                               "unsupported call to variadic function ");
2929   }
2930 
2931   if (!CLI.CB)
2932     report_fatal_error("unsupported libcall legalization");
2933 
2934   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2935       !CLI.CB->getCalledFunction()) {
2936     return lowerUnhandledCall(CLI, InVals,
2937                               "unsupported indirect call to function ");
2938   }
2939 
2940   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2941     return lowerUnhandledCall(CLI, InVals,
2942                               "unsupported required tail call to function ");
2943   }
2944 
2945   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2946     // Note the issue is with the CC of the calling function, not of the call
2947     // itself.
2948     return lowerUnhandledCall(CLI, InVals,
2949                           "unsupported call from graphics shader of function ");
2950   }
2951 
2952   if (IsTailCall) {
2953     IsTailCall = isEligibleForTailCallOptimization(
2954       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2955     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2956       report_fatal_error("failed to perform tail call elimination on a call "
2957                          "site marked musttail");
2958     }
2959 
2960     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2961 
2962     // A sibling call is one where we're under the usual C ABI and not planning
2963     // to change that but can still do a tail call:
2964     if (!TailCallOpt && IsTailCall)
2965       IsSibCall = true;
2966 
2967     if (IsTailCall)
2968       ++NumTailCalls;
2969   }
2970 
2971   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2972   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2973   SmallVector<SDValue, 8> MemOpChains;
2974 
2975   // Analyze operands of the call, assigning locations to each operand.
2976   SmallVector<CCValAssign, 16> ArgLocs;
2977   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2978   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2979 
2980   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2981     // With a fixed ABI, allocate fixed registers before user arguments.
2982     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2983   }
2984 
2985   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2986 
2987   // Get a count of how many bytes are to be pushed on the stack.
2988   unsigned NumBytes = CCInfo.getNextStackOffset();
2989 
2990   if (IsSibCall) {
2991     // Since we're not changing the ABI to make this a tail call, the memory
2992     // operands are already available in the caller's incoming argument space.
2993     NumBytes = 0;
2994   }
2995 
2996   // FPDiff is the byte offset of the call's argument area from the callee's.
2997   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2998   // by this amount for a tail call. In a sibling call it must be 0 because the
2999   // caller will deallocate the entire stack and the callee still expects its
3000   // arguments to begin at SP+0. Completely unused for non-tail calls.
3001   int32_t FPDiff = 0;
3002   MachineFrameInfo &MFI = MF.getFrameInfo();
3003 
3004   // Adjust the stack pointer for the new arguments...
3005   // These operations are automatically eliminated by the prolog/epilog pass
3006   if (!IsSibCall) {
3007     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3008 
3009     SmallVector<SDValue, 4> CopyFromChains;
3010 
3011     // In the HSA case, this should be an identity copy.
3012     SDValue ScratchRSrcReg
3013       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3014     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3015     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3016     Chain = DAG.getTokenFactor(DL, CopyFromChains);
3017   }
3018 
3019   MVT PtrVT = MVT::i32;
3020 
3021   // Walk the register/memloc assignments, inserting copies/loads.
3022   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3023     CCValAssign &VA = ArgLocs[i];
3024     SDValue Arg = OutVals[i];
3025 
3026     // Promote the value if needed.
3027     switch (VA.getLocInfo()) {
3028     case CCValAssign::Full:
3029       break;
3030     case CCValAssign::BCvt:
3031       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3032       break;
3033     case CCValAssign::ZExt:
3034       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3035       break;
3036     case CCValAssign::SExt:
3037       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3038       break;
3039     case CCValAssign::AExt:
3040       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3041       break;
3042     case CCValAssign::FPExt:
3043       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3044       break;
3045     default:
3046       llvm_unreachable("Unknown loc info!");
3047     }
3048 
3049     if (VA.isRegLoc()) {
3050       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3051     } else {
3052       assert(VA.isMemLoc());
3053 
3054       SDValue DstAddr;
3055       MachinePointerInfo DstInfo;
3056 
3057       unsigned LocMemOffset = VA.getLocMemOffset();
3058       int32_t Offset = LocMemOffset;
3059 
3060       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3061       MaybeAlign Alignment;
3062 
3063       if (IsTailCall) {
3064         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3065         unsigned OpSize = Flags.isByVal() ?
3066           Flags.getByValSize() : VA.getValVT().getStoreSize();
3067 
3068         // FIXME: We can have better than the minimum byval required alignment.
3069         Alignment =
3070             Flags.isByVal()
3071                 ? Flags.getNonZeroByValAlign()
3072                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3073 
3074         Offset = Offset + FPDiff;
3075         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3076 
3077         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3078         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3079 
3080         // Make sure any stack arguments overlapping with where we're storing
3081         // are loaded before this eventual operation. Otherwise they'll be
3082         // clobbered.
3083 
3084         // FIXME: Why is this really necessary? This seems to just result in a
3085         // lot of code to copy the stack and write them back to the same
3086         // locations, which are supposed to be immutable?
3087         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3088       } else {
3089         DstAddr = PtrOff;
3090         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3091         Alignment =
3092             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3093       }
3094 
3095       if (Outs[i].Flags.isByVal()) {
3096         SDValue SizeNode =
3097             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3098         SDValue Cpy =
3099             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3100                           Outs[i].Flags.getNonZeroByValAlign(),
3101                           /*isVol = */ false, /*AlwaysInline = */ true,
3102                           /*isTailCall = */ false, DstInfo,
3103                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3104 
3105         MemOpChains.push_back(Cpy);
3106       } else {
3107         SDValue Store =
3108             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3109         MemOpChains.push_back(Store);
3110       }
3111     }
3112   }
3113 
3114   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
3115     // Copy special input registers after user input arguments.
3116     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3117   }
3118 
3119   if (!MemOpChains.empty())
3120     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3121 
3122   // Build a sequence of copy-to-reg nodes chained together with token chain
3123   // and flag operands which copy the outgoing args into the appropriate regs.
3124   SDValue InFlag;
3125   for (auto &RegToPass : RegsToPass) {
3126     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3127                              RegToPass.second, InFlag);
3128     InFlag = Chain.getValue(1);
3129   }
3130 
3131 
3132   SDValue PhysReturnAddrReg;
3133   if (IsTailCall) {
3134     // Since the return is being combined with the call, we need to pass on the
3135     // return address.
3136 
3137     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3138     SDValue ReturnAddrReg = CreateLiveInRegister(
3139       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3140 
3141     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3142                                         MVT::i64);
3143     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3144     InFlag = Chain.getValue(1);
3145   }
3146 
3147   // We don't usually want to end the call-sequence here because we would tidy
3148   // the frame up *after* the call, however in the ABI-changing tail-call case
3149   // we've carefully laid out the parameters so that when sp is reset they'll be
3150   // in the correct location.
3151   if (IsTailCall && !IsSibCall) {
3152     Chain = DAG.getCALLSEQ_END(Chain,
3153                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3154                                DAG.getTargetConstant(0, DL, MVT::i32),
3155                                InFlag, DL);
3156     InFlag = Chain.getValue(1);
3157   }
3158 
3159   std::vector<SDValue> Ops;
3160   Ops.push_back(Chain);
3161   Ops.push_back(Callee);
3162   // Add a redundant copy of the callee global which will not be legalized, as
3163   // we need direct access to the callee later.
3164   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3165     const GlobalValue *GV = GSD->getGlobal();
3166     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3167   } else {
3168     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3169   }
3170 
3171   if (IsTailCall) {
3172     // Each tail call may have to adjust the stack by a different amount, so
3173     // this information must travel along with the operation for eventual
3174     // consumption by emitEpilogue.
3175     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3176 
3177     Ops.push_back(PhysReturnAddrReg);
3178   }
3179 
3180   // Add argument registers to the end of the list so that they are known live
3181   // into the call.
3182   for (auto &RegToPass : RegsToPass) {
3183     Ops.push_back(DAG.getRegister(RegToPass.first,
3184                                   RegToPass.second.getValueType()));
3185   }
3186 
3187   // Add a register mask operand representing the call-preserved registers.
3188 
3189   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3190   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3191   assert(Mask && "Missing call preserved mask for calling convention");
3192   Ops.push_back(DAG.getRegisterMask(Mask));
3193 
3194   if (InFlag.getNode())
3195     Ops.push_back(InFlag);
3196 
3197   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3198 
3199   // If we're doing a tall call, use a TC_RETURN here rather than an
3200   // actual call instruction.
3201   if (IsTailCall) {
3202     MFI.setHasTailCall();
3203     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3204   }
3205 
3206   // Returns a chain and a flag for retval copy to use.
3207   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3208   Chain = Call.getValue(0);
3209   InFlag = Call.getValue(1);
3210 
3211   uint64_t CalleePopBytes = NumBytes;
3212   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3213                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3214                              InFlag, DL);
3215   if (!Ins.empty())
3216     InFlag = Chain.getValue(1);
3217 
3218   // Handle result values, copying them out of physregs into vregs that we
3219   // return.
3220   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3221                          InVals, IsThisReturn,
3222                          IsThisReturn ? OutVals[0] : SDValue());
3223 }
3224 
3225 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3226 // except for applying the wave size scale to the increment amount.
3227 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3228     SDValue Op, SelectionDAG &DAG) const {
3229   const MachineFunction &MF = DAG.getMachineFunction();
3230   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3231 
3232   SDLoc dl(Op);
3233   EVT VT = Op.getValueType();
3234   SDValue Tmp1 = Op;
3235   SDValue Tmp2 = Op.getValue(1);
3236   SDValue Tmp3 = Op.getOperand(2);
3237   SDValue Chain = Tmp1.getOperand(0);
3238 
3239   Register SPReg = Info->getStackPtrOffsetReg();
3240 
3241   // Chain the dynamic stack allocation so that it doesn't modify the stack
3242   // pointer when other instructions are using the stack.
3243   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3244 
3245   SDValue Size  = Tmp2.getOperand(1);
3246   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3247   Chain = SP.getValue(1);
3248   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3249   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3250   const TargetFrameLowering *TFL = ST.getFrameLowering();
3251   unsigned Opc =
3252     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3253     ISD::ADD : ISD::SUB;
3254 
3255   SDValue ScaledSize = DAG.getNode(
3256       ISD::SHL, dl, VT, Size,
3257       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3258 
3259   Align StackAlign = TFL->getStackAlign();
3260   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3261   if (Alignment && *Alignment > StackAlign) {
3262     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3263                        DAG.getConstant(-(uint64_t)Alignment->value()
3264                                            << ST.getWavefrontSizeLog2(),
3265                                        dl, VT));
3266   }
3267 
3268   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3269   Tmp2 = DAG.getCALLSEQ_END(
3270       Chain, DAG.getIntPtrConstant(0, dl, true),
3271       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3272 
3273   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3274 }
3275 
3276 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3277                                                   SelectionDAG &DAG) const {
3278   // We only handle constant sizes here to allow non-entry block, static sized
3279   // allocas. A truly dynamic value is more difficult to support because we
3280   // don't know if the size value is uniform or not. If the size isn't uniform,
3281   // we would need to do a wave reduction to get the maximum size to know how
3282   // much to increment the uniform stack pointer.
3283   SDValue Size = Op.getOperand(1);
3284   if (isa<ConstantSDNode>(Size))
3285       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3286 
3287   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3288 }
3289 
3290 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3291                                              const MachineFunction &MF) const {
3292   Register Reg = StringSwitch<Register>(RegName)
3293     .Case("m0", AMDGPU::M0)
3294     .Case("exec", AMDGPU::EXEC)
3295     .Case("exec_lo", AMDGPU::EXEC_LO)
3296     .Case("exec_hi", AMDGPU::EXEC_HI)
3297     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3298     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3299     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3300     .Default(Register());
3301 
3302   if (Reg == AMDGPU::NoRegister) {
3303     report_fatal_error(Twine("invalid register name \""
3304                              + StringRef(RegName)  + "\"."));
3305 
3306   }
3307 
3308   if (!Subtarget->hasFlatScrRegister() &&
3309        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3310     report_fatal_error(Twine("invalid register \""
3311                              + StringRef(RegName)  + "\" for subtarget."));
3312   }
3313 
3314   switch (Reg) {
3315   case AMDGPU::M0:
3316   case AMDGPU::EXEC_LO:
3317   case AMDGPU::EXEC_HI:
3318   case AMDGPU::FLAT_SCR_LO:
3319   case AMDGPU::FLAT_SCR_HI:
3320     if (VT.getSizeInBits() == 32)
3321       return Reg;
3322     break;
3323   case AMDGPU::EXEC:
3324   case AMDGPU::FLAT_SCR:
3325     if (VT.getSizeInBits() == 64)
3326       return Reg;
3327     break;
3328   default:
3329     llvm_unreachable("missing register type checking");
3330   }
3331 
3332   report_fatal_error(Twine("invalid type for register \""
3333                            + StringRef(RegName) + "\"."));
3334 }
3335 
3336 // If kill is not the last instruction, split the block so kill is always a
3337 // proper terminator.
3338 MachineBasicBlock *
3339 SITargetLowering::splitKillBlock(MachineInstr &MI,
3340                                  MachineBasicBlock *BB) const {
3341   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3342   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3343   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3344   return SplitBB;
3345 }
3346 
3347 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3348 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3349 // be the first instruction in the remainder block.
3350 //
3351 /// \returns { LoopBody, Remainder }
3352 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3353 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3354   MachineFunction *MF = MBB.getParent();
3355   MachineBasicBlock::iterator I(&MI);
3356 
3357   // To insert the loop we need to split the block. Move everything after this
3358   // point to a new block, and insert a new empty block between the two.
3359   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3360   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3361   MachineFunction::iterator MBBI(MBB);
3362   ++MBBI;
3363 
3364   MF->insert(MBBI, LoopBB);
3365   MF->insert(MBBI, RemainderBB);
3366 
3367   LoopBB->addSuccessor(LoopBB);
3368   LoopBB->addSuccessor(RemainderBB);
3369 
3370   // Move the rest of the block into a new block.
3371   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3372 
3373   if (InstInLoop) {
3374     auto Next = std::next(I);
3375 
3376     // Move instruction to loop body.
3377     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3378 
3379     // Move the rest of the block.
3380     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3381   } else {
3382     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3383   }
3384 
3385   MBB.addSuccessor(LoopBB);
3386 
3387   return std::make_pair(LoopBB, RemainderBB);
3388 }
3389 
3390 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3391 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3392   MachineBasicBlock *MBB = MI.getParent();
3393   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3394   auto I = MI.getIterator();
3395   auto E = std::next(I);
3396 
3397   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3398     .addImm(0);
3399 
3400   MIBundleBuilder Bundler(*MBB, I, E);
3401   finalizeBundle(*MBB, Bundler.begin());
3402 }
3403 
3404 MachineBasicBlock *
3405 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3406                                          MachineBasicBlock *BB) const {
3407   const DebugLoc &DL = MI.getDebugLoc();
3408 
3409   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3410 
3411   MachineBasicBlock *LoopBB;
3412   MachineBasicBlock *RemainderBB;
3413   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3414 
3415   // Apparently kill flags are only valid if the def is in the same block?
3416   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3417     Src->setIsKill(false);
3418 
3419   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3420 
3421   MachineBasicBlock::iterator I = LoopBB->end();
3422 
3423   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3424     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3425 
3426   // Clear TRAP_STS.MEM_VIOL
3427   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3428     .addImm(0)
3429     .addImm(EncodedReg);
3430 
3431   bundleInstWithWaitcnt(MI);
3432 
3433   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3434 
3435   // Load and check TRAP_STS.MEM_VIOL
3436   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3437     .addImm(EncodedReg);
3438 
3439   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3440   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3441     .addReg(Reg, RegState::Kill)
3442     .addImm(0);
3443   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3444     .addMBB(LoopBB);
3445 
3446   return RemainderBB;
3447 }
3448 
3449 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3450 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3451 // will only do one iteration. In the worst case, this will loop 64 times.
3452 //
3453 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3454 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3455   const SIInstrInfo *TII,
3456   MachineRegisterInfo &MRI,
3457   MachineBasicBlock &OrigBB,
3458   MachineBasicBlock &LoopBB,
3459   const DebugLoc &DL,
3460   const MachineOperand &IdxReg,
3461   unsigned InitReg,
3462   unsigned ResultReg,
3463   unsigned PhiReg,
3464   unsigned InitSaveExecReg,
3465   int Offset,
3466   bool UseGPRIdxMode,
3467   bool IsIndirectSrc) {
3468   MachineFunction *MF = OrigBB.getParent();
3469   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3470   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3471   MachineBasicBlock::iterator I = LoopBB.begin();
3472 
3473   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3474   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3475   Register NewExec = MRI.createVirtualRegister(BoolRC);
3476   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3477   Register CondReg = MRI.createVirtualRegister(BoolRC);
3478 
3479   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3480     .addReg(InitReg)
3481     .addMBB(&OrigBB)
3482     .addReg(ResultReg)
3483     .addMBB(&LoopBB);
3484 
3485   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3486     .addReg(InitSaveExecReg)
3487     .addMBB(&OrigBB)
3488     .addReg(NewExec)
3489     .addMBB(&LoopBB);
3490 
3491   // Read the next variant <- also loop target.
3492   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3493     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3494 
3495   // Compare the just read M0 value to all possible Idx values.
3496   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3497     .addReg(CurrentIdxReg)
3498     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3499 
3500   // Update EXEC, save the original EXEC value to VCC.
3501   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3502                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3503           NewExec)
3504     .addReg(CondReg, RegState::Kill);
3505 
3506   MRI.setSimpleHint(NewExec, CondReg);
3507 
3508   if (UseGPRIdxMode) {
3509     unsigned IdxReg;
3510     if (Offset == 0) {
3511       IdxReg = CurrentIdxReg;
3512     } else {
3513       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3514       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3515         .addReg(CurrentIdxReg, RegState::Kill)
3516         .addImm(Offset);
3517     }
3518     unsigned IdxMode = IsIndirectSrc ?
3519       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3520     MachineInstr *SetOn =
3521       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3522       .addReg(IdxReg, RegState::Kill)
3523       .addImm(IdxMode);
3524     SetOn->getOperand(3).setIsUndef();
3525   } else {
3526     // Move index from VCC into M0
3527     if (Offset == 0) {
3528       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3529         .addReg(CurrentIdxReg, RegState::Kill);
3530     } else {
3531       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3532         .addReg(CurrentIdxReg, RegState::Kill)
3533         .addImm(Offset);
3534     }
3535   }
3536 
3537   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3538   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3539   MachineInstr *InsertPt =
3540     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3541                                                   : AMDGPU::S_XOR_B64_term), Exec)
3542       .addReg(Exec)
3543       .addReg(NewExec);
3544 
3545   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3546   // s_cbranch_scc0?
3547 
3548   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3549   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3550     .addMBB(&LoopBB);
3551 
3552   return InsertPt->getIterator();
3553 }
3554 
3555 // This has slightly sub-optimal regalloc when the source vector is killed by
3556 // the read. The register allocator does not understand that the kill is
3557 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3558 // subregister from it, using 1 more VGPR than necessary. This was saved when
3559 // this was expanded after register allocation.
3560 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3561                                                   MachineBasicBlock &MBB,
3562                                                   MachineInstr &MI,
3563                                                   unsigned InitResultReg,
3564                                                   unsigned PhiReg,
3565                                                   int Offset,
3566                                                   bool UseGPRIdxMode,
3567                                                   bool IsIndirectSrc) {
3568   MachineFunction *MF = MBB.getParent();
3569   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3570   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3571   MachineRegisterInfo &MRI = MF->getRegInfo();
3572   const DebugLoc &DL = MI.getDebugLoc();
3573   MachineBasicBlock::iterator I(&MI);
3574 
3575   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3576   Register DstReg = MI.getOperand(0).getReg();
3577   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3578   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3579   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3580   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3581 
3582   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3583 
3584   // Save the EXEC mask
3585   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3586     .addReg(Exec);
3587 
3588   MachineBasicBlock *LoopBB;
3589   MachineBasicBlock *RemainderBB;
3590   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3591 
3592   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3593 
3594   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3595                                       InitResultReg, DstReg, PhiReg, TmpExec,
3596                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3597   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3598   MachineFunction::iterator MBBI(LoopBB);
3599   ++MBBI;
3600   MF->insert(MBBI, LandingPad);
3601   LoopBB->removeSuccessor(RemainderBB);
3602   LandingPad->addSuccessor(RemainderBB);
3603   LoopBB->addSuccessor(LandingPad);
3604   MachineBasicBlock::iterator First = LandingPad->begin();
3605   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3606     .addReg(SaveExec);
3607 
3608   return InsPt;
3609 }
3610 
3611 // Returns subreg index, offset
3612 static std::pair<unsigned, int>
3613 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3614                             const TargetRegisterClass *SuperRC,
3615                             unsigned VecReg,
3616                             int Offset) {
3617   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3618 
3619   // Skip out of bounds offsets, or else we would end up using an undefined
3620   // register.
3621   if (Offset >= NumElts || Offset < 0)
3622     return std::make_pair(AMDGPU::sub0, Offset);
3623 
3624   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3625 }
3626 
3627 // Return true if the index is an SGPR and was set.
3628 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3629                                  MachineRegisterInfo &MRI,
3630                                  MachineInstr &MI,
3631                                  int Offset,
3632                                  bool UseGPRIdxMode,
3633                                  bool IsIndirectSrc) {
3634   MachineBasicBlock *MBB = MI.getParent();
3635   const DebugLoc &DL = MI.getDebugLoc();
3636   MachineBasicBlock::iterator I(&MI);
3637 
3638   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3639   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3640 
3641   assert(Idx->getReg() != AMDGPU::NoRegister);
3642 
3643   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3644     return false;
3645 
3646   if (UseGPRIdxMode) {
3647     unsigned IdxMode = IsIndirectSrc ?
3648       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3649     if (Offset == 0) {
3650       MachineInstr *SetOn =
3651           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3652               .add(*Idx)
3653               .addImm(IdxMode);
3654 
3655       SetOn->getOperand(3).setIsUndef();
3656     } else {
3657       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3658       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3659           .add(*Idx)
3660           .addImm(Offset);
3661       MachineInstr *SetOn =
3662         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3663         .addReg(Tmp, RegState::Kill)
3664         .addImm(IdxMode);
3665 
3666       SetOn->getOperand(3).setIsUndef();
3667     }
3668 
3669     return true;
3670   }
3671 
3672   if (Offset == 0) {
3673     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3674       .add(*Idx);
3675   } else {
3676     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3677       .add(*Idx)
3678       .addImm(Offset);
3679   }
3680 
3681   return true;
3682 }
3683 
3684 // Control flow needs to be inserted if indexing with a VGPR.
3685 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3686                                           MachineBasicBlock &MBB,
3687                                           const GCNSubtarget &ST) {
3688   const SIInstrInfo *TII = ST.getInstrInfo();
3689   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3690   MachineFunction *MF = MBB.getParent();
3691   MachineRegisterInfo &MRI = MF->getRegInfo();
3692 
3693   Register Dst = MI.getOperand(0).getReg();
3694   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3695   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3696 
3697   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3698 
3699   unsigned SubReg;
3700   std::tie(SubReg, Offset)
3701     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3702 
3703   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3704 
3705   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3706     MachineBasicBlock::iterator I(&MI);
3707     const DebugLoc &DL = MI.getDebugLoc();
3708 
3709     if (UseGPRIdxMode) {
3710       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3711       // to avoid interfering with other uses, so probably requires a new
3712       // optimization pass.
3713       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3714         .addReg(SrcReg, 0, SubReg)
3715         .addReg(SrcReg, RegState::Implicit)
3716         .addReg(AMDGPU::M0, RegState::Implicit);
3717       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3718     } else {
3719       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3720         .addReg(SrcReg, 0, SubReg)
3721         .addReg(SrcReg, RegState::Implicit);
3722     }
3723 
3724     MI.eraseFromParent();
3725 
3726     return &MBB;
3727   }
3728 
3729   const DebugLoc &DL = MI.getDebugLoc();
3730   MachineBasicBlock::iterator I(&MI);
3731 
3732   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3733   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3734 
3735   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3736 
3737   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3738                               Offset, UseGPRIdxMode, true);
3739   MachineBasicBlock *LoopBB = InsPt->getParent();
3740 
3741   if (UseGPRIdxMode) {
3742     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3743       .addReg(SrcReg, 0, SubReg)
3744       .addReg(SrcReg, RegState::Implicit)
3745       .addReg(AMDGPU::M0, RegState::Implicit);
3746     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3747   } else {
3748     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3749       .addReg(SrcReg, 0, SubReg)
3750       .addReg(SrcReg, RegState::Implicit);
3751   }
3752 
3753   MI.eraseFromParent();
3754 
3755   return LoopBB;
3756 }
3757 
3758 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3759                                           MachineBasicBlock &MBB,
3760                                           const GCNSubtarget &ST) {
3761   const SIInstrInfo *TII = ST.getInstrInfo();
3762   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3763   MachineFunction *MF = MBB.getParent();
3764   MachineRegisterInfo &MRI = MF->getRegInfo();
3765 
3766   Register Dst = MI.getOperand(0).getReg();
3767   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3768   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3769   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3770   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3771   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3772 
3773   // This can be an immediate, but will be folded later.
3774   assert(Val->getReg());
3775 
3776   unsigned SubReg;
3777   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3778                                                          SrcVec->getReg(),
3779                                                          Offset);
3780   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3781 
3782   if (Idx->getReg() == AMDGPU::NoRegister) {
3783     MachineBasicBlock::iterator I(&MI);
3784     const DebugLoc &DL = MI.getDebugLoc();
3785 
3786     assert(Offset == 0);
3787 
3788     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3789         .add(*SrcVec)
3790         .add(*Val)
3791         .addImm(SubReg);
3792 
3793     MI.eraseFromParent();
3794     return &MBB;
3795   }
3796 
3797   const MCInstrDesc &MovRelDesc
3798     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3799 
3800   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3801     MachineBasicBlock::iterator I(&MI);
3802     const DebugLoc &DL = MI.getDebugLoc();
3803     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3804       .addReg(SrcVec->getReg())
3805       .add(*Val)
3806       .addImm(SubReg);
3807     if (UseGPRIdxMode)
3808       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3809 
3810     MI.eraseFromParent();
3811     return &MBB;
3812   }
3813 
3814   if (Val->isReg())
3815     MRI.clearKillFlags(Val->getReg());
3816 
3817   const DebugLoc &DL = MI.getDebugLoc();
3818 
3819   Register PhiReg = MRI.createVirtualRegister(VecRC);
3820 
3821   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3822                               Offset, UseGPRIdxMode, false);
3823   MachineBasicBlock *LoopBB = InsPt->getParent();
3824 
3825   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3826     .addReg(PhiReg)
3827     .add(*Val)
3828     .addImm(AMDGPU::sub0);
3829   if (UseGPRIdxMode)
3830     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3831 
3832   MI.eraseFromParent();
3833   return LoopBB;
3834 }
3835 
3836 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3837   MachineInstr &MI, MachineBasicBlock *BB) const {
3838 
3839   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3840   MachineFunction *MF = BB->getParent();
3841   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3842 
3843   switch (MI.getOpcode()) {
3844   case AMDGPU::S_UADDO_PSEUDO:
3845   case AMDGPU::S_USUBO_PSEUDO: {
3846     const DebugLoc &DL = MI.getDebugLoc();
3847     MachineOperand &Dest0 = MI.getOperand(0);
3848     MachineOperand &Dest1 = MI.getOperand(1);
3849     MachineOperand &Src0 = MI.getOperand(2);
3850     MachineOperand &Src1 = MI.getOperand(3);
3851 
3852     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3853                        ? AMDGPU::S_ADD_I32
3854                        : AMDGPU::S_SUB_I32;
3855     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3856 
3857     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3858         .addImm(1)
3859         .addImm(0);
3860 
3861     MI.eraseFromParent();
3862     return BB;
3863   }
3864   case AMDGPU::S_ADD_U64_PSEUDO:
3865   case AMDGPU::S_SUB_U64_PSEUDO: {
3866     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3867     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3868     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3869     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3870     const DebugLoc &DL = MI.getDebugLoc();
3871 
3872     MachineOperand &Dest = MI.getOperand(0);
3873     MachineOperand &Src0 = MI.getOperand(1);
3874     MachineOperand &Src1 = MI.getOperand(2);
3875 
3876     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3877     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3878 
3879     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3880         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3881     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3882         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3883 
3884     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3885         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3886     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3887         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3888 
3889     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3890 
3891     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3892     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3893     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3894     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3895     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3896         .addReg(DestSub0)
3897         .addImm(AMDGPU::sub0)
3898         .addReg(DestSub1)
3899         .addImm(AMDGPU::sub1);
3900     MI.eraseFromParent();
3901     return BB;
3902   }
3903   case AMDGPU::V_ADD_U64_PSEUDO:
3904   case AMDGPU::V_SUB_U64_PSEUDO: {
3905     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3906     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3907     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3908     const DebugLoc &DL = MI.getDebugLoc();
3909 
3910     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3911 
3912     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3913 
3914     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3915     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3916 
3917     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3918     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3919 
3920     MachineOperand &Dest = MI.getOperand(0);
3921     MachineOperand &Src0 = MI.getOperand(1);
3922     MachineOperand &Src1 = MI.getOperand(2);
3923 
3924     const TargetRegisterClass *Src0RC = Src0.isReg()
3925                                             ? MRI.getRegClass(Src0.getReg())
3926                                             : &AMDGPU::VReg_64RegClass;
3927     const TargetRegisterClass *Src1RC = Src1.isReg()
3928                                             ? MRI.getRegClass(Src1.getReg())
3929                                             : &AMDGPU::VReg_64RegClass;
3930 
3931     const TargetRegisterClass *Src0SubRC =
3932         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3933     const TargetRegisterClass *Src1SubRC =
3934         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3935 
3936     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3937         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3938     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3939         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3940 
3941     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3942         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3943     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3944         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3945 
3946     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3947     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3948                                .addReg(CarryReg, RegState::Define)
3949                                .add(SrcReg0Sub0)
3950                                .add(SrcReg1Sub0)
3951                                .addImm(0); // clamp bit
3952 
3953     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3954     MachineInstr *HiHalf =
3955         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3956             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3957             .add(SrcReg0Sub1)
3958             .add(SrcReg1Sub1)
3959             .addReg(CarryReg, RegState::Kill)
3960             .addImm(0); // clamp bit
3961 
3962     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3963         .addReg(DestSub0)
3964         .addImm(AMDGPU::sub0)
3965         .addReg(DestSub1)
3966         .addImm(AMDGPU::sub1);
3967     TII->legalizeOperands(*LoHalf);
3968     TII->legalizeOperands(*HiHalf);
3969     MI.eraseFromParent();
3970     return BB;
3971   }
3972   case AMDGPU::S_ADD_CO_PSEUDO:
3973   case AMDGPU::S_SUB_CO_PSEUDO: {
3974     // This pseudo has a chance to be selected
3975     // only from uniform add/subcarry node. All the VGPR operands
3976     // therefore assumed to be splat vectors.
3977     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3978     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3979     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3980     MachineBasicBlock::iterator MII = MI;
3981     const DebugLoc &DL = MI.getDebugLoc();
3982     MachineOperand &Dest = MI.getOperand(0);
3983     MachineOperand &CarryDest = MI.getOperand(1);
3984     MachineOperand &Src0 = MI.getOperand(2);
3985     MachineOperand &Src1 = MI.getOperand(3);
3986     MachineOperand &Src2 = MI.getOperand(4);
3987     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3988                        ? AMDGPU::S_ADDC_U32
3989                        : AMDGPU::S_SUBB_U32;
3990     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3991       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3992       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3993           .addReg(Src0.getReg());
3994       Src0.setReg(RegOp0);
3995     }
3996     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3997       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3998       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3999           .addReg(Src1.getReg());
4000       Src1.setReg(RegOp1);
4001     }
4002     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4003     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4004       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4005           .addReg(Src2.getReg());
4006       Src2.setReg(RegOp2);
4007     }
4008 
4009     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
4010       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4011           .addReg(Src2.getReg())
4012           .addImm(0);
4013     } else {
4014       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4015           .addReg(Src2.getReg())
4016           .addImm(0);
4017     }
4018 
4019     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4020 
4021     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4022       .addReg(AMDGPU::SCC);
4023     MI.eraseFromParent();
4024     return BB;
4025   }
4026   case AMDGPU::SI_INIT_M0: {
4027     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4028             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4029         .add(MI.getOperand(0));
4030     MI.eraseFromParent();
4031     return BB;
4032   }
4033   case AMDGPU::SI_INIT_EXEC:
4034     // This should be before all vector instructions.
4035     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
4036             AMDGPU::EXEC)
4037         .addImm(MI.getOperand(0).getImm());
4038     MI.eraseFromParent();
4039     return BB;
4040 
4041   case AMDGPU::SI_INIT_EXEC_LO:
4042     // This should be before all vector instructions.
4043     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
4044             AMDGPU::EXEC_LO)
4045         .addImm(MI.getOperand(0).getImm());
4046     MI.eraseFromParent();
4047     return BB;
4048 
4049   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
4050     // Extract the thread count from an SGPR input and set EXEC accordingly.
4051     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
4052     //
4053     // S_BFE_U32 count, input, {shift, 7}
4054     // S_BFM_B64 exec, count, 0
4055     // S_CMP_EQ_U32 count, 64
4056     // S_CMOV_B64 exec, -1
4057     MachineInstr *FirstMI = &*BB->begin();
4058     MachineRegisterInfo &MRI = MF->getRegInfo();
4059     Register InputReg = MI.getOperand(0).getReg();
4060     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4061     bool Found = false;
4062 
4063     // Move the COPY of the input reg to the beginning, so that we can use it.
4064     for (auto I = BB->begin(); I != &MI; I++) {
4065       if (I->getOpcode() != TargetOpcode::COPY ||
4066           I->getOperand(0).getReg() != InputReg)
4067         continue;
4068 
4069       if (I == FirstMI) {
4070         FirstMI = &*++BB->begin();
4071       } else {
4072         I->removeFromParent();
4073         BB->insert(FirstMI, &*I);
4074       }
4075       Found = true;
4076       break;
4077     }
4078     assert(Found);
4079     (void)Found;
4080 
4081     // This should be before all vector instructions.
4082     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
4083     bool isWave32 = getSubtarget()->isWave32();
4084     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4085     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
4086         .addReg(InputReg)
4087         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
4088     BuildMI(*BB, FirstMI, DebugLoc(),
4089             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
4090             Exec)
4091         .addReg(CountReg)
4092         .addImm(0);
4093     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
4094         .addReg(CountReg, RegState::Kill)
4095         .addImm(getSubtarget()->getWavefrontSize());
4096     BuildMI(*BB, FirstMI, DebugLoc(),
4097             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
4098             Exec)
4099         .addImm(-1);
4100     MI.eraseFromParent();
4101     return BB;
4102   }
4103 
4104   case AMDGPU::GET_GROUPSTATICSIZE: {
4105     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4106            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4107     DebugLoc DL = MI.getDebugLoc();
4108     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4109         .add(MI.getOperand(0))
4110         .addImm(MFI->getLDSSize());
4111     MI.eraseFromParent();
4112     return BB;
4113   }
4114   case AMDGPU::SI_INDIRECT_SRC_V1:
4115   case AMDGPU::SI_INDIRECT_SRC_V2:
4116   case AMDGPU::SI_INDIRECT_SRC_V4:
4117   case AMDGPU::SI_INDIRECT_SRC_V8:
4118   case AMDGPU::SI_INDIRECT_SRC_V16:
4119   case AMDGPU::SI_INDIRECT_SRC_V32:
4120     return emitIndirectSrc(MI, *BB, *getSubtarget());
4121   case AMDGPU::SI_INDIRECT_DST_V1:
4122   case AMDGPU::SI_INDIRECT_DST_V2:
4123   case AMDGPU::SI_INDIRECT_DST_V4:
4124   case AMDGPU::SI_INDIRECT_DST_V8:
4125   case AMDGPU::SI_INDIRECT_DST_V16:
4126   case AMDGPU::SI_INDIRECT_DST_V32:
4127     return emitIndirectDst(MI, *BB, *getSubtarget());
4128   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4129   case AMDGPU::SI_KILL_I1_PSEUDO:
4130     return splitKillBlock(MI, BB);
4131   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4132     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4133     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4134     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4135 
4136     Register Dst = MI.getOperand(0).getReg();
4137     Register Src0 = MI.getOperand(1).getReg();
4138     Register Src1 = MI.getOperand(2).getReg();
4139     const DebugLoc &DL = MI.getDebugLoc();
4140     Register SrcCond = MI.getOperand(3).getReg();
4141 
4142     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4143     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4144     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4145     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4146 
4147     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4148       .addReg(SrcCond);
4149     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4150       .addImm(0)
4151       .addReg(Src0, 0, AMDGPU::sub0)
4152       .addImm(0)
4153       .addReg(Src1, 0, AMDGPU::sub0)
4154       .addReg(SrcCondCopy);
4155     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4156       .addImm(0)
4157       .addReg(Src0, 0, AMDGPU::sub1)
4158       .addImm(0)
4159       .addReg(Src1, 0, AMDGPU::sub1)
4160       .addReg(SrcCondCopy);
4161 
4162     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4163       .addReg(DstLo)
4164       .addImm(AMDGPU::sub0)
4165       .addReg(DstHi)
4166       .addImm(AMDGPU::sub1);
4167     MI.eraseFromParent();
4168     return BB;
4169   }
4170   case AMDGPU::SI_BR_UNDEF: {
4171     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4172     const DebugLoc &DL = MI.getDebugLoc();
4173     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4174                            .add(MI.getOperand(0));
4175     Br->getOperand(1).setIsUndef(true); // read undef SCC
4176     MI.eraseFromParent();
4177     return BB;
4178   }
4179   case AMDGPU::ADJCALLSTACKUP:
4180   case AMDGPU::ADJCALLSTACKDOWN: {
4181     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4182     MachineInstrBuilder MIB(*MF, &MI);
4183     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4184        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4185     return BB;
4186   }
4187   case AMDGPU::SI_CALL_ISEL: {
4188     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4189     const DebugLoc &DL = MI.getDebugLoc();
4190 
4191     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4192 
4193     MachineInstrBuilder MIB;
4194     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4195 
4196     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4197       MIB.add(MI.getOperand(I));
4198 
4199     MIB.cloneMemRefs(MI);
4200     MI.eraseFromParent();
4201     return BB;
4202   }
4203   case AMDGPU::V_ADD_CO_U32_e32:
4204   case AMDGPU::V_SUB_CO_U32_e32:
4205   case AMDGPU::V_SUBREV_CO_U32_e32: {
4206     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4207     const DebugLoc &DL = MI.getDebugLoc();
4208     unsigned Opc = MI.getOpcode();
4209 
4210     bool NeedClampOperand = false;
4211     if (TII->pseudoToMCOpcode(Opc) == -1) {
4212       Opc = AMDGPU::getVOPe64(Opc);
4213       NeedClampOperand = true;
4214     }
4215 
4216     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4217     if (TII->isVOP3(*I)) {
4218       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4219       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4220       I.addReg(TRI->getVCC(), RegState::Define);
4221     }
4222     I.add(MI.getOperand(1))
4223      .add(MI.getOperand(2));
4224     if (NeedClampOperand)
4225       I.addImm(0); // clamp bit for e64 encoding
4226 
4227     TII->legalizeOperands(*I);
4228 
4229     MI.eraseFromParent();
4230     return BB;
4231   }
4232   case AMDGPU::DS_GWS_INIT:
4233   case AMDGPU::DS_GWS_SEMA_V:
4234   case AMDGPU::DS_GWS_SEMA_BR:
4235   case AMDGPU::DS_GWS_SEMA_P:
4236   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4237   case AMDGPU::DS_GWS_BARRIER:
4238     // A s_waitcnt 0 is required to be the instruction immediately following.
4239     if (getSubtarget()->hasGWSAutoReplay()) {
4240       bundleInstWithWaitcnt(MI);
4241       return BB;
4242     }
4243 
4244     return emitGWSMemViolTestLoop(MI, BB);
4245   case AMDGPU::S_SETREG_B32: {
4246     // Try to optimize cases that only set the denormal mode or rounding mode.
4247     //
4248     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4249     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4250     // instead.
4251     //
4252     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4253     // allow you to have a no side effect instruction in the output of a
4254     // sideeffecting pattern.
4255     unsigned ID, Offset, Width;
4256     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4257     if (ID != AMDGPU::Hwreg::ID_MODE)
4258       return BB;
4259 
4260     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4261     const unsigned SetMask = WidthMask << Offset;
4262 
4263     if (getSubtarget()->hasDenormModeInst()) {
4264       unsigned SetDenormOp = 0;
4265       unsigned SetRoundOp = 0;
4266 
4267       // The dedicated instructions can only set the whole denorm or round mode
4268       // at once, not a subset of bits in either.
4269       if (SetMask ==
4270           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4271         // If this fully sets both the round and denorm mode, emit the two
4272         // dedicated instructions for these.
4273         SetRoundOp = AMDGPU::S_ROUND_MODE;
4274         SetDenormOp = AMDGPU::S_DENORM_MODE;
4275       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4276         SetRoundOp = AMDGPU::S_ROUND_MODE;
4277       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4278         SetDenormOp = AMDGPU::S_DENORM_MODE;
4279       }
4280 
4281       if (SetRoundOp || SetDenormOp) {
4282         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4283         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4284         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4285           unsigned ImmVal = Def->getOperand(1).getImm();
4286           if (SetRoundOp) {
4287             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4288                 .addImm(ImmVal & 0xf);
4289 
4290             // If we also have the denorm mode, get just the denorm mode bits.
4291             ImmVal >>= 4;
4292           }
4293 
4294           if (SetDenormOp) {
4295             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4296                 .addImm(ImmVal & 0xf);
4297           }
4298 
4299           MI.eraseFromParent();
4300           return BB;
4301         }
4302       }
4303     }
4304 
4305     // If only FP bits are touched, used the no side effects pseudo.
4306     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4307                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4308       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4309 
4310     return BB;
4311   }
4312   default:
4313     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4314   }
4315 }
4316 
4317 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4318   return isTypeLegal(VT.getScalarType());
4319 }
4320 
4321 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4322   // This currently forces unfolding various combinations of fsub into fma with
4323   // free fneg'd operands. As long as we have fast FMA (controlled by
4324   // isFMAFasterThanFMulAndFAdd), we should perform these.
4325 
4326   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4327   // most of these combines appear to be cycle neutral but save on instruction
4328   // count / code size.
4329   return true;
4330 }
4331 
4332 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4333                                          EVT VT) const {
4334   if (!VT.isVector()) {
4335     return MVT::i1;
4336   }
4337   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4338 }
4339 
4340 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4341   // TODO: Should i16 be used always if legal? For now it would force VALU
4342   // shifts.
4343   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4344 }
4345 
4346 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4347   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4348              ? Ty.changeElementSize(16)
4349              : Ty.changeElementSize(32);
4350 }
4351 
4352 // Answering this is somewhat tricky and depends on the specific device which
4353 // have different rates for fma or all f64 operations.
4354 //
4355 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4356 // regardless of which device (although the number of cycles differs between
4357 // devices), so it is always profitable for f64.
4358 //
4359 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4360 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4361 // which we can always do even without fused FP ops since it returns the same
4362 // result as the separate operations and since it is always full
4363 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4364 // however does not support denormals, so we do report fma as faster if we have
4365 // a fast fma device and require denormals.
4366 //
4367 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4368                                                   EVT VT) const {
4369   VT = VT.getScalarType();
4370 
4371   switch (VT.getSimpleVT().SimpleTy) {
4372   case MVT::f32: {
4373     // If mad is not available this depends only on if f32 fma is full rate.
4374     if (!Subtarget->hasMadMacF32Insts())
4375       return Subtarget->hasFastFMAF32();
4376 
4377     // Otherwise f32 mad is always full rate and returns the same result as
4378     // the separate operations so should be preferred over fma.
4379     // However does not support denomals.
4380     if (hasFP32Denormals(MF))
4381       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4382 
4383     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4384     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4385   }
4386   case MVT::f64:
4387     return true;
4388   case MVT::f16:
4389     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4390   default:
4391     break;
4392   }
4393 
4394   return false;
4395 }
4396 
4397 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4398                                    const SDNode *N) const {
4399   // TODO: Check future ftz flag
4400   // v_mad_f32/v_mac_f32 do not support denormals.
4401   EVT VT = N->getValueType(0);
4402   if (VT == MVT::f32)
4403     return Subtarget->hasMadMacF32Insts() &&
4404            !hasFP32Denormals(DAG.getMachineFunction());
4405   if (VT == MVT::f16) {
4406     return Subtarget->hasMadF16() &&
4407            !hasFP64FP16Denormals(DAG.getMachineFunction());
4408   }
4409 
4410   return false;
4411 }
4412 
4413 //===----------------------------------------------------------------------===//
4414 // Custom DAG Lowering Operations
4415 //===----------------------------------------------------------------------===//
4416 
4417 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4418 // wider vector type is legal.
4419 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4420                                              SelectionDAG &DAG) const {
4421   unsigned Opc = Op.getOpcode();
4422   EVT VT = Op.getValueType();
4423   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4424 
4425   SDValue Lo, Hi;
4426   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4427 
4428   SDLoc SL(Op);
4429   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4430                              Op->getFlags());
4431   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4432                              Op->getFlags());
4433 
4434   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4435 }
4436 
4437 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4438 // wider vector type is legal.
4439 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4440                                               SelectionDAG &DAG) const {
4441   unsigned Opc = Op.getOpcode();
4442   EVT VT = Op.getValueType();
4443   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4444 
4445   SDValue Lo0, Hi0;
4446   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4447   SDValue Lo1, Hi1;
4448   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4449 
4450   SDLoc SL(Op);
4451 
4452   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4453                              Op->getFlags());
4454   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4455                              Op->getFlags());
4456 
4457   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4458 }
4459 
4460 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4461                                               SelectionDAG &DAG) const {
4462   unsigned Opc = Op.getOpcode();
4463   EVT VT = Op.getValueType();
4464   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4465 
4466   SDValue Lo0, Hi0;
4467   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4468   SDValue Lo1, Hi1;
4469   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4470   SDValue Lo2, Hi2;
4471   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4472 
4473   SDLoc SL(Op);
4474 
4475   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4476                              Op->getFlags());
4477   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4478                              Op->getFlags());
4479 
4480   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4481 }
4482 
4483 
4484 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4485   switch (Op.getOpcode()) {
4486   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4487   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4488   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4489   case ISD::LOAD: {
4490     SDValue Result = LowerLOAD(Op, DAG);
4491     assert((!Result.getNode() ||
4492             Result.getNode()->getNumValues() == 2) &&
4493            "Load should return a value and a chain");
4494     return Result;
4495   }
4496 
4497   case ISD::FSIN:
4498   case ISD::FCOS:
4499     return LowerTrig(Op, DAG);
4500   case ISD::SELECT: return LowerSELECT(Op, DAG);
4501   case ISD::FDIV: return LowerFDIV(Op, DAG);
4502   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4503   case ISD::STORE: return LowerSTORE(Op, DAG);
4504   case ISD::GlobalAddress: {
4505     MachineFunction &MF = DAG.getMachineFunction();
4506     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4507     return LowerGlobalAddress(MFI, Op, DAG);
4508   }
4509   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4510   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4511   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4512   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4513   case ISD::INSERT_SUBVECTOR:
4514     return lowerINSERT_SUBVECTOR(Op, DAG);
4515   case ISD::INSERT_VECTOR_ELT:
4516     return lowerINSERT_VECTOR_ELT(Op, DAG);
4517   case ISD::EXTRACT_VECTOR_ELT:
4518     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4519   case ISD::VECTOR_SHUFFLE:
4520     return lowerVECTOR_SHUFFLE(Op, DAG);
4521   case ISD::BUILD_VECTOR:
4522     return lowerBUILD_VECTOR(Op, DAG);
4523   case ISD::FP_ROUND:
4524     return lowerFP_ROUND(Op, DAG);
4525   case ISD::TRAP:
4526     return lowerTRAP(Op, DAG);
4527   case ISD::DEBUGTRAP:
4528     return lowerDEBUGTRAP(Op, DAG);
4529   case ISD::FABS:
4530   case ISD::FNEG:
4531   case ISD::FCANONICALIZE:
4532   case ISD::BSWAP:
4533     return splitUnaryVectorOp(Op, DAG);
4534   case ISD::FMINNUM:
4535   case ISD::FMAXNUM:
4536     return lowerFMINNUM_FMAXNUM(Op, DAG);
4537   case ISD::FMA:
4538     return splitTernaryVectorOp(Op, DAG);
4539   case ISD::SHL:
4540   case ISD::SRA:
4541   case ISD::SRL:
4542   case ISD::ADD:
4543   case ISD::SUB:
4544   case ISD::MUL:
4545   case ISD::SMIN:
4546   case ISD::SMAX:
4547   case ISD::UMIN:
4548   case ISD::UMAX:
4549   case ISD::FADD:
4550   case ISD::FMUL:
4551   case ISD::FMINNUM_IEEE:
4552   case ISD::FMAXNUM_IEEE:
4553   case ISD::UADDSAT:
4554   case ISD::USUBSAT:
4555   case ISD::SADDSAT:
4556   case ISD::SSUBSAT:
4557     return splitBinaryVectorOp(Op, DAG);
4558   case ISD::SMULO:
4559   case ISD::UMULO:
4560     return lowerXMULO(Op, DAG);
4561   case ISD::DYNAMIC_STACKALLOC:
4562     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4563   }
4564   return SDValue();
4565 }
4566 
4567 // Used for D16: Casts the result of an instruction into the right vector,
4568 // packs values if loads return unpacked values.
4569 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4570                                        const SDLoc &DL,
4571                                        SelectionDAG &DAG, bool Unpacked) {
4572   if (!LoadVT.isVector())
4573     return Result;
4574 
4575   // Cast back to the original packed type or to a larger type that is a
4576   // multiple of 32 bit for D16. Widening the return type is a required for
4577   // legalization.
4578   EVT FittingLoadVT = LoadVT;
4579   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4580     FittingLoadVT =
4581         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4582                          LoadVT.getVectorNumElements() + 1);
4583   }
4584 
4585   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4586     // Truncate to v2i16/v4i16.
4587     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4588 
4589     // Workaround legalizer not scalarizing truncate after vector op
4590     // legalization but not creating intermediate vector trunc.
4591     SmallVector<SDValue, 4> Elts;
4592     DAG.ExtractVectorElements(Result, Elts);
4593     for (SDValue &Elt : Elts)
4594       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4595 
4596     // Pad illegal v1i16/v3fi6 to v4i16
4597     if ((LoadVT.getVectorNumElements() % 2) == 1)
4598       Elts.push_back(DAG.getUNDEF(MVT::i16));
4599 
4600     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4601 
4602     // Bitcast to original type (v2f16/v4f16).
4603     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4604   }
4605 
4606   // Cast back to the original packed type.
4607   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4608 }
4609 
4610 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4611                                               MemSDNode *M,
4612                                               SelectionDAG &DAG,
4613                                               ArrayRef<SDValue> Ops,
4614                                               bool IsIntrinsic) const {
4615   SDLoc DL(M);
4616 
4617   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4618   EVT LoadVT = M->getValueType(0);
4619 
4620   EVT EquivLoadVT = LoadVT;
4621   if (LoadVT.isVector()) {
4622     if (Unpacked) {
4623       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4624                                      LoadVT.getVectorNumElements());
4625     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4626       // Widen v3f16 to legal type
4627       EquivLoadVT =
4628           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4629                            LoadVT.getVectorNumElements() + 1);
4630     }
4631   }
4632 
4633   // Change from v4f16/v2f16 to EquivLoadVT.
4634   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4635 
4636   SDValue Load
4637     = DAG.getMemIntrinsicNode(
4638       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4639       VTList, Ops, M->getMemoryVT(),
4640       M->getMemOperand());
4641 
4642   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4643 
4644   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4645 }
4646 
4647 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4648                                              SelectionDAG &DAG,
4649                                              ArrayRef<SDValue> Ops) const {
4650   SDLoc DL(M);
4651   EVT LoadVT = M->getValueType(0);
4652   EVT EltType = LoadVT.getScalarType();
4653   EVT IntVT = LoadVT.changeTypeToInteger();
4654 
4655   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4656 
4657   unsigned Opc =
4658       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4659 
4660   if (IsD16) {
4661     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4662   }
4663 
4664   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4665   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4666     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4667 
4668   if (isTypeLegal(LoadVT)) {
4669     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4670                                M->getMemOperand(), DAG);
4671   }
4672 
4673   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4674   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4675   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4676                                         M->getMemOperand(), DAG);
4677   return DAG.getMergeValues(
4678       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4679       DL);
4680 }
4681 
4682 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4683                                   SDNode *N, SelectionDAG &DAG) {
4684   EVT VT = N->getValueType(0);
4685   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4686   unsigned CondCode = CD->getZExtValue();
4687   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4688     return DAG.getUNDEF(VT);
4689 
4690   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4691 
4692   SDValue LHS = N->getOperand(1);
4693   SDValue RHS = N->getOperand(2);
4694 
4695   SDLoc DL(N);
4696 
4697   EVT CmpVT = LHS.getValueType();
4698   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4699     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4700       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4701     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4702     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4703   }
4704 
4705   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4706 
4707   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4708   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4709 
4710   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4711                               DAG.getCondCode(CCOpcode));
4712   if (VT.bitsEq(CCVT))
4713     return SetCC;
4714   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4715 }
4716 
4717 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4718                                   SDNode *N, SelectionDAG &DAG) {
4719   EVT VT = N->getValueType(0);
4720   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4721 
4722   unsigned CondCode = CD->getZExtValue();
4723   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4724     return DAG.getUNDEF(VT);
4725 
4726   SDValue Src0 = N->getOperand(1);
4727   SDValue Src1 = N->getOperand(2);
4728   EVT CmpVT = Src0.getValueType();
4729   SDLoc SL(N);
4730 
4731   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4732     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4733     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4734   }
4735 
4736   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4737   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4738   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4739   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4740   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4741                               Src1, DAG.getCondCode(CCOpcode));
4742   if (VT.bitsEq(CCVT))
4743     return SetCC;
4744   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4745 }
4746 
4747 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4748                                     SelectionDAG &DAG) {
4749   EVT VT = N->getValueType(0);
4750   SDValue Src = N->getOperand(1);
4751   SDLoc SL(N);
4752 
4753   if (Src.getOpcode() == ISD::SETCC) {
4754     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4755     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4756                        Src.getOperand(1), Src.getOperand(2));
4757   }
4758   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4759     // (ballot 0) -> 0
4760     if (Arg->isNullValue())
4761       return DAG.getConstant(0, SL, VT);
4762 
4763     // (ballot 1) -> EXEC/EXEC_LO
4764     if (Arg->isOne()) {
4765       Register Exec;
4766       if (VT.getScalarSizeInBits() == 32)
4767         Exec = AMDGPU::EXEC_LO;
4768       else if (VT.getScalarSizeInBits() == 64)
4769         Exec = AMDGPU::EXEC;
4770       else
4771         return SDValue();
4772 
4773       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4774     }
4775   }
4776 
4777   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4778   // ISD::SETNE)
4779   return DAG.getNode(
4780       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4781       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4782 }
4783 
4784 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4785                                           SmallVectorImpl<SDValue> &Results,
4786                                           SelectionDAG &DAG) const {
4787   switch (N->getOpcode()) {
4788   case ISD::INSERT_VECTOR_ELT: {
4789     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4790       Results.push_back(Res);
4791     return;
4792   }
4793   case ISD::EXTRACT_VECTOR_ELT: {
4794     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4795       Results.push_back(Res);
4796     return;
4797   }
4798   case ISD::INTRINSIC_WO_CHAIN: {
4799     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4800     switch (IID) {
4801     case Intrinsic::amdgcn_cvt_pkrtz: {
4802       SDValue Src0 = N->getOperand(1);
4803       SDValue Src1 = N->getOperand(2);
4804       SDLoc SL(N);
4805       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4806                                 Src0, Src1);
4807       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4808       return;
4809     }
4810     case Intrinsic::amdgcn_cvt_pknorm_i16:
4811     case Intrinsic::amdgcn_cvt_pknorm_u16:
4812     case Intrinsic::amdgcn_cvt_pk_i16:
4813     case Intrinsic::amdgcn_cvt_pk_u16: {
4814       SDValue Src0 = N->getOperand(1);
4815       SDValue Src1 = N->getOperand(2);
4816       SDLoc SL(N);
4817       unsigned Opcode;
4818 
4819       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4820         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4821       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4822         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4823       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4824         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4825       else
4826         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4827 
4828       EVT VT = N->getValueType(0);
4829       if (isTypeLegal(VT))
4830         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4831       else {
4832         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4833         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4834       }
4835       return;
4836     }
4837     }
4838     break;
4839   }
4840   case ISD::INTRINSIC_W_CHAIN: {
4841     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4842       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4843         // FIXME: Hacky
4844         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4845           Results.push_back(Res.getOperand(I));
4846         }
4847       } else {
4848         Results.push_back(Res);
4849         Results.push_back(Res.getValue(1));
4850       }
4851       return;
4852     }
4853 
4854     break;
4855   }
4856   case ISD::SELECT: {
4857     SDLoc SL(N);
4858     EVT VT = N->getValueType(0);
4859     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4860     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4861     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4862 
4863     EVT SelectVT = NewVT;
4864     if (NewVT.bitsLT(MVT::i32)) {
4865       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4866       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4867       SelectVT = MVT::i32;
4868     }
4869 
4870     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4871                                     N->getOperand(0), LHS, RHS);
4872 
4873     if (NewVT != SelectVT)
4874       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4875     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4876     return;
4877   }
4878   case ISD::FNEG: {
4879     if (N->getValueType(0) != MVT::v2f16)
4880       break;
4881 
4882     SDLoc SL(N);
4883     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4884 
4885     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4886                              BC,
4887                              DAG.getConstant(0x80008000, SL, MVT::i32));
4888     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4889     return;
4890   }
4891   case ISD::FABS: {
4892     if (N->getValueType(0) != MVT::v2f16)
4893       break;
4894 
4895     SDLoc SL(N);
4896     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4897 
4898     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4899                              BC,
4900                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4901     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4902     return;
4903   }
4904   default:
4905     break;
4906   }
4907 }
4908 
4909 /// Helper function for LowerBRCOND
4910 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4911 
4912   SDNode *Parent = Value.getNode();
4913   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4914        I != E; ++I) {
4915 
4916     if (I.getUse().get() != Value)
4917       continue;
4918 
4919     if (I->getOpcode() == Opcode)
4920       return *I;
4921   }
4922   return nullptr;
4923 }
4924 
4925 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4926   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4927     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4928     case Intrinsic::amdgcn_if:
4929       return AMDGPUISD::IF;
4930     case Intrinsic::amdgcn_else:
4931       return AMDGPUISD::ELSE;
4932     case Intrinsic::amdgcn_loop:
4933       return AMDGPUISD::LOOP;
4934     case Intrinsic::amdgcn_end_cf:
4935       llvm_unreachable("should not occur");
4936     default:
4937       return 0;
4938     }
4939   }
4940 
4941   // break, if_break, else_break are all only used as inputs to loop, not
4942   // directly as branch conditions.
4943   return 0;
4944 }
4945 
4946 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4947   const Triple &TT = getTargetMachine().getTargetTriple();
4948   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4949           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4950          AMDGPU::shouldEmitConstantsToTextSection(TT);
4951 }
4952 
4953 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4954   // FIXME: Either avoid relying on address space here or change the default
4955   // address space for functions to avoid the explicit check.
4956   return (GV->getValueType()->isFunctionTy() ||
4957           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4958          !shouldEmitFixup(GV) &&
4959          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4960 }
4961 
4962 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4963   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4964 }
4965 
4966 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4967   if (!GV->hasExternalLinkage())
4968     return true;
4969 
4970   const auto OS = getTargetMachine().getTargetTriple().getOS();
4971   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4972 }
4973 
4974 /// This transforms the control flow intrinsics to get the branch destination as
4975 /// last parameter, also switches branch target with BR if the need arise
4976 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4977                                       SelectionDAG &DAG) const {
4978   SDLoc DL(BRCOND);
4979 
4980   SDNode *Intr = BRCOND.getOperand(1).getNode();
4981   SDValue Target = BRCOND.getOperand(2);
4982   SDNode *BR = nullptr;
4983   SDNode *SetCC = nullptr;
4984 
4985   if (Intr->getOpcode() == ISD::SETCC) {
4986     // As long as we negate the condition everything is fine
4987     SetCC = Intr;
4988     Intr = SetCC->getOperand(0).getNode();
4989 
4990   } else {
4991     // Get the target from BR if we don't negate the condition
4992     BR = findUser(BRCOND, ISD::BR);
4993     assert(BR && "brcond missing unconditional branch user");
4994     Target = BR->getOperand(1);
4995   }
4996 
4997   unsigned CFNode = isCFIntrinsic(Intr);
4998   if (CFNode == 0) {
4999     // This is a uniform branch so we don't need to legalize.
5000     return BRCOND;
5001   }
5002 
5003   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5004                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5005 
5006   assert(!SetCC ||
5007         (SetCC->getConstantOperandVal(1) == 1 &&
5008          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5009                                                              ISD::SETNE));
5010 
5011   // operands of the new intrinsic call
5012   SmallVector<SDValue, 4> Ops;
5013   if (HaveChain)
5014     Ops.push_back(BRCOND.getOperand(0));
5015 
5016   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5017   Ops.push_back(Target);
5018 
5019   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5020 
5021   // build the new intrinsic call
5022   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5023 
5024   if (!HaveChain) {
5025     SDValue Ops[] =  {
5026       SDValue(Result, 0),
5027       BRCOND.getOperand(0)
5028     };
5029 
5030     Result = DAG.getMergeValues(Ops, DL).getNode();
5031   }
5032 
5033   if (BR) {
5034     // Give the branch instruction our target
5035     SDValue Ops[] = {
5036       BR->getOperand(0),
5037       BRCOND.getOperand(2)
5038     };
5039     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5040     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5041   }
5042 
5043   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5044 
5045   // Copy the intrinsic results to registers
5046   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5047     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5048     if (!CopyToReg)
5049       continue;
5050 
5051     Chain = DAG.getCopyToReg(
5052       Chain, DL,
5053       CopyToReg->getOperand(1),
5054       SDValue(Result, i - 1),
5055       SDValue());
5056 
5057     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5058   }
5059 
5060   // Remove the old intrinsic from the chain
5061   DAG.ReplaceAllUsesOfValueWith(
5062     SDValue(Intr, Intr->getNumValues() - 1),
5063     Intr->getOperand(0));
5064 
5065   return Chain;
5066 }
5067 
5068 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5069                                           SelectionDAG &DAG) const {
5070   MVT VT = Op.getSimpleValueType();
5071   SDLoc DL(Op);
5072   // Checking the depth
5073   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5074     return DAG.getConstant(0, DL, VT);
5075 
5076   MachineFunction &MF = DAG.getMachineFunction();
5077   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5078   // Check for kernel and shader functions
5079   if (Info->isEntryFunction())
5080     return DAG.getConstant(0, DL, VT);
5081 
5082   MachineFrameInfo &MFI = MF.getFrameInfo();
5083   // There is a call to @llvm.returnaddress in this function
5084   MFI.setReturnAddressIsTaken(true);
5085 
5086   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5087   // Get the return address reg and mark it as an implicit live-in
5088   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5089 
5090   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5091 }
5092 
5093 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5094                                             SDValue Op,
5095                                             const SDLoc &DL,
5096                                             EVT VT) const {
5097   return Op.getValueType().bitsLE(VT) ?
5098       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5099     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5100                 DAG.getTargetConstant(0, DL, MVT::i32));
5101 }
5102 
5103 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5104   assert(Op.getValueType() == MVT::f16 &&
5105          "Do not know how to custom lower FP_ROUND for non-f16 type");
5106 
5107   SDValue Src = Op.getOperand(0);
5108   EVT SrcVT = Src.getValueType();
5109   if (SrcVT != MVT::f64)
5110     return Op;
5111 
5112   SDLoc DL(Op);
5113 
5114   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5115   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5116   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5117 }
5118 
5119 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5120                                                SelectionDAG &DAG) const {
5121   EVT VT = Op.getValueType();
5122   const MachineFunction &MF = DAG.getMachineFunction();
5123   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5124   bool IsIEEEMode = Info->getMode().IEEE;
5125 
5126   // FIXME: Assert during selection that this is only selected for
5127   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5128   // mode functions, but this happens to be OK since it's only done in cases
5129   // where there is known no sNaN.
5130   if (IsIEEEMode)
5131     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5132 
5133   if (VT == MVT::v4f16)
5134     return splitBinaryVectorOp(Op, DAG);
5135   return Op;
5136 }
5137 
5138 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5139   EVT VT = Op.getValueType();
5140   SDLoc SL(Op);
5141   SDValue LHS = Op.getOperand(0);
5142   SDValue RHS = Op.getOperand(1);
5143   bool isSigned = Op.getOpcode() == ISD::SMULO;
5144 
5145   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5146     const APInt &C = RHSC->getAPIntValue();
5147     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5148     if (C.isPowerOf2()) {
5149       // smulo(x, signed_min) is same as umulo(x, signed_min).
5150       bool UseArithShift = isSigned && !C.isMinSignedValue();
5151       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5152       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5153       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5154           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5155                       SL, VT, Result, ShiftAmt),
5156           LHS, ISD::SETNE);
5157       return DAG.getMergeValues({ Result, Overflow }, SL);
5158     }
5159   }
5160 
5161   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5162   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5163                             SL, VT, LHS, RHS);
5164 
5165   SDValue Sign = isSigned
5166     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5167                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5168     : DAG.getConstant(0, SL, VT);
5169   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5170 
5171   return DAG.getMergeValues({ Result, Overflow }, SL);
5172 }
5173 
5174 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5175   SDLoc SL(Op);
5176   SDValue Chain = Op.getOperand(0);
5177 
5178   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5179       !Subtarget->isTrapHandlerEnabled())
5180     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5181 
5182   MachineFunction &MF = DAG.getMachineFunction();
5183   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5184   Register UserSGPR = Info->getQueuePtrUserSGPR();
5185   assert(UserSGPR != AMDGPU::NoRegister);
5186   SDValue QueuePtr = CreateLiveInRegister(
5187     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5188   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5189   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5190                                    QueuePtr, SDValue());
5191   SDValue Ops[] = {
5192     ToReg,
5193     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5194     SGPR01,
5195     ToReg.getValue(1)
5196   };
5197   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5198 }
5199 
5200 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5201   SDLoc SL(Op);
5202   SDValue Chain = Op.getOperand(0);
5203   MachineFunction &MF = DAG.getMachineFunction();
5204 
5205   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5206       !Subtarget->isTrapHandlerEnabled()) {
5207     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5208                                      "debugtrap handler not supported",
5209                                      Op.getDebugLoc(),
5210                                      DS_Warning);
5211     LLVMContext &Ctx = MF.getFunction().getContext();
5212     Ctx.diagnose(NoTrap);
5213     return Chain;
5214   }
5215 
5216   SDValue Ops[] = {
5217     Chain,
5218     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5219   };
5220   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5221 }
5222 
5223 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5224                                              SelectionDAG &DAG) const {
5225   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5226   if (Subtarget->hasApertureRegs()) {
5227     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5228         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5229         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5230     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5231         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5232         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5233     unsigned Encoding =
5234         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5235         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5236         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5237 
5238     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5239     SDValue ApertureReg = SDValue(
5240         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5241     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5242     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5243   }
5244 
5245   MachineFunction &MF = DAG.getMachineFunction();
5246   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5247   Register UserSGPR = Info->getQueuePtrUserSGPR();
5248   assert(UserSGPR != AMDGPU::NoRegister);
5249 
5250   SDValue QueuePtr = CreateLiveInRegister(
5251     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5252 
5253   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5254   // private_segment_aperture_base_hi.
5255   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5256 
5257   SDValue Ptr =
5258       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5259 
5260   // TODO: Use custom target PseudoSourceValue.
5261   // TODO: We should use the value from the IR intrinsic call, but it might not
5262   // be available and how do we get it?
5263   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5264   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5265                      commonAlignment(Align(64), StructOffset),
5266                      MachineMemOperand::MODereferenceable |
5267                          MachineMemOperand::MOInvariant);
5268 }
5269 
5270 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5271                                              SelectionDAG &DAG) const {
5272   SDLoc SL(Op);
5273   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5274 
5275   SDValue Src = ASC->getOperand(0);
5276   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5277 
5278   const AMDGPUTargetMachine &TM =
5279     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5280 
5281   // flat -> local/private
5282   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5283     unsigned DestAS = ASC->getDestAddressSpace();
5284 
5285     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5286         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5287       unsigned NullVal = TM.getNullPointerValue(DestAS);
5288       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5289       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5290       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5291 
5292       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5293                          NonNull, Ptr, SegmentNullPtr);
5294     }
5295   }
5296 
5297   // local/private -> flat
5298   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5299     unsigned SrcAS = ASC->getSrcAddressSpace();
5300 
5301     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5302         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5303       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5304       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5305 
5306       SDValue NonNull
5307         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5308 
5309       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5310       SDValue CvtPtr
5311         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5312 
5313       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5314                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5315                          FlatNullPtr);
5316     }
5317   }
5318 
5319   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5320       Src.getValueType() == MVT::i64)
5321     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5322 
5323   // global <-> flat are no-ops and never emitted.
5324 
5325   const MachineFunction &MF = DAG.getMachineFunction();
5326   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5327     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5328   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5329 
5330   return DAG.getUNDEF(ASC->getValueType(0));
5331 }
5332 
5333 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5334 // the small vector and inserting them into the big vector. That is better than
5335 // the default expansion of doing it via a stack slot. Even though the use of
5336 // the stack slot would be optimized away afterwards, the stack slot itself
5337 // remains.
5338 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5339                                                 SelectionDAG &DAG) const {
5340   SDValue Vec = Op.getOperand(0);
5341   SDValue Ins = Op.getOperand(1);
5342   SDValue Idx = Op.getOperand(2);
5343   EVT VecVT = Vec.getValueType();
5344   EVT InsVT = Ins.getValueType();
5345   EVT EltVT = VecVT.getVectorElementType();
5346   unsigned InsNumElts = InsVT.getVectorNumElements();
5347   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5348   SDLoc SL(Op);
5349 
5350   for (unsigned I = 0; I != InsNumElts; ++I) {
5351     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5352                               DAG.getConstant(I, SL, MVT::i32));
5353     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5354                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5355   }
5356   return Vec;
5357 }
5358 
5359 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5360                                                  SelectionDAG &DAG) const {
5361   SDValue Vec = Op.getOperand(0);
5362   SDValue InsVal = Op.getOperand(1);
5363   SDValue Idx = Op.getOperand(2);
5364   EVT VecVT = Vec.getValueType();
5365   EVT EltVT = VecVT.getVectorElementType();
5366   unsigned VecSize = VecVT.getSizeInBits();
5367   unsigned EltSize = EltVT.getSizeInBits();
5368 
5369 
5370   assert(VecSize <= 64);
5371 
5372   unsigned NumElts = VecVT.getVectorNumElements();
5373   SDLoc SL(Op);
5374   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5375 
5376   if (NumElts == 4 && EltSize == 16 && KIdx) {
5377     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5378 
5379     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5380                                  DAG.getConstant(0, SL, MVT::i32));
5381     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5382                                  DAG.getConstant(1, SL, MVT::i32));
5383 
5384     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5385     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5386 
5387     unsigned Idx = KIdx->getZExtValue();
5388     bool InsertLo = Idx < 2;
5389     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5390       InsertLo ? LoVec : HiVec,
5391       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5392       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5393 
5394     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5395 
5396     SDValue Concat = InsertLo ?
5397       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5398       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5399 
5400     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5401   }
5402 
5403   if (isa<ConstantSDNode>(Idx))
5404     return SDValue();
5405 
5406   MVT IntVT = MVT::getIntegerVT(VecSize);
5407 
5408   // Avoid stack access for dynamic indexing.
5409   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5410 
5411   // Create a congruent vector with the target value in each element so that
5412   // the required element can be masked and ORed into the target vector.
5413   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5414                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5415 
5416   assert(isPowerOf2_32(EltSize));
5417   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5418 
5419   // Convert vector index to bit-index.
5420   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5421 
5422   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5423   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5424                             DAG.getConstant(0xffff, SL, IntVT),
5425                             ScaledIdx);
5426 
5427   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5428   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5429                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5430 
5431   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5432   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5433 }
5434 
5435 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5436                                                   SelectionDAG &DAG) const {
5437   SDLoc SL(Op);
5438 
5439   EVT ResultVT = Op.getValueType();
5440   SDValue Vec = Op.getOperand(0);
5441   SDValue Idx = Op.getOperand(1);
5442   EVT VecVT = Vec.getValueType();
5443   unsigned VecSize = VecVT.getSizeInBits();
5444   EVT EltVT = VecVT.getVectorElementType();
5445   assert(VecSize <= 64);
5446 
5447   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5448 
5449   // Make sure we do any optimizations that will make it easier to fold
5450   // source modifiers before obscuring it with bit operations.
5451 
5452   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5453   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5454     return Combined;
5455 
5456   unsigned EltSize = EltVT.getSizeInBits();
5457   assert(isPowerOf2_32(EltSize));
5458 
5459   MVT IntVT = MVT::getIntegerVT(VecSize);
5460   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5461 
5462   // Convert vector index to bit-index (* EltSize)
5463   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5464 
5465   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5466   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5467 
5468   if (ResultVT == MVT::f16) {
5469     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5470     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5471   }
5472 
5473   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5474 }
5475 
5476 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5477   assert(Elt % 2 == 0);
5478   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5479 }
5480 
5481 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5482                                               SelectionDAG &DAG) const {
5483   SDLoc SL(Op);
5484   EVT ResultVT = Op.getValueType();
5485   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5486 
5487   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5488   EVT EltVT = PackVT.getVectorElementType();
5489   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5490 
5491   // vector_shuffle <0,1,6,7> lhs, rhs
5492   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5493   //
5494   // vector_shuffle <6,7,2,3> lhs, rhs
5495   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5496   //
5497   // vector_shuffle <6,7,0,1> lhs, rhs
5498   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5499 
5500   // Avoid scalarizing when both halves are reading from consecutive elements.
5501   SmallVector<SDValue, 4> Pieces;
5502   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5503     if (elementPairIsContiguous(SVN->getMask(), I)) {
5504       const int Idx = SVN->getMaskElt(I);
5505       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5506       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5507       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5508                                     PackVT, SVN->getOperand(VecIdx),
5509                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5510       Pieces.push_back(SubVec);
5511     } else {
5512       const int Idx0 = SVN->getMaskElt(I);
5513       const int Idx1 = SVN->getMaskElt(I + 1);
5514       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5515       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5516       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5517       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5518 
5519       SDValue Vec0 = SVN->getOperand(VecIdx0);
5520       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5521                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5522 
5523       SDValue Vec1 = SVN->getOperand(VecIdx1);
5524       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5525                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5526       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5527     }
5528   }
5529 
5530   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5531 }
5532 
5533 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5534                                             SelectionDAG &DAG) const {
5535   SDLoc SL(Op);
5536   EVT VT = Op.getValueType();
5537 
5538   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5539     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5540 
5541     // Turn into pair of packed build_vectors.
5542     // TODO: Special case for constants that can be materialized with s_mov_b64.
5543     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5544                                     { Op.getOperand(0), Op.getOperand(1) });
5545     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5546                                     { Op.getOperand(2), Op.getOperand(3) });
5547 
5548     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5549     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5550 
5551     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5552     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5553   }
5554 
5555   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5556   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5557 
5558   SDValue Lo = Op.getOperand(0);
5559   SDValue Hi = Op.getOperand(1);
5560 
5561   // Avoid adding defined bits with the zero_extend.
5562   if (Hi.isUndef()) {
5563     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5564     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5565     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5566   }
5567 
5568   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5569   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5570 
5571   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5572                               DAG.getConstant(16, SL, MVT::i32));
5573   if (Lo.isUndef())
5574     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5575 
5576   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5577   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5578 
5579   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5580   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5581 }
5582 
5583 bool
5584 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5585   // We can fold offsets for anything that doesn't require a GOT relocation.
5586   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5587           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5588           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5589          !shouldEmitGOTReloc(GA->getGlobal());
5590 }
5591 
5592 static SDValue
5593 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5594                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5595                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5596   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5597   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5598   // lowered to the following code sequence:
5599   //
5600   // For constant address space:
5601   //   s_getpc_b64 s[0:1]
5602   //   s_add_u32 s0, s0, $symbol
5603   //   s_addc_u32 s1, s1, 0
5604   //
5605   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5606   //   a fixup or relocation is emitted to replace $symbol with a literal
5607   //   constant, which is a pc-relative offset from the encoding of the $symbol
5608   //   operand to the global variable.
5609   //
5610   // For global address space:
5611   //   s_getpc_b64 s[0:1]
5612   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5613   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5614   //
5615   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5616   //   fixups or relocations are emitted to replace $symbol@*@lo and
5617   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5618   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5619   //   operand to the global variable.
5620   //
5621   // What we want here is an offset from the value returned by s_getpc
5622   // (which is the address of the s_add_u32 instruction) to the global
5623   // variable, but since the encoding of $symbol starts 4 bytes after the start
5624   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5625   // small. This requires us to add 4 to the global variable offset in order to
5626   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5627   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5628   // instruction.
5629   SDValue PtrLo =
5630       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5631   SDValue PtrHi;
5632   if (GAFlags == SIInstrInfo::MO_NONE) {
5633     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5634   } else {
5635     PtrHi =
5636         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5637   }
5638   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5639 }
5640 
5641 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5642                                              SDValue Op,
5643                                              SelectionDAG &DAG) const {
5644   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5645   SDLoc DL(GSD);
5646   EVT PtrVT = Op.getValueType();
5647 
5648   const GlobalValue *GV = GSD->getGlobal();
5649   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5650        shouldUseLDSConstAddress(GV)) ||
5651       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5652       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5653     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5654         GV->hasExternalLinkage()) {
5655       Type *Ty = GV->getValueType();
5656       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5657       // zero-sized type in other languages to declare the dynamic shared
5658       // memory which size is not known at the compile time. They will be
5659       // allocated by the runtime and placed directly after the static
5660       // allocated ones. They all share the same offset.
5661       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5662         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5663         // Adjust alignment for that dynamic shared memory array.
5664         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5665         return SDValue(
5666             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5667       }
5668     }
5669     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5670   }
5671 
5672   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5673     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5674                                             SIInstrInfo::MO_ABS32_LO);
5675     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5676   }
5677 
5678   if (shouldEmitFixup(GV))
5679     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5680   else if (shouldEmitPCReloc(GV))
5681     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5682                                    SIInstrInfo::MO_REL32);
5683 
5684   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5685                                             SIInstrInfo::MO_GOTPCREL32);
5686 
5687   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5688   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5689   const DataLayout &DataLayout = DAG.getDataLayout();
5690   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5691   MachinePointerInfo PtrInfo
5692     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5693 
5694   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5695                      MachineMemOperand::MODereferenceable |
5696                          MachineMemOperand::MOInvariant);
5697 }
5698 
5699 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5700                                    const SDLoc &DL, SDValue V) const {
5701   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5702   // the destination register.
5703   //
5704   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5705   // so we will end up with redundant moves to m0.
5706   //
5707   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5708 
5709   // A Null SDValue creates a glue result.
5710   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5711                                   V, Chain);
5712   return SDValue(M0, 0);
5713 }
5714 
5715 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5716                                                  SDValue Op,
5717                                                  MVT VT,
5718                                                  unsigned Offset) const {
5719   SDLoc SL(Op);
5720   SDValue Param = lowerKernargMemParameter(
5721       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5722   // The local size values will have the hi 16-bits as zero.
5723   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5724                      DAG.getValueType(VT));
5725 }
5726 
5727 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5728                                         EVT VT) {
5729   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5730                                       "non-hsa intrinsic with hsa target",
5731                                       DL.getDebugLoc());
5732   DAG.getContext()->diagnose(BadIntrin);
5733   return DAG.getUNDEF(VT);
5734 }
5735 
5736 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5737                                          EVT VT) {
5738   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5739                                       "intrinsic not supported on subtarget",
5740                                       DL.getDebugLoc());
5741   DAG.getContext()->diagnose(BadIntrin);
5742   return DAG.getUNDEF(VT);
5743 }
5744 
5745 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5746                                     ArrayRef<SDValue> Elts) {
5747   assert(!Elts.empty());
5748   MVT Type;
5749   unsigned NumElts;
5750 
5751   if (Elts.size() == 1) {
5752     Type = MVT::f32;
5753     NumElts = 1;
5754   } else if (Elts.size() == 2) {
5755     Type = MVT::v2f32;
5756     NumElts = 2;
5757   } else if (Elts.size() == 3) {
5758     Type = MVT::v3f32;
5759     NumElts = 3;
5760   } else if (Elts.size() <= 4) {
5761     Type = MVT::v4f32;
5762     NumElts = 4;
5763   } else if (Elts.size() <= 8) {
5764     Type = MVT::v8f32;
5765     NumElts = 8;
5766   } else {
5767     assert(Elts.size() <= 16);
5768     Type = MVT::v16f32;
5769     NumElts = 16;
5770   }
5771 
5772   SmallVector<SDValue, 16> VecElts(NumElts);
5773   for (unsigned i = 0; i < Elts.size(); ++i) {
5774     SDValue Elt = Elts[i];
5775     if (Elt.getValueType() != MVT::f32)
5776       Elt = DAG.getBitcast(MVT::f32, Elt);
5777     VecElts[i] = Elt;
5778   }
5779   for (unsigned i = Elts.size(); i < NumElts; ++i)
5780     VecElts[i] = DAG.getUNDEF(MVT::f32);
5781 
5782   if (NumElts == 1)
5783     return VecElts[0];
5784   return DAG.getBuildVector(Type, DL, VecElts);
5785 }
5786 
5787 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5788                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5789   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5790 
5791   uint64_t Value = CachePolicyConst->getZExtValue();
5792   SDLoc DL(CachePolicy);
5793   if (GLC) {
5794     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5795     Value &= ~(uint64_t)0x1;
5796   }
5797   if (SLC) {
5798     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5799     Value &= ~(uint64_t)0x2;
5800   }
5801   if (DLC) {
5802     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5803     Value &= ~(uint64_t)0x4;
5804   }
5805 
5806   return Value == 0;
5807 }
5808 
5809 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5810                               SDValue Src, int ExtraElts) {
5811   EVT SrcVT = Src.getValueType();
5812 
5813   SmallVector<SDValue, 8> Elts;
5814 
5815   if (SrcVT.isVector())
5816     DAG.ExtractVectorElements(Src, Elts);
5817   else
5818     Elts.push_back(Src);
5819 
5820   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5821   while (ExtraElts--)
5822     Elts.push_back(Undef);
5823 
5824   return DAG.getBuildVector(CastVT, DL, Elts);
5825 }
5826 
5827 // Re-construct the required return value for a image load intrinsic.
5828 // This is more complicated due to the optional use TexFailCtrl which means the required
5829 // return type is an aggregate
5830 static SDValue constructRetValue(SelectionDAG &DAG,
5831                                  MachineSDNode *Result,
5832                                  ArrayRef<EVT> ResultTypes,
5833                                  bool IsTexFail, bool Unpacked, bool IsD16,
5834                                  int DMaskPop, int NumVDataDwords,
5835                                  const SDLoc &DL, LLVMContext &Context) {
5836   // Determine the required return type. This is the same regardless of IsTexFail flag
5837   EVT ReqRetVT = ResultTypes[0];
5838   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5839   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5840     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5841 
5842   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5843     DMaskPop : (DMaskPop + 1) / 2;
5844 
5845   MVT DataDwordVT = NumDataDwords == 1 ?
5846     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5847 
5848   MVT MaskPopVT = MaskPopDwords == 1 ?
5849     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5850 
5851   SDValue Data(Result, 0);
5852   SDValue TexFail;
5853 
5854   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5855     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5856     if (MaskPopVT.isVector()) {
5857       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5858                          SDValue(Result, 0), ZeroIdx);
5859     } else {
5860       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5861                          SDValue(Result, 0), ZeroIdx);
5862     }
5863   }
5864 
5865   if (DataDwordVT.isVector())
5866     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5867                           NumDataDwords - MaskPopDwords);
5868 
5869   if (IsD16)
5870     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5871 
5872   EVT LegalReqRetVT = ReqRetVT;
5873   if (!ReqRetVT.isVector()) {
5874     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5875   } else {
5876     // We need to widen the return vector to a legal type
5877     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5878         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5879       LegalReqRetVT =
5880           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5881                            ReqRetVT.getVectorNumElements() + 1);
5882     }
5883   }
5884   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5885 
5886   if (IsTexFail) {
5887     TexFail =
5888         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5889                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5890 
5891     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5892   }
5893 
5894   if (Result->getNumValues() == 1)
5895     return Data;
5896 
5897   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5898 }
5899 
5900 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5901                          SDValue *LWE, bool &IsTexFail) {
5902   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5903 
5904   uint64_t Value = TexFailCtrlConst->getZExtValue();
5905   if (Value) {
5906     IsTexFail = true;
5907   }
5908 
5909   SDLoc DL(TexFailCtrlConst);
5910   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5911   Value &= ~(uint64_t)0x1;
5912   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5913   Value &= ~(uint64_t)0x2;
5914 
5915   return Value == 0;
5916 }
5917 
5918 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5919                                         MVT PackVectorVT,
5920                                         SmallVectorImpl<SDValue> &PackedAddrs,
5921                                         unsigned DimIdx, unsigned EndIdx,
5922                                         unsigned NumGradients) {
5923   SDLoc DL(Op);
5924   for (unsigned I = DimIdx; I < EndIdx; I++) {
5925     SDValue Addr = Op.getOperand(I);
5926 
5927     // Gradients are packed with undef for each coordinate.
5928     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5929     // 1D: undef,dx/dh; undef,dx/dv
5930     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5931     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5932     if (((I + 1) >= EndIdx) ||
5933         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5934                                          I == DimIdx + NumGradients - 1))) {
5935       if (Addr.getValueType() != MVT::i16)
5936         Addr = DAG.getBitcast(MVT::i16, Addr);
5937       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5938     } else {
5939       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5940       I++;
5941     }
5942     Addr = DAG.getBitcast(MVT::f32, Addr);
5943     PackedAddrs.push_back(Addr);
5944   }
5945 }
5946 
5947 SDValue SITargetLowering::lowerImage(SDValue Op,
5948                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5949                                      SelectionDAG &DAG, bool WithChain) const {
5950   SDLoc DL(Op);
5951   MachineFunction &MF = DAG.getMachineFunction();
5952   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5953   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5954       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5955   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5956   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5957       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5958   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5959       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5960   unsigned IntrOpcode = Intr->BaseOpcode;
5961   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5962 
5963   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5964   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5965   bool IsD16 = false;
5966   bool IsG16 = false;
5967   bool IsA16 = false;
5968   SDValue VData;
5969   int NumVDataDwords;
5970   bool AdjustRetType = false;
5971 
5972   // Offset of intrinsic arguments
5973   const unsigned ArgOffset = WithChain ? 2 : 1;
5974 
5975   unsigned DMask;
5976   unsigned DMaskLanes = 0;
5977 
5978   if (BaseOpcode->Atomic) {
5979     VData = Op.getOperand(2);
5980 
5981     bool Is64Bit = VData.getValueType() == MVT::i64;
5982     if (BaseOpcode->AtomicX2) {
5983       SDValue VData2 = Op.getOperand(3);
5984       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5985                                  {VData, VData2});
5986       if (Is64Bit)
5987         VData = DAG.getBitcast(MVT::v4i32, VData);
5988 
5989       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5990       DMask = Is64Bit ? 0xf : 0x3;
5991       NumVDataDwords = Is64Bit ? 4 : 2;
5992     } else {
5993       DMask = Is64Bit ? 0x3 : 0x1;
5994       NumVDataDwords = Is64Bit ? 2 : 1;
5995     }
5996   } else {
5997     auto *DMaskConst =
5998         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
5999     DMask = DMaskConst->getZExtValue();
6000     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6001 
6002     if (BaseOpcode->Store) {
6003       VData = Op.getOperand(2);
6004 
6005       MVT StoreVT = VData.getSimpleValueType();
6006       if (StoreVT.getScalarType() == MVT::f16) {
6007         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6008           return Op; // D16 is unsupported for this instruction
6009 
6010         IsD16 = true;
6011         VData = handleD16VData(VData, DAG, true);
6012       }
6013 
6014       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6015     } else {
6016       // Work out the num dwords based on the dmask popcount and underlying type
6017       // and whether packing is supported.
6018       MVT LoadVT = ResultTypes[0].getSimpleVT();
6019       if (LoadVT.getScalarType() == MVT::f16) {
6020         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6021           return Op; // D16 is unsupported for this instruction
6022 
6023         IsD16 = true;
6024       }
6025 
6026       // Confirm that the return type is large enough for the dmask specified
6027       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6028           (!LoadVT.isVector() && DMaskLanes > 1))
6029           return Op;
6030 
6031       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6032       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6033       // instructions.
6034       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6035           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6036         NumVDataDwords = (DMaskLanes + 1) / 2;
6037       else
6038         NumVDataDwords = DMaskLanes;
6039 
6040       AdjustRetType = true;
6041     }
6042   }
6043 
6044   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6045   SmallVector<SDValue, 4> VAddrs;
6046 
6047   // Optimize _L to _LZ when _L is zero
6048   if (LZMappingInfo) {
6049     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6050             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6051       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6052         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6053         VAddrEnd--;                      // remove 'lod'
6054       }
6055     }
6056   }
6057 
6058   // Optimize _mip away, when 'lod' is zero
6059   if (MIPMappingInfo) {
6060     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6061             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6062       if (ConstantLod->isNullValue()) {
6063         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6064         VAddrEnd--;                           // remove 'mip'
6065       }
6066     }
6067   }
6068 
6069   // Push back extra arguments.
6070   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6071     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6072 
6073   // Check for 16 bit addresses or derivatives and pack if true.
6074   MVT VAddrVT =
6075       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6076   MVT VAddrScalarVT = VAddrVT.getScalarType();
6077   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6078   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6079 
6080   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6081   VAddrScalarVT = VAddrVT.getScalarType();
6082   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6083   if (IsA16 || IsG16) {
6084     if (IsA16) {
6085       if (!ST->hasA16()) {
6086         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6087                              "support 16 bit addresses\n");
6088         return Op;
6089       }
6090       if (!IsG16) {
6091         LLVM_DEBUG(
6092             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6093                       "need 16 bit derivatives but got 32 bit derivatives\n");
6094         return Op;
6095       }
6096     } else if (!ST->hasG16()) {
6097       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6098                            "support 16 bit derivatives\n");
6099       return Op;
6100     }
6101 
6102     if (BaseOpcode->Gradients && !IsA16) {
6103       if (!ST->hasG16()) {
6104         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6105                              "support 16 bit derivatives\n");
6106         return Op;
6107       }
6108       // Activate g16
6109       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6110           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6111       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6112     }
6113 
6114     // Don't compress addresses for G16
6115     const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6116     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs,
6117                                 ArgOffset + Intr->GradientStart, PackEndIdx,
6118                                 Intr->NumGradients);
6119 
6120     if (!IsA16) {
6121       // Add uncompressed address
6122       for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6123         VAddrs.push_back(Op.getOperand(I));
6124     }
6125   } else {
6126     for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++)
6127       VAddrs.push_back(Op.getOperand(I));
6128   }
6129 
6130   // If the register allocator cannot place the address registers contiguously
6131   // without introducing moves, then using the non-sequential address encoding
6132   // is always preferable, since it saves VALU instructions and is usually a
6133   // wash in terms of code size or even better.
6134   //
6135   // However, we currently have no way of hinting to the register allocator that
6136   // MIMG addresses should be placed contiguously when it is possible to do so,
6137   // so force non-NSA for the common 2-address case as a heuristic.
6138   //
6139   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6140   // allocation when possible.
6141   bool UseNSA =
6142       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6143   SDValue VAddr;
6144   if (!UseNSA)
6145     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6146 
6147   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6148   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6149   SDValue Unorm;
6150   if (!BaseOpcode->Sampler) {
6151     Unorm = True;
6152   } else {
6153     auto UnormConst =
6154         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6155 
6156     Unorm = UnormConst->getZExtValue() ? True : False;
6157   }
6158 
6159   SDValue TFE;
6160   SDValue LWE;
6161   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6162   bool IsTexFail = false;
6163   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6164     return Op;
6165 
6166   if (IsTexFail) {
6167     if (!DMaskLanes) {
6168       // Expecting to get an error flag since TFC is on - and dmask is 0
6169       // Force dmask to be at least 1 otherwise the instruction will fail
6170       DMask = 0x1;
6171       DMaskLanes = 1;
6172       NumVDataDwords = 1;
6173     }
6174     NumVDataDwords += 1;
6175     AdjustRetType = true;
6176   }
6177 
6178   // Has something earlier tagged that the return type needs adjusting
6179   // This happens if the instruction is a load or has set TexFailCtrl flags
6180   if (AdjustRetType) {
6181     // NumVDataDwords reflects the true number of dwords required in the return type
6182     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6183       // This is a no-op load. This can be eliminated
6184       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6185       if (isa<MemSDNode>(Op))
6186         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6187       return Undef;
6188     }
6189 
6190     EVT NewVT = NumVDataDwords > 1 ?
6191                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6192                 : MVT::i32;
6193 
6194     ResultTypes[0] = NewVT;
6195     if (ResultTypes.size() == 3) {
6196       // Original result was aggregate type used for TexFailCtrl results
6197       // The actual instruction returns as a vector type which has now been
6198       // created. Remove the aggregate result.
6199       ResultTypes.erase(&ResultTypes[1]);
6200     }
6201   }
6202 
6203   SDValue GLC;
6204   SDValue SLC;
6205   SDValue DLC;
6206   if (BaseOpcode->Atomic) {
6207     GLC = True; // TODO no-return optimization
6208     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6209                           DAG, nullptr, &SLC, IsGFX10 ? &DLC : nullptr))
6210       return Op;
6211   } else {
6212     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6213                           DAG, &GLC, &SLC, IsGFX10 ? &DLC : nullptr))
6214       return Op;
6215   }
6216 
6217   SmallVector<SDValue, 26> Ops;
6218   if (BaseOpcode->Store || BaseOpcode->Atomic)
6219     Ops.push_back(VData); // vdata
6220   if (UseNSA) {
6221     for (const SDValue &Addr : VAddrs)
6222       Ops.push_back(Addr);
6223   } else {
6224     Ops.push_back(VAddr);
6225   }
6226   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6227   if (BaseOpcode->Sampler)
6228     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6229   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6230   if (IsGFX10)
6231     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6232   Ops.push_back(Unorm);
6233   if (IsGFX10)
6234     Ops.push_back(DLC);
6235   Ops.push_back(GLC);
6236   Ops.push_back(SLC);
6237   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6238                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6239   if (IsGFX10)
6240     Ops.push_back(IsA16 ? True : False);
6241   Ops.push_back(TFE);
6242   Ops.push_back(LWE);
6243   if (!IsGFX10)
6244     Ops.push_back(DimInfo->DA ? True : False);
6245   if (BaseOpcode->HasD16)
6246     Ops.push_back(IsD16 ? True : False);
6247   if (isa<MemSDNode>(Op))
6248     Ops.push_back(Op.getOperand(0)); // chain
6249 
6250   int NumVAddrDwords =
6251       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6252   int Opcode = -1;
6253 
6254   if (IsGFX10) {
6255     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6256                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6257                                           : AMDGPU::MIMGEncGfx10Default,
6258                                    NumVDataDwords, NumVAddrDwords);
6259   } else {
6260     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6261       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6262                                      NumVDataDwords, NumVAddrDwords);
6263     if (Opcode == -1)
6264       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6265                                      NumVDataDwords, NumVAddrDwords);
6266   }
6267   assert(Opcode != -1);
6268 
6269   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6270   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6271     MachineMemOperand *MemRef = MemOp->getMemOperand();
6272     DAG.setNodeMemRefs(NewNode, {MemRef});
6273   }
6274 
6275   if (BaseOpcode->AtomicX2) {
6276     SmallVector<SDValue, 1> Elt;
6277     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6278     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6279   } else if (!BaseOpcode->Store) {
6280     return constructRetValue(DAG, NewNode,
6281                              OrigResultTypes, IsTexFail,
6282                              Subtarget->hasUnpackedD16VMem(), IsD16,
6283                              DMaskLanes, NumVDataDwords, DL,
6284                              *DAG.getContext());
6285   }
6286 
6287   return SDValue(NewNode, 0);
6288 }
6289 
6290 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6291                                        SDValue Offset, SDValue CachePolicy,
6292                                        SelectionDAG &DAG) const {
6293   MachineFunction &MF = DAG.getMachineFunction();
6294 
6295   const DataLayout &DataLayout = DAG.getDataLayout();
6296   Align Alignment =
6297       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6298 
6299   MachineMemOperand *MMO = MF.getMachineMemOperand(
6300       MachinePointerInfo(),
6301       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6302           MachineMemOperand::MOInvariant,
6303       VT.getStoreSize(), Alignment);
6304 
6305   if (!Offset->isDivergent()) {
6306     SDValue Ops[] = {
6307         Rsrc,
6308         Offset, // Offset
6309         CachePolicy
6310     };
6311 
6312     // Widen vec3 load to vec4.
6313     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6314       EVT WidenedVT =
6315           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6316       auto WidenedOp = DAG.getMemIntrinsicNode(
6317           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6318           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6319       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6320                                    DAG.getVectorIdxConstant(0, DL));
6321       return Subvector;
6322     }
6323 
6324     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6325                                    DAG.getVTList(VT), Ops, VT, MMO);
6326   }
6327 
6328   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6329   // assume that the buffer is unswizzled.
6330   SmallVector<SDValue, 4> Loads;
6331   unsigned NumLoads = 1;
6332   MVT LoadVT = VT.getSimpleVT();
6333   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6334   assert((LoadVT.getScalarType() == MVT::i32 ||
6335           LoadVT.getScalarType() == MVT::f32));
6336 
6337   if (NumElts == 8 || NumElts == 16) {
6338     NumLoads = NumElts / 4;
6339     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6340   }
6341 
6342   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6343   SDValue Ops[] = {
6344       DAG.getEntryNode(),                               // Chain
6345       Rsrc,                                             // rsrc
6346       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6347       {},                                               // voffset
6348       {},                                               // soffset
6349       {},                                               // offset
6350       CachePolicy,                                      // cachepolicy
6351       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6352   };
6353 
6354   // Use the alignment to ensure that the required offsets will fit into the
6355   // immediate offsets.
6356   setBufferOffsets(Offset, DAG, &Ops[3],
6357                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6358 
6359   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6360   for (unsigned i = 0; i < NumLoads; ++i) {
6361     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6362     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6363                                         LoadVT, MMO, DAG));
6364   }
6365 
6366   if (NumElts == 8 || NumElts == 16)
6367     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6368 
6369   return Loads[0];
6370 }
6371 
6372 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6373                                                   SelectionDAG &DAG) const {
6374   MachineFunction &MF = DAG.getMachineFunction();
6375   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6376 
6377   EVT VT = Op.getValueType();
6378   SDLoc DL(Op);
6379   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6380 
6381   // TODO: Should this propagate fast-math-flags?
6382 
6383   switch (IntrinsicID) {
6384   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6385     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6386       return emitNonHSAIntrinsicError(DAG, DL, VT);
6387     return getPreloadedValue(DAG, *MFI, VT,
6388                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6389   }
6390   case Intrinsic::amdgcn_dispatch_ptr:
6391   case Intrinsic::amdgcn_queue_ptr: {
6392     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6393       DiagnosticInfoUnsupported BadIntrin(
6394           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6395           DL.getDebugLoc());
6396       DAG.getContext()->diagnose(BadIntrin);
6397       return DAG.getUNDEF(VT);
6398     }
6399 
6400     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6401       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6402     return getPreloadedValue(DAG, *MFI, VT, RegID);
6403   }
6404   case Intrinsic::amdgcn_implicitarg_ptr: {
6405     if (MFI->isEntryFunction())
6406       return getImplicitArgPtr(DAG, DL);
6407     return getPreloadedValue(DAG, *MFI, VT,
6408                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6409   }
6410   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6411     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6412       // This only makes sense to call in a kernel, so just lower to null.
6413       return DAG.getConstant(0, DL, VT);
6414     }
6415 
6416     return getPreloadedValue(DAG, *MFI, VT,
6417                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6418   }
6419   case Intrinsic::amdgcn_dispatch_id: {
6420     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6421   }
6422   case Intrinsic::amdgcn_rcp:
6423     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6424   case Intrinsic::amdgcn_rsq:
6425     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6426   case Intrinsic::amdgcn_rsq_legacy:
6427     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6428       return emitRemovedIntrinsicError(DAG, DL, VT);
6429     return SDValue();
6430   case Intrinsic::amdgcn_rcp_legacy:
6431     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6432       return emitRemovedIntrinsicError(DAG, DL, VT);
6433     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6434   case Intrinsic::amdgcn_rsq_clamp: {
6435     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6436       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6437 
6438     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6439     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6440     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6441 
6442     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6443     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6444                               DAG.getConstantFP(Max, DL, VT));
6445     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6446                        DAG.getConstantFP(Min, DL, VT));
6447   }
6448   case Intrinsic::r600_read_ngroups_x:
6449     if (Subtarget->isAmdHsaOS())
6450       return emitNonHSAIntrinsicError(DAG, DL, VT);
6451 
6452     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6453                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6454                                     false);
6455   case Intrinsic::r600_read_ngroups_y:
6456     if (Subtarget->isAmdHsaOS())
6457       return emitNonHSAIntrinsicError(DAG, DL, VT);
6458 
6459     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6460                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6461                                     false);
6462   case Intrinsic::r600_read_ngroups_z:
6463     if (Subtarget->isAmdHsaOS())
6464       return emitNonHSAIntrinsicError(DAG, DL, VT);
6465 
6466     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6467                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6468                                     false);
6469   case Intrinsic::r600_read_global_size_x:
6470     if (Subtarget->isAmdHsaOS())
6471       return emitNonHSAIntrinsicError(DAG, DL, VT);
6472 
6473     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6474                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6475                                     Align(4), false);
6476   case Intrinsic::r600_read_global_size_y:
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_Y,
6482                                     Align(4), false);
6483   case Intrinsic::r600_read_global_size_z:
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_Z,
6489                                     Align(4), false);
6490   case Intrinsic::r600_read_local_size_x:
6491     if (Subtarget->isAmdHsaOS())
6492       return emitNonHSAIntrinsicError(DAG, DL, VT);
6493 
6494     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6495                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6496   case Intrinsic::r600_read_local_size_y:
6497     if (Subtarget->isAmdHsaOS())
6498       return emitNonHSAIntrinsicError(DAG, DL, VT);
6499 
6500     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6501                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6502   case Intrinsic::r600_read_local_size_z:
6503     if (Subtarget->isAmdHsaOS())
6504       return emitNonHSAIntrinsicError(DAG, DL, VT);
6505 
6506     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6507                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6508   case Intrinsic::amdgcn_workgroup_id_x:
6509     return getPreloadedValue(DAG, *MFI, VT,
6510                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6511   case Intrinsic::amdgcn_workgroup_id_y:
6512     return getPreloadedValue(DAG, *MFI, VT,
6513                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6514   case Intrinsic::amdgcn_workgroup_id_z:
6515     return getPreloadedValue(DAG, *MFI, VT,
6516                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6517   case Intrinsic::amdgcn_workitem_id_x:
6518     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6519                           SDLoc(DAG.getEntryNode()),
6520                           MFI->getArgInfo().WorkItemIDX);
6521   case Intrinsic::amdgcn_workitem_id_y:
6522     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6523                           SDLoc(DAG.getEntryNode()),
6524                           MFI->getArgInfo().WorkItemIDY);
6525   case Intrinsic::amdgcn_workitem_id_z:
6526     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6527                           SDLoc(DAG.getEntryNode()),
6528                           MFI->getArgInfo().WorkItemIDZ);
6529   case Intrinsic::amdgcn_wavefrontsize:
6530     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6531                            SDLoc(Op), MVT::i32);
6532   case Intrinsic::amdgcn_s_buffer_load: {
6533     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6534     SDValue GLC;
6535     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6536     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6537                           IsGFX10 ? &DLC : nullptr))
6538       return Op;
6539     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6540                         DAG);
6541   }
6542   case Intrinsic::amdgcn_fdiv_fast:
6543     return lowerFDIV_FAST(Op, DAG);
6544   case Intrinsic::amdgcn_sin:
6545     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6546 
6547   case Intrinsic::amdgcn_cos:
6548     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6549 
6550   case Intrinsic::amdgcn_mul_u24:
6551     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6552   case Intrinsic::amdgcn_mul_i24:
6553     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6554 
6555   case Intrinsic::amdgcn_log_clamp: {
6556     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6557       return SDValue();
6558 
6559     DiagnosticInfoUnsupported BadIntrin(
6560       MF.getFunction(), "intrinsic not supported on subtarget",
6561       DL.getDebugLoc());
6562       DAG.getContext()->diagnose(BadIntrin);
6563       return DAG.getUNDEF(VT);
6564   }
6565   case Intrinsic::amdgcn_ldexp:
6566     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6567                        Op.getOperand(1), Op.getOperand(2));
6568 
6569   case Intrinsic::amdgcn_fract:
6570     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6571 
6572   case Intrinsic::amdgcn_class:
6573     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6574                        Op.getOperand(1), Op.getOperand(2));
6575   case Intrinsic::amdgcn_div_fmas:
6576     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6577                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6578                        Op.getOperand(4));
6579 
6580   case Intrinsic::amdgcn_div_fixup:
6581     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6582                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6583 
6584   case Intrinsic::amdgcn_div_scale: {
6585     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6586 
6587     // Translate to the operands expected by the machine instruction. The
6588     // first parameter must be the same as the first instruction.
6589     SDValue Numerator = Op.getOperand(1);
6590     SDValue Denominator = Op.getOperand(2);
6591 
6592     // Note this order is opposite of the machine instruction's operations,
6593     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6594     // intrinsic has the numerator as the first operand to match a normal
6595     // division operation.
6596 
6597     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6598 
6599     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6600                        Denominator, Numerator);
6601   }
6602   case Intrinsic::amdgcn_icmp: {
6603     // There is a Pat that handles this variant, so return it as-is.
6604     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6605         Op.getConstantOperandVal(2) == 0 &&
6606         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6607       return Op;
6608     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6609   }
6610   case Intrinsic::amdgcn_fcmp: {
6611     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6612   }
6613   case Intrinsic::amdgcn_ballot:
6614     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6615   case Intrinsic::amdgcn_fmed3:
6616     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6617                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6618   case Intrinsic::amdgcn_fdot2:
6619     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6620                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6621                        Op.getOperand(4));
6622   case Intrinsic::amdgcn_fmul_legacy:
6623     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6624                        Op.getOperand(1), Op.getOperand(2));
6625   case Intrinsic::amdgcn_sffbh:
6626     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6627   case Intrinsic::amdgcn_sbfe:
6628     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6629                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6630   case Intrinsic::amdgcn_ubfe:
6631     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6632                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6633   case Intrinsic::amdgcn_cvt_pkrtz:
6634   case Intrinsic::amdgcn_cvt_pknorm_i16:
6635   case Intrinsic::amdgcn_cvt_pknorm_u16:
6636   case Intrinsic::amdgcn_cvt_pk_i16:
6637   case Intrinsic::amdgcn_cvt_pk_u16: {
6638     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6639     EVT VT = Op.getValueType();
6640     unsigned Opcode;
6641 
6642     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6643       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6644     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6645       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6646     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6647       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6648     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6649       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6650     else
6651       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6652 
6653     if (isTypeLegal(VT))
6654       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6655 
6656     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6657                                Op.getOperand(1), Op.getOperand(2));
6658     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6659   }
6660   case Intrinsic::amdgcn_fmad_ftz:
6661     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6662                        Op.getOperand(2), Op.getOperand(3));
6663 
6664   case Intrinsic::amdgcn_if_break:
6665     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6666                                       Op->getOperand(1), Op->getOperand(2)), 0);
6667 
6668   case Intrinsic::amdgcn_groupstaticsize: {
6669     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6670     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6671       return Op;
6672 
6673     const Module *M = MF.getFunction().getParent();
6674     const GlobalValue *GV =
6675         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6676     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6677                                             SIInstrInfo::MO_ABS32_LO);
6678     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6679   }
6680   case Intrinsic::amdgcn_is_shared:
6681   case Intrinsic::amdgcn_is_private: {
6682     SDLoc SL(Op);
6683     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6684       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6685     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6686     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6687                                  Op.getOperand(1));
6688 
6689     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6690                                 DAG.getConstant(1, SL, MVT::i32));
6691     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6692   }
6693   case Intrinsic::amdgcn_alignbit:
6694     return DAG.getNode(ISD::FSHR, DL, VT,
6695                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6696   case Intrinsic::amdgcn_reloc_constant: {
6697     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6698     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6699     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6700     auto RelocSymbol = cast<GlobalVariable>(
6701         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6702     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6703                                             SIInstrInfo::MO_ABS32_LO);
6704     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6705   }
6706   default:
6707     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6708             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6709       return lowerImage(Op, ImageDimIntr, DAG, false);
6710 
6711     return Op;
6712   }
6713 }
6714 
6715 // This function computes an appropriate offset to pass to
6716 // MachineMemOperand::setOffset() based on the offset inputs to
6717 // an intrinsic.  If any of the offsets are non-contstant or
6718 // if VIndex is non-zero then this function returns 0.  Otherwise,
6719 // it returns the sum of VOffset, SOffset, and Offset.
6720 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6721                                       SDValue SOffset,
6722                                       SDValue Offset,
6723                                       SDValue VIndex = SDValue()) {
6724 
6725   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6726       !isa<ConstantSDNode>(Offset))
6727     return 0;
6728 
6729   if (VIndex) {
6730     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6731       return 0;
6732   }
6733 
6734   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6735          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6736          cast<ConstantSDNode>(Offset)->getSExtValue();
6737 }
6738 
6739 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6740                                                      SelectionDAG &DAG,
6741                                                      unsigned NewOpcode) const {
6742   SDLoc DL(Op);
6743 
6744   SDValue VData = Op.getOperand(2);
6745   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6746   SDValue Ops[] = {
6747     Op.getOperand(0), // Chain
6748     VData,            // vdata
6749     Op.getOperand(3), // rsrc
6750     DAG.getConstant(0, DL, MVT::i32), // vindex
6751     Offsets.first,    // voffset
6752     Op.getOperand(5), // soffset
6753     Offsets.second,   // offset
6754     Op.getOperand(6), // cachepolicy
6755     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6756   };
6757 
6758   auto *M = cast<MemSDNode>(Op);
6759   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6760 
6761   EVT MemVT = VData.getValueType();
6762   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6763                                  M->getMemOperand());
6764 }
6765 
6766 SDValue
6767 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6768                                                 unsigned NewOpcode) const {
6769   SDLoc DL(Op);
6770 
6771   SDValue VData = Op.getOperand(2);
6772   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6773   SDValue Ops[] = {
6774     Op.getOperand(0), // Chain
6775     VData,            // vdata
6776     Op.getOperand(3), // rsrc
6777     Op.getOperand(4), // vindex
6778     Offsets.first,    // voffset
6779     Op.getOperand(6), // soffset
6780     Offsets.second,   // offset
6781     Op.getOperand(7), // cachepolicy
6782     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6783   };
6784 
6785   auto *M = cast<MemSDNode>(Op);
6786   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6787                                                       Ops[3]));
6788 
6789   EVT MemVT = VData.getValueType();
6790   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6791                                  M->getMemOperand());
6792 }
6793 
6794 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6795                                                  SelectionDAG &DAG) const {
6796   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6797   SDLoc DL(Op);
6798 
6799   switch (IntrID) {
6800   case Intrinsic::amdgcn_ds_ordered_add:
6801   case Intrinsic::amdgcn_ds_ordered_swap: {
6802     MemSDNode *M = cast<MemSDNode>(Op);
6803     SDValue Chain = M->getOperand(0);
6804     SDValue M0 = M->getOperand(2);
6805     SDValue Value = M->getOperand(3);
6806     unsigned IndexOperand = M->getConstantOperandVal(7);
6807     unsigned WaveRelease = M->getConstantOperandVal(8);
6808     unsigned WaveDone = M->getConstantOperandVal(9);
6809 
6810     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6811     IndexOperand &= ~0x3f;
6812     unsigned CountDw = 0;
6813 
6814     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6815       CountDw = (IndexOperand >> 24) & 0xf;
6816       IndexOperand &= ~(0xf << 24);
6817 
6818       if (CountDw < 1 || CountDw > 4) {
6819         report_fatal_error(
6820             "ds_ordered_count: dword count must be between 1 and 4");
6821       }
6822     }
6823 
6824     if (IndexOperand)
6825       report_fatal_error("ds_ordered_count: bad index operand");
6826 
6827     if (WaveDone && !WaveRelease)
6828       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6829 
6830     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6831     unsigned ShaderType =
6832         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6833     unsigned Offset0 = OrderedCountIndex << 2;
6834     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6835                        (Instruction << 4);
6836 
6837     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6838       Offset1 |= (CountDw - 1) << 6;
6839 
6840     unsigned Offset = Offset0 | (Offset1 << 8);
6841 
6842     SDValue Ops[] = {
6843       Chain,
6844       Value,
6845       DAG.getTargetConstant(Offset, DL, MVT::i16),
6846       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6847     };
6848     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6849                                    M->getVTList(), Ops, M->getMemoryVT(),
6850                                    M->getMemOperand());
6851   }
6852   case Intrinsic::amdgcn_ds_fadd: {
6853     MemSDNode *M = cast<MemSDNode>(Op);
6854     unsigned Opc;
6855     switch (IntrID) {
6856     case Intrinsic::amdgcn_ds_fadd:
6857       Opc = ISD::ATOMIC_LOAD_FADD;
6858       break;
6859     }
6860 
6861     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6862                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6863                          M->getMemOperand());
6864   }
6865   case Intrinsic::amdgcn_atomic_inc:
6866   case Intrinsic::amdgcn_atomic_dec:
6867   case Intrinsic::amdgcn_ds_fmin:
6868   case Intrinsic::amdgcn_ds_fmax: {
6869     MemSDNode *M = cast<MemSDNode>(Op);
6870     unsigned Opc;
6871     switch (IntrID) {
6872     case Intrinsic::amdgcn_atomic_inc:
6873       Opc = AMDGPUISD::ATOMIC_INC;
6874       break;
6875     case Intrinsic::amdgcn_atomic_dec:
6876       Opc = AMDGPUISD::ATOMIC_DEC;
6877       break;
6878     case Intrinsic::amdgcn_ds_fmin:
6879       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6880       break;
6881     case Intrinsic::amdgcn_ds_fmax:
6882       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6883       break;
6884     default:
6885       llvm_unreachable("Unknown intrinsic!");
6886     }
6887     SDValue Ops[] = {
6888       M->getOperand(0), // Chain
6889       M->getOperand(2), // Ptr
6890       M->getOperand(3)  // Value
6891     };
6892 
6893     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6894                                    M->getMemoryVT(), M->getMemOperand());
6895   }
6896   case Intrinsic::amdgcn_buffer_load:
6897   case Intrinsic::amdgcn_buffer_load_format: {
6898     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6899     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6900     unsigned IdxEn = 1;
6901     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6902       IdxEn = Idx->getZExtValue() != 0;
6903     SDValue Ops[] = {
6904       Op.getOperand(0), // Chain
6905       Op.getOperand(2), // rsrc
6906       Op.getOperand(3), // vindex
6907       SDValue(),        // voffset -- will be set by setBufferOffsets
6908       SDValue(),        // soffset -- will be set by setBufferOffsets
6909       SDValue(),        // offset -- will be set by setBufferOffsets
6910       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6911       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6912     };
6913 
6914     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6915     // We don't know the offset if vindex is non-zero, so clear it.
6916     if (IdxEn)
6917       Offset = 0;
6918 
6919     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6920         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6921 
6922     EVT VT = Op.getValueType();
6923     EVT IntVT = VT.changeTypeToInteger();
6924     auto *M = cast<MemSDNode>(Op);
6925     M->getMemOperand()->setOffset(Offset);
6926     EVT LoadVT = Op.getValueType();
6927 
6928     if (LoadVT.getScalarType() == MVT::f16)
6929       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6930                                  M, DAG, Ops);
6931 
6932     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6933     if (LoadVT.getScalarType() == MVT::i8 ||
6934         LoadVT.getScalarType() == MVT::i16)
6935       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6936 
6937     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6938                                M->getMemOperand(), DAG);
6939   }
6940   case Intrinsic::amdgcn_raw_buffer_load:
6941   case Intrinsic::amdgcn_raw_buffer_load_format: {
6942     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6943 
6944     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6945     SDValue Ops[] = {
6946       Op.getOperand(0), // Chain
6947       Op.getOperand(2), // rsrc
6948       DAG.getConstant(0, DL, MVT::i32), // vindex
6949       Offsets.first,    // voffset
6950       Op.getOperand(4), // soffset
6951       Offsets.second,   // offset
6952       Op.getOperand(5), // cachepolicy, swizzled buffer
6953       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6954     };
6955 
6956     auto *M = cast<MemSDNode>(Op);
6957     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6958     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6959   }
6960   case Intrinsic::amdgcn_struct_buffer_load:
6961   case Intrinsic::amdgcn_struct_buffer_load_format: {
6962     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6963 
6964     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6965     SDValue Ops[] = {
6966       Op.getOperand(0), // Chain
6967       Op.getOperand(2), // rsrc
6968       Op.getOperand(3), // vindex
6969       Offsets.first,    // voffset
6970       Op.getOperand(5), // soffset
6971       Offsets.second,   // offset
6972       Op.getOperand(6), // cachepolicy, swizzled buffer
6973       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6974     };
6975 
6976     auto *M = cast<MemSDNode>(Op);
6977     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6978                                                         Ops[2]));
6979     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6980   }
6981   case Intrinsic::amdgcn_tbuffer_load: {
6982     MemSDNode *M = cast<MemSDNode>(Op);
6983     EVT LoadVT = Op.getValueType();
6984 
6985     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6986     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6987     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6988     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6989     unsigned IdxEn = 1;
6990     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6991       IdxEn = Idx->getZExtValue() != 0;
6992     SDValue Ops[] = {
6993       Op.getOperand(0),  // Chain
6994       Op.getOperand(2),  // rsrc
6995       Op.getOperand(3),  // vindex
6996       Op.getOperand(4),  // voffset
6997       Op.getOperand(5),  // soffset
6998       Op.getOperand(6),  // offset
6999       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7000       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7001       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7002     };
7003 
7004     if (LoadVT.getScalarType() == MVT::f16)
7005       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7006                                  M, DAG, Ops);
7007     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7008                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7009                                DAG);
7010   }
7011   case Intrinsic::amdgcn_raw_tbuffer_load: {
7012     MemSDNode *M = cast<MemSDNode>(Op);
7013     EVT LoadVT = Op.getValueType();
7014     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7015 
7016     SDValue Ops[] = {
7017       Op.getOperand(0),  // Chain
7018       Op.getOperand(2),  // rsrc
7019       DAG.getConstant(0, DL, MVT::i32), // vindex
7020       Offsets.first,     // voffset
7021       Op.getOperand(4),  // soffset
7022       Offsets.second,    // offset
7023       Op.getOperand(5),  // format
7024       Op.getOperand(6),  // cachepolicy, swizzled buffer
7025       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7026     };
7027 
7028     if (LoadVT.getScalarType() == MVT::f16)
7029       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7030                                  M, DAG, Ops);
7031     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7032                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7033                                DAG);
7034   }
7035   case Intrinsic::amdgcn_struct_tbuffer_load: {
7036     MemSDNode *M = cast<MemSDNode>(Op);
7037     EVT LoadVT = Op.getValueType();
7038     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7039 
7040     SDValue Ops[] = {
7041       Op.getOperand(0),  // Chain
7042       Op.getOperand(2),  // rsrc
7043       Op.getOperand(3),  // vindex
7044       Offsets.first,     // voffset
7045       Op.getOperand(5),  // soffset
7046       Offsets.second,    // offset
7047       Op.getOperand(6),  // format
7048       Op.getOperand(7),  // cachepolicy, swizzled buffer
7049       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7050     };
7051 
7052     if (LoadVT.getScalarType() == MVT::f16)
7053       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7054                                  M, DAG, Ops);
7055     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7056                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7057                                DAG);
7058   }
7059   case Intrinsic::amdgcn_buffer_atomic_swap:
7060   case Intrinsic::amdgcn_buffer_atomic_add:
7061   case Intrinsic::amdgcn_buffer_atomic_sub:
7062   case Intrinsic::amdgcn_buffer_atomic_csub:
7063   case Intrinsic::amdgcn_buffer_atomic_smin:
7064   case Intrinsic::amdgcn_buffer_atomic_umin:
7065   case Intrinsic::amdgcn_buffer_atomic_smax:
7066   case Intrinsic::amdgcn_buffer_atomic_umax:
7067   case Intrinsic::amdgcn_buffer_atomic_and:
7068   case Intrinsic::amdgcn_buffer_atomic_or:
7069   case Intrinsic::amdgcn_buffer_atomic_xor:
7070   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7071     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7072     unsigned IdxEn = 1;
7073     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7074       IdxEn = Idx->getZExtValue() != 0;
7075     SDValue Ops[] = {
7076       Op.getOperand(0), // Chain
7077       Op.getOperand(2), // vdata
7078       Op.getOperand(3), // rsrc
7079       Op.getOperand(4), // vindex
7080       SDValue(),        // voffset -- will be set by setBufferOffsets
7081       SDValue(),        // soffset -- will be set by setBufferOffsets
7082       SDValue(),        // offset -- will be set by setBufferOffsets
7083       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7084       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7085     };
7086     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7087     // We don't know the offset if vindex is non-zero, so clear it.
7088     if (IdxEn)
7089       Offset = 0;
7090     EVT VT = Op.getValueType();
7091 
7092     auto *M = cast<MemSDNode>(Op);
7093     M->getMemOperand()->setOffset(Offset);
7094     unsigned Opcode = 0;
7095 
7096     switch (IntrID) {
7097     case Intrinsic::amdgcn_buffer_atomic_swap:
7098       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7099       break;
7100     case Intrinsic::amdgcn_buffer_atomic_add:
7101       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7102       break;
7103     case Intrinsic::amdgcn_buffer_atomic_sub:
7104       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7105       break;
7106     case Intrinsic::amdgcn_buffer_atomic_csub:
7107       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7108       break;
7109     case Intrinsic::amdgcn_buffer_atomic_smin:
7110       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7111       break;
7112     case Intrinsic::amdgcn_buffer_atomic_umin:
7113       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7114       break;
7115     case Intrinsic::amdgcn_buffer_atomic_smax:
7116       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7117       break;
7118     case Intrinsic::amdgcn_buffer_atomic_umax:
7119       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7120       break;
7121     case Intrinsic::amdgcn_buffer_atomic_and:
7122       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7123       break;
7124     case Intrinsic::amdgcn_buffer_atomic_or:
7125       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7126       break;
7127     case Intrinsic::amdgcn_buffer_atomic_xor:
7128       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7129       break;
7130     case Intrinsic::amdgcn_buffer_atomic_fadd:
7131       if (!Op.getValue(0).use_empty()) {
7132         DiagnosticInfoUnsupported
7133           NoFpRet(DAG.getMachineFunction().getFunction(),
7134                   "return versions of fp atomics not supported",
7135                   DL.getDebugLoc(), DS_Error);
7136         DAG.getContext()->diagnose(NoFpRet);
7137         return SDValue();
7138       }
7139       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7140       break;
7141     default:
7142       llvm_unreachable("unhandled atomic opcode");
7143     }
7144 
7145     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7146                                    M->getMemOperand());
7147   }
7148   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7149     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7150   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7151     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7152   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7153     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7154   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7155     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7156   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7157     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7158   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7159     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7160   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7161     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7162   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7163     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7164   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7165     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7166   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7167     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7168   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7169     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7170   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7171     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7172   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7173     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7174   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7175     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7176   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7177     return lowerStructBufferAtomicIntrin(Op, DAG,
7178                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7179   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7180     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7181   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7182     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7183   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7184     return lowerStructBufferAtomicIntrin(Op, DAG,
7185                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7186   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7187     return lowerStructBufferAtomicIntrin(Op, DAG,
7188                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7189   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7190     return lowerStructBufferAtomicIntrin(Op, DAG,
7191                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7192   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7193     return lowerStructBufferAtomicIntrin(Op, DAG,
7194                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7195   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7196     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7197   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7198     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7199   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7200     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7201   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7202     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7203   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7204     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7205 
7206   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7207     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7208     unsigned IdxEn = 1;
7209     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7210       IdxEn = Idx->getZExtValue() != 0;
7211     SDValue Ops[] = {
7212       Op.getOperand(0), // Chain
7213       Op.getOperand(2), // src
7214       Op.getOperand(3), // cmp
7215       Op.getOperand(4), // rsrc
7216       Op.getOperand(5), // vindex
7217       SDValue(),        // voffset -- will be set by setBufferOffsets
7218       SDValue(),        // soffset -- will be set by setBufferOffsets
7219       SDValue(),        // offset -- will be set by setBufferOffsets
7220       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7221       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7222     };
7223     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7224     // We don't know the offset if vindex is non-zero, so clear it.
7225     if (IdxEn)
7226       Offset = 0;
7227     EVT VT = Op.getValueType();
7228     auto *M = cast<MemSDNode>(Op);
7229     M->getMemOperand()->setOffset(Offset);
7230 
7231     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7232                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7233   }
7234   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7235     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7236     SDValue Ops[] = {
7237       Op.getOperand(0), // Chain
7238       Op.getOperand(2), // src
7239       Op.getOperand(3), // cmp
7240       Op.getOperand(4), // rsrc
7241       DAG.getConstant(0, DL, MVT::i32), // vindex
7242       Offsets.first,    // voffset
7243       Op.getOperand(6), // soffset
7244       Offsets.second,   // offset
7245       Op.getOperand(7), // cachepolicy
7246       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7247     };
7248     EVT VT = Op.getValueType();
7249     auto *M = cast<MemSDNode>(Op);
7250     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7251 
7252     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7253                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7254   }
7255   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7256     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7257     SDValue Ops[] = {
7258       Op.getOperand(0), // Chain
7259       Op.getOperand(2), // src
7260       Op.getOperand(3), // cmp
7261       Op.getOperand(4), // rsrc
7262       Op.getOperand(5), // vindex
7263       Offsets.first,    // voffset
7264       Op.getOperand(7), // soffset
7265       Offsets.second,   // offset
7266       Op.getOperand(8), // cachepolicy
7267       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7268     };
7269     EVT VT = Op.getValueType();
7270     auto *M = cast<MemSDNode>(Op);
7271     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7272                                                         Ops[4]));
7273 
7274     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7275                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7276   }
7277   case Intrinsic::amdgcn_global_atomic_fadd: {
7278     if (!Op.getValue(0).use_empty()) {
7279       DiagnosticInfoUnsupported
7280         NoFpRet(DAG.getMachineFunction().getFunction(),
7281                 "return versions of fp atomics not supported",
7282                 DL.getDebugLoc(), DS_Error);
7283       DAG.getContext()->diagnose(NoFpRet);
7284       return SDValue();
7285     }
7286     MemSDNode *M = cast<MemSDNode>(Op);
7287     SDValue Ops[] = {
7288       M->getOperand(0), // Chain
7289       M->getOperand(2), // Ptr
7290       M->getOperand(3)  // Value
7291     };
7292 
7293     EVT VT = Op.getOperand(3).getValueType();
7294     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7295                          DAG.getVTList(VT, MVT::Other), Ops,
7296                          M->getMemOperand());
7297   }
7298   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7299     SDLoc DL(Op);
7300     MemSDNode *M = cast<MemSDNode>(Op);
7301     SDValue NodePtr = M->getOperand(2);
7302     SDValue RayExtent = M->getOperand(3);
7303     SDValue RayOrigin = M->getOperand(4);
7304     SDValue RayDir = M->getOperand(5);
7305     SDValue RayInvDir = M->getOperand(6);
7306     SDValue TDescr = M->getOperand(7);
7307 
7308     assert(NodePtr.getValueType() == MVT::i32 ||
7309            NodePtr.getValueType() == MVT::i64);
7310     assert(RayDir.getValueType() == MVT::v4f16 ||
7311            RayDir.getValueType() == MVT::v4f32);
7312 
7313     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7314     bool Is64 = NodePtr.getValueType() == MVT::i64;
7315     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7316                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7317                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7318                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7319 
7320     SmallVector<SDValue, 16> Ops;
7321 
7322     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7323       SmallVector<SDValue, 3> Lanes;
7324       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7325       if (Lanes[0].getValueSizeInBits() == 32) {
7326         for (unsigned I = 0; I < 3; ++I)
7327           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7328       } else {
7329         if (IsAligned) {
7330           Ops.push_back(
7331             DAG.getBitcast(MVT::i32,
7332                            DAG.getBuildVector(MVT::v2f16, DL,
7333                                               { Lanes[0], Lanes[1] })));
7334           Ops.push_back(Lanes[2]);
7335         } else {
7336           SDValue Elt0 = Ops.pop_back_val();
7337           Ops.push_back(
7338             DAG.getBitcast(MVT::i32,
7339                            DAG.getBuildVector(MVT::v2f16, DL,
7340                                               { Elt0, Lanes[0] })));
7341           Ops.push_back(
7342             DAG.getBitcast(MVT::i32,
7343                            DAG.getBuildVector(MVT::v2f16, DL,
7344                                               { Lanes[1], Lanes[2] })));
7345         }
7346       }
7347     };
7348 
7349     if (Is64)
7350       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7351     else
7352       Ops.push_back(NodePtr);
7353 
7354     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7355     packLanes(RayOrigin, true);
7356     packLanes(RayDir, true);
7357     packLanes(RayInvDir, false);
7358     Ops.push_back(TDescr);
7359     if (IsA16)
7360       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7361     Ops.push_back(M->getChain());
7362 
7363     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7364     MachineMemOperand *MemRef = M->getMemOperand();
7365     DAG.setNodeMemRefs(NewNode, {MemRef});
7366     return SDValue(NewNode, 0);
7367   }
7368   default:
7369     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7370             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7371       return lowerImage(Op, ImageDimIntr, DAG, true);
7372 
7373     return SDValue();
7374   }
7375 }
7376 
7377 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7378 // dwordx4 if on SI.
7379 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7380                                               SDVTList VTList,
7381                                               ArrayRef<SDValue> Ops, EVT MemVT,
7382                                               MachineMemOperand *MMO,
7383                                               SelectionDAG &DAG) const {
7384   EVT VT = VTList.VTs[0];
7385   EVT WidenedVT = VT;
7386   EVT WidenedMemVT = MemVT;
7387   if (!Subtarget->hasDwordx3LoadStores() &&
7388       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7389     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7390                                  WidenedVT.getVectorElementType(), 4);
7391     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7392                                     WidenedMemVT.getVectorElementType(), 4);
7393     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7394   }
7395 
7396   assert(VTList.NumVTs == 2);
7397   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7398 
7399   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7400                                        WidenedMemVT, MMO);
7401   if (WidenedVT != VT) {
7402     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7403                                DAG.getVectorIdxConstant(0, DL));
7404     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7405   }
7406   return NewOp;
7407 }
7408 
7409 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7410                                          bool ImageStore) const {
7411   EVT StoreVT = VData.getValueType();
7412 
7413   // No change for f16 and legal vector D16 types.
7414   if (!StoreVT.isVector())
7415     return VData;
7416 
7417   SDLoc DL(VData);
7418   unsigned NumElements = StoreVT.getVectorNumElements();
7419 
7420   if (Subtarget->hasUnpackedD16VMem()) {
7421     // We need to unpack the packed data to store.
7422     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7423     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7424 
7425     EVT EquivStoreVT =
7426         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7427     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7428     return DAG.UnrollVectorOp(ZExt.getNode());
7429   } else if (NumElements == 3) {
7430     EVT IntStoreVT =
7431         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7432     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7433 
7434     EVT WidenedStoreVT = EVT::getVectorVT(
7435         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7436     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7437                                          WidenedStoreVT.getStoreSizeInBits());
7438     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7439     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7440   }
7441 
7442   // The sq block of gfx8.1 does not estimate register use correctly for d16
7443   // image store instructions. The data operand is computed as if it were not a
7444   // d16 image instruction.
7445   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7446     // Bitcast to i16
7447     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7448     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7449 
7450     // Decompose into scalars
7451     SmallVector<SDValue, 4> Elts;
7452     DAG.ExtractVectorElements(IntVData, Elts);
7453 
7454     // Group pairs of i16 into v2i16 and bitcast to i32
7455     SmallVector<SDValue, 4> PackedElts;
7456     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7457       SDValue Pair =
7458           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7459       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7460       PackedElts.push_back(IntPair);
7461     }
7462 
7463     // Pad using UNDEF
7464     PackedElts.resize(PackedElts.size() * 2, DAG.getUNDEF(MVT::i32));
7465 
7466     // Build final vector
7467     EVT VecVT =
7468         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7469     return DAG.getBuildVector(VecVT, DL, PackedElts);
7470   }
7471 
7472   assert(isTypeLegal(StoreVT));
7473   return VData;
7474 }
7475 
7476 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7477                                               SelectionDAG &DAG) const {
7478   SDLoc DL(Op);
7479   SDValue Chain = Op.getOperand(0);
7480   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7481   MachineFunction &MF = DAG.getMachineFunction();
7482 
7483   switch (IntrinsicID) {
7484   case Intrinsic::amdgcn_exp_compr: {
7485     SDValue Src0 = Op.getOperand(4);
7486     SDValue Src1 = Op.getOperand(5);
7487     // Hack around illegal type on SI by directly selecting it.
7488     if (isTypeLegal(Src0.getValueType()))
7489       return SDValue();
7490 
7491     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7492     SDValue Undef = DAG.getUNDEF(MVT::f32);
7493     const SDValue Ops[] = {
7494       Op.getOperand(2), // tgt
7495       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7496       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7497       Undef, // src2
7498       Undef, // src3
7499       Op.getOperand(7), // vm
7500       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7501       Op.getOperand(3), // en
7502       Op.getOperand(0) // Chain
7503     };
7504 
7505     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7506     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7507   }
7508   case Intrinsic::amdgcn_s_barrier: {
7509     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7510       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7511       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7512       if (WGSize <= ST.getWavefrontSize())
7513         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7514                                           Op.getOperand(0)), 0);
7515     }
7516     return SDValue();
7517   };
7518   case Intrinsic::amdgcn_tbuffer_store: {
7519     SDValue VData = Op.getOperand(2);
7520     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7521     if (IsD16)
7522       VData = handleD16VData(VData, DAG);
7523     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7524     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7525     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7526     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7527     unsigned IdxEn = 1;
7528     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7529       IdxEn = Idx->getZExtValue() != 0;
7530     SDValue Ops[] = {
7531       Chain,
7532       VData,             // vdata
7533       Op.getOperand(3),  // rsrc
7534       Op.getOperand(4),  // vindex
7535       Op.getOperand(5),  // voffset
7536       Op.getOperand(6),  // soffset
7537       Op.getOperand(7),  // offset
7538       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7539       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7540       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7541     };
7542     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7543                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7544     MemSDNode *M = cast<MemSDNode>(Op);
7545     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7546                                    M->getMemoryVT(), M->getMemOperand());
7547   }
7548 
7549   case Intrinsic::amdgcn_struct_tbuffer_store: {
7550     SDValue VData = Op.getOperand(2);
7551     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7552     if (IsD16)
7553       VData = handleD16VData(VData, DAG);
7554     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7555     SDValue Ops[] = {
7556       Chain,
7557       VData,             // vdata
7558       Op.getOperand(3),  // rsrc
7559       Op.getOperand(4),  // vindex
7560       Offsets.first,     // voffset
7561       Op.getOperand(6),  // soffset
7562       Offsets.second,    // offset
7563       Op.getOperand(7),  // format
7564       Op.getOperand(8),  // cachepolicy, swizzled buffer
7565       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7566     };
7567     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7568                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7569     MemSDNode *M = cast<MemSDNode>(Op);
7570     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7571                                    M->getMemoryVT(), M->getMemOperand());
7572   }
7573 
7574   case Intrinsic::amdgcn_raw_tbuffer_store: {
7575     SDValue VData = Op.getOperand(2);
7576     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7577     if (IsD16)
7578       VData = handleD16VData(VData, DAG);
7579     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7580     SDValue Ops[] = {
7581       Chain,
7582       VData,             // vdata
7583       Op.getOperand(3),  // rsrc
7584       DAG.getConstant(0, DL, MVT::i32), // vindex
7585       Offsets.first,     // voffset
7586       Op.getOperand(5),  // soffset
7587       Offsets.second,    // offset
7588       Op.getOperand(6),  // format
7589       Op.getOperand(7),  // cachepolicy, swizzled buffer
7590       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7591     };
7592     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7593                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7594     MemSDNode *M = cast<MemSDNode>(Op);
7595     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7596                                    M->getMemoryVT(), M->getMemOperand());
7597   }
7598 
7599   case Intrinsic::amdgcn_buffer_store:
7600   case Intrinsic::amdgcn_buffer_store_format: {
7601     SDValue VData = Op.getOperand(2);
7602     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7603     if (IsD16)
7604       VData = handleD16VData(VData, DAG);
7605     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7606     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7607     unsigned IdxEn = 1;
7608     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7609       IdxEn = Idx->getZExtValue() != 0;
7610     SDValue Ops[] = {
7611       Chain,
7612       VData,
7613       Op.getOperand(3), // rsrc
7614       Op.getOperand(4), // vindex
7615       SDValue(), // voffset -- will be set by setBufferOffsets
7616       SDValue(), // soffset -- will be set by setBufferOffsets
7617       SDValue(), // offset -- will be set by setBufferOffsets
7618       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7619       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7620     };
7621     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7622     // We don't know the offset if vindex is non-zero, so clear it.
7623     if (IdxEn)
7624       Offset = 0;
7625     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7626                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7627     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7628     MemSDNode *M = cast<MemSDNode>(Op);
7629     M->getMemOperand()->setOffset(Offset);
7630 
7631     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7632     EVT VDataType = VData.getValueType().getScalarType();
7633     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7634       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7635 
7636     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7637                                    M->getMemoryVT(), M->getMemOperand());
7638   }
7639 
7640   case Intrinsic::amdgcn_raw_buffer_store:
7641   case Intrinsic::amdgcn_raw_buffer_store_format: {
7642     const bool IsFormat =
7643         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7644 
7645     SDValue VData = Op.getOperand(2);
7646     EVT VDataVT = VData.getValueType();
7647     EVT EltType = VDataVT.getScalarType();
7648     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7649     if (IsD16) {
7650       VData = handleD16VData(VData, DAG);
7651       VDataVT = VData.getValueType();
7652     }
7653 
7654     if (!isTypeLegal(VDataVT)) {
7655       VData =
7656           DAG.getNode(ISD::BITCAST, DL,
7657                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7658     }
7659 
7660     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7661     SDValue Ops[] = {
7662       Chain,
7663       VData,
7664       Op.getOperand(3), // rsrc
7665       DAG.getConstant(0, DL, MVT::i32), // vindex
7666       Offsets.first,    // voffset
7667       Op.getOperand(5), // soffset
7668       Offsets.second,   // offset
7669       Op.getOperand(6), // cachepolicy, swizzled buffer
7670       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7671     };
7672     unsigned Opc =
7673         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7674     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7675     MemSDNode *M = cast<MemSDNode>(Op);
7676     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7677 
7678     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7679     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7680       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7681 
7682     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7683                                    M->getMemoryVT(), M->getMemOperand());
7684   }
7685 
7686   case Intrinsic::amdgcn_struct_buffer_store:
7687   case Intrinsic::amdgcn_struct_buffer_store_format: {
7688     const bool IsFormat =
7689         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7690 
7691     SDValue VData = Op.getOperand(2);
7692     EVT VDataVT = VData.getValueType();
7693     EVT EltType = VDataVT.getScalarType();
7694     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7695 
7696     if (IsD16) {
7697       VData = handleD16VData(VData, DAG);
7698       VDataVT = VData.getValueType();
7699     }
7700 
7701     if (!isTypeLegal(VDataVT)) {
7702       VData =
7703           DAG.getNode(ISD::BITCAST, DL,
7704                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7705     }
7706 
7707     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7708     SDValue Ops[] = {
7709       Chain,
7710       VData,
7711       Op.getOperand(3), // rsrc
7712       Op.getOperand(4), // vindex
7713       Offsets.first,    // voffset
7714       Op.getOperand(6), // soffset
7715       Offsets.second,   // offset
7716       Op.getOperand(7), // cachepolicy, swizzled buffer
7717       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7718     };
7719     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7720                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7721     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7722     MemSDNode *M = cast<MemSDNode>(Op);
7723     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7724                                                         Ops[3]));
7725 
7726     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7727     EVT VDataType = VData.getValueType().getScalarType();
7728     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7729       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7730 
7731     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7732                                    M->getMemoryVT(), M->getMemOperand());
7733   }
7734   case Intrinsic::amdgcn_end_cf:
7735     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7736                                       Op->getOperand(2), Chain), 0);
7737 
7738   default: {
7739     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7740             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7741       return lowerImage(Op, ImageDimIntr, DAG, true);
7742 
7743     return Op;
7744   }
7745   }
7746 }
7747 
7748 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7749 // offset (the offset that is included in bounds checking and swizzling, to be
7750 // split between the instruction's voffset and immoffset fields) and soffset
7751 // (the offset that is excluded from bounds checking and swizzling, to go in
7752 // the instruction's soffset field).  This function takes the first kind of
7753 // offset and figures out how to split it between voffset and immoffset.
7754 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7755     SDValue Offset, SelectionDAG &DAG) const {
7756   SDLoc DL(Offset);
7757   const unsigned MaxImm = 4095;
7758   SDValue N0 = Offset;
7759   ConstantSDNode *C1 = nullptr;
7760 
7761   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7762     N0 = SDValue();
7763   else if (DAG.isBaseWithConstantOffset(N0)) {
7764     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7765     N0 = N0.getOperand(0);
7766   }
7767 
7768   if (C1) {
7769     unsigned ImmOffset = C1->getZExtValue();
7770     // If the immediate value is too big for the immoffset field, put the value
7771     // and -4096 into the immoffset field so that the value that is copied/added
7772     // for the voffset field is a multiple of 4096, and it stands more chance
7773     // of being CSEd with the copy/add for another similar load/store.
7774     // However, do not do that rounding down to a multiple of 4096 if that is a
7775     // negative number, as it appears to be illegal to have a negative offset
7776     // in the vgpr, even if adding the immediate offset makes it positive.
7777     unsigned Overflow = ImmOffset & ~MaxImm;
7778     ImmOffset -= Overflow;
7779     if ((int32_t)Overflow < 0) {
7780       Overflow += ImmOffset;
7781       ImmOffset = 0;
7782     }
7783     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7784     if (Overflow) {
7785       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7786       if (!N0)
7787         N0 = OverflowVal;
7788       else {
7789         SDValue Ops[] = { N0, OverflowVal };
7790         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7791       }
7792     }
7793   }
7794   if (!N0)
7795     N0 = DAG.getConstant(0, DL, MVT::i32);
7796   if (!C1)
7797     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7798   return {N0, SDValue(C1, 0)};
7799 }
7800 
7801 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7802 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7803 // pointed to by Offsets.
7804 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7805                                             SelectionDAG &DAG, SDValue *Offsets,
7806                                             Align Alignment) const {
7807   SDLoc DL(CombinedOffset);
7808   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7809     uint32_t Imm = C->getZExtValue();
7810     uint32_t SOffset, ImmOffset;
7811     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7812                                  Alignment)) {
7813       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7814       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7815       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7816       return SOffset + ImmOffset;
7817     }
7818   }
7819   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7820     SDValue N0 = CombinedOffset.getOperand(0);
7821     SDValue N1 = CombinedOffset.getOperand(1);
7822     uint32_t SOffset, ImmOffset;
7823     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7824     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7825                                                 Subtarget, Alignment)) {
7826       Offsets[0] = N0;
7827       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7828       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7829       return 0;
7830     }
7831   }
7832   Offsets[0] = CombinedOffset;
7833   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7834   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7835   return 0;
7836 }
7837 
7838 // Handle 8 bit and 16 bit buffer loads
7839 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7840                                                      EVT LoadVT, SDLoc DL,
7841                                                      ArrayRef<SDValue> Ops,
7842                                                      MemSDNode *M) const {
7843   EVT IntVT = LoadVT.changeTypeToInteger();
7844   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7845          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7846 
7847   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7848   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7849                                                Ops, IntVT,
7850                                                M->getMemOperand());
7851   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7852   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7853 
7854   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7855 }
7856 
7857 // Handle 8 bit and 16 bit buffer stores
7858 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7859                                                       EVT VDataType, SDLoc DL,
7860                                                       SDValue Ops[],
7861                                                       MemSDNode *M) const {
7862   if (VDataType == MVT::f16)
7863     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7864 
7865   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7866   Ops[1] = BufferStoreExt;
7867   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7868                                  AMDGPUISD::BUFFER_STORE_SHORT;
7869   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7870   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7871                                      M->getMemOperand());
7872 }
7873 
7874 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7875                                  ISD::LoadExtType ExtType, SDValue Op,
7876                                  const SDLoc &SL, EVT VT) {
7877   if (VT.bitsLT(Op.getValueType()))
7878     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7879 
7880   switch (ExtType) {
7881   case ISD::SEXTLOAD:
7882     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7883   case ISD::ZEXTLOAD:
7884     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7885   case ISD::EXTLOAD:
7886     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7887   case ISD::NON_EXTLOAD:
7888     return Op;
7889   }
7890 
7891   llvm_unreachable("invalid ext type");
7892 }
7893 
7894 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7895   SelectionDAG &DAG = DCI.DAG;
7896   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7897     return SDValue();
7898 
7899   // FIXME: Constant loads should all be marked invariant.
7900   unsigned AS = Ld->getAddressSpace();
7901   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7902       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7903       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7904     return SDValue();
7905 
7906   // Don't do this early, since it may interfere with adjacent load merging for
7907   // illegal types. We can avoid losing alignment information for exotic types
7908   // pre-legalize.
7909   EVT MemVT = Ld->getMemoryVT();
7910   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7911       MemVT.getSizeInBits() >= 32)
7912     return SDValue();
7913 
7914   SDLoc SL(Ld);
7915 
7916   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7917          "unexpected vector extload");
7918 
7919   // TODO: Drop only high part of range.
7920   SDValue Ptr = Ld->getBasePtr();
7921   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7922                                 MVT::i32, SL, Ld->getChain(), Ptr,
7923                                 Ld->getOffset(),
7924                                 Ld->getPointerInfo(), MVT::i32,
7925                                 Ld->getAlignment(),
7926                                 Ld->getMemOperand()->getFlags(),
7927                                 Ld->getAAInfo(),
7928                                 nullptr); // Drop ranges
7929 
7930   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7931   if (MemVT.isFloatingPoint()) {
7932     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7933            "unexpected fp extload");
7934     TruncVT = MemVT.changeTypeToInteger();
7935   }
7936 
7937   SDValue Cvt = NewLoad;
7938   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7939     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7940                       DAG.getValueType(TruncVT));
7941   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7942              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7943     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7944   } else {
7945     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7946   }
7947 
7948   EVT VT = Ld->getValueType(0);
7949   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7950 
7951   DCI.AddToWorklist(Cvt.getNode());
7952 
7953   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7954   // the appropriate extension from the 32-bit load.
7955   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7956   DCI.AddToWorklist(Cvt.getNode());
7957 
7958   // Handle conversion back to floating point if necessary.
7959   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7960 
7961   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7962 }
7963 
7964 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7965   SDLoc DL(Op);
7966   LoadSDNode *Load = cast<LoadSDNode>(Op);
7967   ISD::LoadExtType ExtType = Load->getExtensionType();
7968   EVT MemVT = Load->getMemoryVT();
7969 
7970   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7971     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7972       return SDValue();
7973 
7974     // FIXME: Copied from PPC
7975     // First, load into 32 bits, then truncate to 1 bit.
7976 
7977     SDValue Chain = Load->getChain();
7978     SDValue BasePtr = Load->getBasePtr();
7979     MachineMemOperand *MMO = Load->getMemOperand();
7980 
7981     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7982 
7983     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7984                                    BasePtr, RealMemVT, MMO);
7985 
7986     if (!MemVT.isVector()) {
7987       SDValue Ops[] = {
7988         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7989         NewLD.getValue(1)
7990       };
7991 
7992       return DAG.getMergeValues(Ops, DL);
7993     }
7994 
7995     SmallVector<SDValue, 3> Elts;
7996     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7997       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7998                                 DAG.getConstant(I, DL, MVT::i32));
7999 
8000       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8001     }
8002 
8003     SDValue Ops[] = {
8004       DAG.getBuildVector(MemVT, DL, Elts),
8005       NewLD.getValue(1)
8006     };
8007 
8008     return DAG.getMergeValues(Ops, DL);
8009   }
8010 
8011   if (!MemVT.isVector())
8012     return SDValue();
8013 
8014   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8015          "Custom lowering for non-i32 vectors hasn't been implemented.");
8016 
8017   unsigned Alignment = Load->getAlignment();
8018   unsigned AS = Load->getAddressSpace();
8019   if (Subtarget->hasLDSMisalignedBug() &&
8020       AS == AMDGPUAS::FLAT_ADDRESS &&
8021       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8022     return SplitVectorLoad(Op, DAG);
8023   }
8024 
8025   MachineFunction &MF = DAG.getMachineFunction();
8026   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8027   // If there is a possibilty that flat instruction access scratch memory
8028   // then we need to use the same legalization rules we use for private.
8029   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8030       !Subtarget->hasMultiDwordFlatScratchAddressing())
8031     AS = MFI->hasFlatScratchInit() ?
8032          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8033 
8034   unsigned NumElements = MemVT.getVectorNumElements();
8035 
8036   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8037       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8038     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8039       if (MemVT.isPow2VectorType())
8040         return SDValue();
8041       if (NumElements == 3)
8042         return WidenVectorLoad(Op, DAG);
8043       return SplitVectorLoad(Op, DAG);
8044     }
8045     // Non-uniform loads will be selected to MUBUF instructions, so they
8046     // have the same legalization requirements as global and private
8047     // loads.
8048     //
8049   }
8050 
8051   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8052       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8053       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8054     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8055         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8056         Alignment >= 4 && NumElements < 32) {
8057       if (MemVT.isPow2VectorType())
8058         return SDValue();
8059       if (NumElements == 3)
8060         return WidenVectorLoad(Op, DAG);
8061       return SplitVectorLoad(Op, DAG);
8062     }
8063     // Non-uniform loads will be selected to MUBUF instructions, so they
8064     // have the same legalization requirements as global and private
8065     // loads.
8066     //
8067   }
8068   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8069       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8070       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8071       AS == AMDGPUAS::FLAT_ADDRESS) {
8072     if (NumElements > 4)
8073       return SplitVectorLoad(Op, DAG);
8074     // v3 loads not supported on SI.
8075     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8076       return WidenVectorLoad(Op, DAG);
8077     // v3 and v4 loads are supported for private and global memory.
8078     return SDValue();
8079   }
8080   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8081     // Depending on the setting of the private_element_size field in the
8082     // resource descriptor, we can only make private accesses up to a certain
8083     // size.
8084     switch (Subtarget->getMaxPrivateElementSize()) {
8085     case 4: {
8086       SDValue Ops[2];
8087       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8088       return DAG.getMergeValues(Ops, DL);
8089     }
8090     case 8:
8091       if (NumElements > 2)
8092         return SplitVectorLoad(Op, DAG);
8093       return SDValue();
8094     case 16:
8095       // Same as global/flat
8096       if (NumElements > 4)
8097         return SplitVectorLoad(Op, DAG);
8098       // v3 loads not supported on SI.
8099       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8100         return WidenVectorLoad(Op, DAG);
8101       return SDValue();
8102     default:
8103       llvm_unreachable("unsupported private_element_size");
8104     }
8105   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8106     // Use ds_read_b128 or ds_read_b96 when possible.
8107     if (Subtarget->hasDS96AndDS128() &&
8108         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8109          MemVT.getStoreSize() == 12) &&
8110         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8111                                            Load->getAlign()))
8112       return SDValue();
8113 
8114     if (NumElements > 2)
8115       return SplitVectorLoad(Op, DAG);
8116 
8117     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8118     // address is negative, then the instruction is incorrectly treated as
8119     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8120     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8121     // load later in the SILoadStoreOptimizer.
8122     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8123         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8124         Load->getAlignment() < 8) {
8125       return SplitVectorLoad(Op, DAG);
8126     }
8127   }
8128 
8129   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8130                                       MemVT, *Load->getMemOperand())) {
8131     SDValue Ops[2];
8132     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8133     return DAG.getMergeValues(Ops, DL);
8134   }
8135 
8136   return SDValue();
8137 }
8138 
8139 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8140   EVT VT = Op.getValueType();
8141   assert(VT.getSizeInBits() == 64);
8142 
8143   SDLoc DL(Op);
8144   SDValue Cond = Op.getOperand(0);
8145 
8146   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8147   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8148 
8149   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8150   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8151 
8152   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8153   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8154 
8155   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8156 
8157   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8158   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8159 
8160   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8161 
8162   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8163   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8164 }
8165 
8166 // Catch division cases where we can use shortcuts with rcp and rsq
8167 // instructions.
8168 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8169                                               SelectionDAG &DAG) const {
8170   SDLoc SL(Op);
8171   SDValue LHS = Op.getOperand(0);
8172   SDValue RHS = Op.getOperand(1);
8173   EVT VT = Op.getValueType();
8174   const SDNodeFlags Flags = Op->getFlags();
8175 
8176   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
8177                             Flags.hasApproximateFuncs();
8178 
8179   // Without !fpmath accuracy information, we can't do more because we don't
8180   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8181   if (!AllowInaccurateRcp)
8182     return SDValue();
8183 
8184   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8185     if (CLHS->isExactlyValue(1.0)) {
8186       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8187       // the CI documentation has a worst case error of 1 ulp.
8188       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8189       // use it as long as we aren't trying to use denormals.
8190       //
8191       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8192 
8193       // 1.0 / sqrt(x) -> rsq(x)
8194 
8195       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8196       // error seems really high at 2^29 ULP.
8197       if (RHS.getOpcode() == ISD::FSQRT)
8198         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8199 
8200       // 1.0 / x -> rcp(x)
8201       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8202     }
8203 
8204     // Same as for 1.0, but expand the sign out of the constant.
8205     if (CLHS->isExactlyValue(-1.0)) {
8206       // -1.0 / x -> rcp (fneg x)
8207       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8208       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8209     }
8210   }
8211 
8212   // Turn into multiply by the reciprocal.
8213   // x / y -> x * (1.0 / y)
8214   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8215   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8216 }
8217 
8218 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8219                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8220                           SDNodeFlags Flags) {
8221   if (GlueChain->getNumValues() <= 1) {
8222     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8223   }
8224 
8225   assert(GlueChain->getNumValues() == 3);
8226 
8227   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8228   switch (Opcode) {
8229   default: llvm_unreachable("no chain equivalent for opcode");
8230   case ISD::FMUL:
8231     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8232     break;
8233   }
8234 
8235   return DAG.getNode(Opcode, SL, VTList,
8236                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8237                      Flags);
8238 }
8239 
8240 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8241                            EVT VT, SDValue A, SDValue B, SDValue C,
8242                            SDValue GlueChain, SDNodeFlags Flags) {
8243   if (GlueChain->getNumValues() <= 1) {
8244     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8245   }
8246 
8247   assert(GlueChain->getNumValues() == 3);
8248 
8249   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8250   switch (Opcode) {
8251   default: llvm_unreachable("no chain equivalent for opcode");
8252   case ISD::FMA:
8253     Opcode = AMDGPUISD::FMA_W_CHAIN;
8254     break;
8255   }
8256 
8257   return DAG.getNode(Opcode, SL, VTList,
8258                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8259                      Flags);
8260 }
8261 
8262 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8263   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8264     return FastLowered;
8265 
8266   SDLoc SL(Op);
8267   SDValue Src0 = Op.getOperand(0);
8268   SDValue Src1 = Op.getOperand(1);
8269 
8270   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8271   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8272 
8273   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8274   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8275 
8276   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8277   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8278 
8279   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8280 }
8281 
8282 // Faster 2.5 ULP division that does not support denormals.
8283 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8284   SDLoc SL(Op);
8285   SDValue LHS = Op.getOperand(1);
8286   SDValue RHS = Op.getOperand(2);
8287 
8288   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8289 
8290   const APFloat K0Val(BitsToFloat(0x6f800000));
8291   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8292 
8293   const APFloat K1Val(BitsToFloat(0x2f800000));
8294   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8295 
8296   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8297 
8298   EVT SetCCVT =
8299     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8300 
8301   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8302 
8303   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8304 
8305   // TODO: Should this propagate fast-math-flags?
8306   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8307 
8308   // rcp does not support denormals.
8309   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8310 
8311   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8312 
8313   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8314 }
8315 
8316 // Returns immediate value for setting the F32 denorm mode when using the
8317 // S_DENORM_MODE instruction.
8318 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8319                                           const SDLoc &SL, const GCNSubtarget *ST) {
8320   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8321   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8322                                 ? FP_DENORM_FLUSH_NONE
8323                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8324 
8325   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8326   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8327 }
8328 
8329 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8330   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8331     return FastLowered;
8332 
8333   // The selection matcher assumes anything with a chain selecting to a
8334   // mayRaiseFPException machine instruction. Since we're introducing a chain
8335   // here, we need to explicitly report nofpexcept for the regular fdiv
8336   // lowering.
8337   SDNodeFlags Flags = Op->getFlags();
8338   Flags.setNoFPExcept(true);
8339 
8340   SDLoc SL(Op);
8341   SDValue LHS = Op.getOperand(0);
8342   SDValue RHS = Op.getOperand(1);
8343 
8344   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8345 
8346   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8347 
8348   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8349                                           {RHS, RHS, LHS}, Flags);
8350   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8351                                         {LHS, RHS, LHS}, Flags);
8352 
8353   // Denominator is scaled to not be denormal, so using rcp is ok.
8354   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8355                                   DenominatorScaled, Flags);
8356   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8357                                      DenominatorScaled, Flags);
8358 
8359   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8360                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8361                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8362   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8363 
8364   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8365 
8366   if (!HasFP32Denormals) {
8367     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8368     // lowering. The chain dependence is insufficient, and we need glue. We do
8369     // not need the glue variants in a strictfp function.
8370 
8371     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8372 
8373     SDNode *EnableDenorm;
8374     if (Subtarget->hasDenormModeInst()) {
8375       const SDValue EnableDenormValue =
8376           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8377 
8378       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8379                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8380     } else {
8381       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8382                                                         SL, MVT::i32);
8383       EnableDenorm =
8384           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8385                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8386     }
8387 
8388     SDValue Ops[3] = {
8389       NegDivScale0,
8390       SDValue(EnableDenorm, 0),
8391       SDValue(EnableDenorm, 1)
8392     };
8393 
8394     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8395   }
8396 
8397   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8398                              ApproxRcp, One, NegDivScale0, Flags);
8399 
8400   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8401                              ApproxRcp, Fma0, Flags);
8402 
8403   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8404                            Fma1, Fma1, Flags);
8405 
8406   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8407                              NumeratorScaled, Mul, Flags);
8408 
8409   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8410                              Fma2, Fma1, Mul, Fma2, Flags);
8411 
8412   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8413                              NumeratorScaled, Fma3, Flags);
8414 
8415   if (!HasFP32Denormals) {
8416     SDNode *DisableDenorm;
8417     if (Subtarget->hasDenormModeInst()) {
8418       const SDValue DisableDenormValue =
8419           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8420 
8421       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8422                                   Fma4.getValue(1), DisableDenormValue,
8423                                   Fma4.getValue(2)).getNode();
8424     } else {
8425       const SDValue DisableDenormValue =
8426           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8427 
8428       DisableDenorm = DAG.getMachineNode(
8429           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8430           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8431     }
8432 
8433     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8434                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8435     DAG.setRoot(OutputChain);
8436   }
8437 
8438   SDValue Scale = NumeratorScaled.getValue(1);
8439   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8440                              {Fma4, Fma1, Fma3, Scale}, Flags);
8441 
8442   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8443 }
8444 
8445 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8446   if (DAG.getTarget().Options.UnsafeFPMath)
8447     return lowerFastUnsafeFDIV(Op, DAG);
8448 
8449   SDLoc SL(Op);
8450   SDValue X = Op.getOperand(0);
8451   SDValue Y = Op.getOperand(1);
8452 
8453   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8454 
8455   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8456 
8457   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8458 
8459   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8460 
8461   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8462 
8463   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8464 
8465   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8466 
8467   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8468 
8469   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8470 
8471   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8472   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8473 
8474   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8475                              NegDivScale0, Mul, DivScale1);
8476 
8477   SDValue Scale;
8478 
8479   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8480     // Workaround a hardware bug on SI where the condition output from div_scale
8481     // is not usable.
8482 
8483     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8484 
8485     // Figure out if the scale to use for div_fmas.
8486     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8487     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8488     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8489     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8490 
8491     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8492     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8493 
8494     SDValue Scale0Hi
8495       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8496     SDValue Scale1Hi
8497       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8498 
8499     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8500     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8501     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8502   } else {
8503     Scale = DivScale1.getValue(1);
8504   }
8505 
8506   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8507                              Fma4, Fma3, Mul, Scale);
8508 
8509   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8510 }
8511 
8512 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8513   EVT VT = Op.getValueType();
8514 
8515   if (VT == MVT::f32)
8516     return LowerFDIV32(Op, DAG);
8517 
8518   if (VT == MVT::f64)
8519     return LowerFDIV64(Op, DAG);
8520 
8521   if (VT == MVT::f16)
8522     return LowerFDIV16(Op, DAG);
8523 
8524   llvm_unreachable("Unexpected type for fdiv");
8525 }
8526 
8527 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8528   SDLoc DL(Op);
8529   StoreSDNode *Store = cast<StoreSDNode>(Op);
8530   EVT VT = Store->getMemoryVT();
8531 
8532   if (VT == MVT::i1) {
8533     return DAG.getTruncStore(Store->getChain(), DL,
8534        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8535        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8536   }
8537 
8538   assert(VT.isVector() &&
8539          Store->getValue().getValueType().getScalarType() == MVT::i32);
8540 
8541   unsigned AS = Store->getAddressSpace();
8542   if (Subtarget->hasLDSMisalignedBug() &&
8543       AS == AMDGPUAS::FLAT_ADDRESS &&
8544       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8545     return SplitVectorStore(Op, DAG);
8546   }
8547 
8548   MachineFunction &MF = DAG.getMachineFunction();
8549   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8550   // If there is a possibilty that flat instruction access scratch memory
8551   // then we need to use the same legalization rules we use for private.
8552   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8553       !Subtarget->hasMultiDwordFlatScratchAddressing())
8554     AS = MFI->hasFlatScratchInit() ?
8555          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8556 
8557   unsigned NumElements = VT.getVectorNumElements();
8558   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8559       AS == AMDGPUAS::FLAT_ADDRESS) {
8560     if (NumElements > 4)
8561       return SplitVectorStore(Op, DAG);
8562     // v3 stores not supported on SI.
8563     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8564       return SplitVectorStore(Op, DAG);
8565 
8566     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8567                                         VT, *Store->getMemOperand()))
8568       return expandUnalignedStore(Store, DAG);
8569 
8570     return SDValue();
8571   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8572     switch (Subtarget->getMaxPrivateElementSize()) {
8573     case 4:
8574       return scalarizeVectorStore(Store, DAG);
8575     case 8:
8576       if (NumElements > 2)
8577         return SplitVectorStore(Op, DAG);
8578       return SDValue();
8579     case 16:
8580       if (NumElements > 4 || NumElements == 3)
8581         return SplitVectorStore(Op, DAG);
8582       return SDValue();
8583     default:
8584       llvm_unreachable("unsupported private_element_size");
8585     }
8586   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8587     // Use ds_write_b128 or ds_write_b96 when possible.
8588     if (Subtarget->hasDS96AndDS128() &&
8589         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8590          (VT.getStoreSize() == 12)) &&
8591         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8592                                            Store->getAlign()))
8593       return SDValue();
8594 
8595     if (NumElements > 2)
8596       return SplitVectorStore(Op, DAG);
8597 
8598     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8599     // address is negative, then the instruction is incorrectly treated as
8600     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8601     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8602     // store later in the SILoadStoreOptimizer.
8603     if (!Subtarget->hasUsableDSOffset() &&
8604         NumElements == 2 && VT.getStoreSize() == 8 &&
8605         Store->getAlignment() < 8) {
8606       return SplitVectorStore(Op, DAG);
8607     }
8608 
8609     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8610                                         VT, *Store->getMemOperand())) {
8611       if (VT.isVector())
8612         return SplitVectorStore(Op, DAG);
8613       return expandUnalignedStore(Store, DAG);
8614     }
8615 
8616     return SDValue();
8617   } else {
8618     llvm_unreachable("unhandled address space");
8619   }
8620 }
8621 
8622 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8623   SDLoc DL(Op);
8624   EVT VT = Op.getValueType();
8625   SDValue Arg = Op.getOperand(0);
8626   SDValue TrigVal;
8627 
8628   // Propagate fast-math flags so that the multiply we introduce can be folded
8629   // if Arg is already the result of a multiply by constant.
8630   auto Flags = Op->getFlags();
8631 
8632   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8633 
8634   if (Subtarget->hasTrigReducedRange()) {
8635     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8636     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8637   } else {
8638     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8639   }
8640 
8641   switch (Op.getOpcode()) {
8642   case ISD::FCOS:
8643     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8644   case ISD::FSIN:
8645     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8646   default:
8647     llvm_unreachable("Wrong trig opcode");
8648   }
8649 }
8650 
8651 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8652   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8653   assert(AtomicNode->isCompareAndSwap());
8654   unsigned AS = AtomicNode->getAddressSpace();
8655 
8656   // No custom lowering required for local address space
8657   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8658     return Op;
8659 
8660   // Non-local address space requires custom lowering for atomic compare
8661   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8662   SDLoc DL(Op);
8663   SDValue ChainIn = Op.getOperand(0);
8664   SDValue Addr = Op.getOperand(1);
8665   SDValue Old = Op.getOperand(2);
8666   SDValue New = Op.getOperand(3);
8667   EVT VT = Op.getValueType();
8668   MVT SimpleVT = VT.getSimpleVT();
8669   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8670 
8671   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8672   SDValue Ops[] = { ChainIn, Addr, NewOld };
8673 
8674   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8675                                  Ops, VT, AtomicNode->getMemOperand());
8676 }
8677 
8678 //===----------------------------------------------------------------------===//
8679 // Custom DAG optimizations
8680 //===----------------------------------------------------------------------===//
8681 
8682 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8683                                                      DAGCombinerInfo &DCI) const {
8684   EVT VT = N->getValueType(0);
8685   EVT ScalarVT = VT.getScalarType();
8686   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8687     return SDValue();
8688 
8689   SelectionDAG &DAG = DCI.DAG;
8690   SDLoc DL(N);
8691 
8692   SDValue Src = N->getOperand(0);
8693   EVT SrcVT = Src.getValueType();
8694 
8695   // TODO: We could try to match extracting the higher bytes, which would be
8696   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8697   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8698   // about in practice.
8699   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8700     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8701       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8702       DCI.AddToWorklist(Cvt.getNode());
8703 
8704       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8705       if (ScalarVT != MVT::f32) {
8706         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8707                           DAG.getTargetConstant(0, DL, MVT::i32));
8708       }
8709       return Cvt;
8710     }
8711   }
8712 
8713   return SDValue();
8714 }
8715 
8716 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8717 
8718 // This is a variant of
8719 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8720 //
8721 // The normal DAG combiner will do this, but only if the add has one use since
8722 // that would increase the number of instructions.
8723 //
8724 // This prevents us from seeing a constant offset that can be folded into a
8725 // memory instruction's addressing mode. If we know the resulting add offset of
8726 // a pointer can be folded into an addressing offset, we can replace the pointer
8727 // operand with the add of new constant offset. This eliminates one of the uses,
8728 // and may allow the remaining use to also be simplified.
8729 //
8730 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8731                                                unsigned AddrSpace,
8732                                                EVT MemVT,
8733                                                DAGCombinerInfo &DCI) const {
8734   SDValue N0 = N->getOperand(0);
8735   SDValue N1 = N->getOperand(1);
8736 
8737   // We only do this to handle cases where it's profitable when there are
8738   // multiple uses of the add, so defer to the standard combine.
8739   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8740       N0->hasOneUse())
8741     return SDValue();
8742 
8743   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8744   if (!CN1)
8745     return SDValue();
8746 
8747   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8748   if (!CAdd)
8749     return SDValue();
8750 
8751   // If the resulting offset is too large, we can't fold it into the addressing
8752   // mode offset.
8753   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8754   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8755 
8756   AddrMode AM;
8757   AM.HasBaseReg = true;
8758   AM.BaseOffs = Offset.getSExtValue();
8759   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8760     return SDValue();
8761 
8762   SelectionDAG &DAG = DCI.DAG;
8763   SDLoc SL(N);
8764   EVT VT = N->getValueType(0);
8765 
8766   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8767   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8768 
8769   SDNodeFlags Flags;
8770   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8771                           (N0.getOpcode() == ISD::OR ||
8772                            N0->getFlags().hasNoUnsignedWrap()));
8773 
8774   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8775 }
8776 
8777 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8778 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8779 /// specific intrinsic, but they all place the pointer operand first.
8780 static unsigned getBasePtrIndex(const MemSDNode *N) {
8781   switch (N->getOpcode()) {
8782   case ISD::STORE:
8783   case ISD::INTRINSIC_W_CHAIN:
8784   case ISD::INTRINSIC_VOID:
8785     return 2;
8786   default:
8787     return 1;
8788   }
8789 }
8790 
8791 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8792                                                   DAGCombinerInfo &DCI) const {
8793   SelectionDAG &DAG = DCI.DAG;
8794   SDLoc SL(N);
8795 
8796   unsigned PtrIdx = getBasePtrIndex(N);
8797   SDValue Ptr = N->getOperand(PtrIdx);
8798 
8799   // TODO: We could also do this for multiplies.
8800   if (Ptr.getOpcode() == ISD::SHL) {
8801     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8802                                           N->getMemoryVT(), DCI);
8803     if (NewPtr) {
8804       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8805 
8806       NewOps[PtrIdx] = NewPtr;
8807       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8808     }
8809   }
8810 
8811   return SDValue();
8812 }
8813 
8814 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8815   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8816          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8817          (Opc == ISD::XOR && Val == 0);
8818 }
8819 
8820 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8821 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8822 // integer combine opportunities since most 64-bit operations are decomposed
8823 // this way.  TODO: We won't want this for SALU especially if it is an inline
8824 // immediate.
8825 SDValue SITargetLowering::splitBinaryBitConstantOp(
8826   DAGCombinerInfo &DCI,
8827   const SDLoc &SL,
8828   unsigned Opc, SDValue LHS,
8829   const ConstantSDNode *CRHS) const {
8830   uint64_t Val = CRHS->getZExtValue();
8831   uint32_t ValLo = Lo_32(Val);
8832   uint32_t ValHi = Hi_32(Val);
8833   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8834 
8835     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8836          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8837         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8838     // If we need to materialize a 64-bit immediate, it will be split up later
8839     // anyway. Avoid creating the harder to understand 64-bit immediate
8840     // materialization.
8841     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8842   }
8843 
8844   return SDValue();
8845 }
8846 
8847 // Returns true if argument is a boolean value which is not serialized into
8848 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8849 static bool isBoolSGPR(SDValue V) {
8850   if (V.getValueType() != MVT::i1)
8851     return false;
8852   switch (V.getOpcode()) {
8853   default: break;
8854   case ISD::SETCC:
8855   case ISD::AND:
8856   case ISD::OR:
8857   case ISD::XOR:
8858   case AMDGPUISD::FP_CLASS:
8859     return true;
8860   }
8861   return false;
8862 }
8863 
8864 // If a constant has all zeroes or all ones within each byte return it.
8865 // Otherwise return 0.
8866 static uint32_t getConstantPermuteMask(uint32_t C) {
8867   // 0xff for any zero byte in the mask
8868   uint32_t ZeroByteMask = 0;
8869   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8870   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8871   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8872   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8873   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8874   if ((NonZeroByteMask & C) != NonZeroByteMask)
8875     return 0; // Partial bytes selected.
8876   return C;
8877 }
8878 
8879 // Check if a node selects whole bytes from its operand 0 starting at a byte
8880 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8881 // or -1 if not succeeded.
8882 // Note byte select encoding:
8883 // value 0-3 selects corresponding source byte;
8884 // value 0xc selects zero;
8885 // value 0xff selects 0xff.
8886 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8887   assert(V.getValueSizeInBits() == 32);
8888 
8889   if (V.getNumOperands() != 2)
8890     return ~0;
8891 
8892   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8893   if (!N1)
8894     return ~0;
8895 
8896   uint32_t C = N1->getZExtValue();
8897 
8898   switch (V.getOpcode()) {
8899   default:
8900     break;
8901   case ISD::AND:
8902     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8903       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8904     }
8905     break;
8906 
8907   case ISD::OR:
8908     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8909       return (0x03020100 & ~ConstMask) | ConstMask;
8910     }
8911     break;
8912 
8913   case ISD::SHL:
8914     if (C % 8)
8915       return ~0;
8916 
8917     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8918 
8919   case ISD::SRL:
8920     if (C % 8)
8921       return ~0;
8922 
8923     return uint32_t(0x0c0c0c0c03020100ull >> C);
8924   }
8925 
8926   return ~0;
8927 }
8928 
8929 SDValue SITargetLowering::performAndCombine(SDNode *N,
8930                                             DAGCombinerInfo &DCI) const {
8931   if (DCI.isBeforeLegalize())
8932     return SDValue();
8933 
8934   SelectionDAG &DAG = DCI.DAG;
8935   EVT VT = N->getValueType(0);
8936   SDValue LHS = N->getOperand(0);
8937   SDValue RHS = N->getOperand(1);
8938 
8939 
8940   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8941   if (VT == MVT::i64 && CRHS) {
8942     if (SDValue Split
8943         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8944       return Split;
8945   }
8946 
8947   if (CRHS && VT == MVT::i32) {
8948     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8949     // nb = number of trailing zeroes in mask
8950     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8951     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8952     uint64_t Mask = CRHS->getZExtValue();
8953     unsigned Bits = countPopulation(Mask);
8954     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8955         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8956       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8957         unsigned Shift = CShift->getZExtValue();
8958         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8959         unsigned Offset = NB + Shift;
8960         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8961           SDLoc SL(N);
8962           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8963                                     LHS->getOperand(0),
8964                                     DAG.getConstant(Offset, SL, MVT::i32),
8965                                     DAG.getConstant(Bits, SL, MVT::i32));
8966           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8967           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8968                                     DAG.getValueType(NarrowVT));
8969           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8970                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8971           return Shl;
8972         }
8973       }
8974     }
8975 
8976     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8977     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8978         isa<ConstantSDNode>(LHS.getOperand(2))) {
8979       uint32_t Sel = getConstantPermuteMask(Mask);
8980       if (!Sel)
8981         return SDValue();
8982 
8983       // Select 0xc for all zero bytes
8984       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8985       SDLoc DL(N);
8986       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8987                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8988     }
8989   }
8990 
8991   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8992   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8993   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8994     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8995     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8996 
8997     SDValue X = LHS.getOperand(0);
8998     SDValue Y = RHS.getOperand(0);
8999     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9000       return SDValue();
9001 
9002     if (LCC == ISD::SETO) {
9003       if (X != LHS.getOperand(1))
9004         return SDValue();
9005 
9006       if (RCC == ISD::SETUNE) {
9007         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9008         if (!C1 || !C1->isInfinity() || C1->isNegative())
9009           return SDValue();
9010 
9011         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9012                               SIInstrFlags::N_SUBNORMAL |
9013                               SIInstrFlags::N_ZERO |
9014                               SIInstrFlags::P_ZERO |
9015                               SIInstrFlags::P_SUBNORMAL |
9016                               SIInstrFlags::P_NORMAL;
9017 
9018         static_assert(((~(SIInstrFlags::S_NAN |
9019                           SIInstrFlags::Q_NAN |
9020                           SIInstrFlags::N_INFINITY |
9021                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9022                       "mask not equal");
9023 
9024         SDLoc DL(N);
9025         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9026                            X, DAG.getConstant(Mask, DL, MVT::i32));
9027       }
9028     }
9029   }
9030 
9031   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9032     std::swap(LHS, RHS);
9033 
9034   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9035       RHS.hasOneUse()) {
9036     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9037     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9038     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9039     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9040     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9041         (RHS.getOperand(0) == LHS.getOperand(0) &&
9042          LHS.getOperand(0) == LHS.getOperand(1))) {
9043       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9044       unsigned NewMask = LCC == ISD::SETO ?
9045         Mask->getZExtValue() & ~OrdMask :
9046         Mask->getZExtValue() & OrdMask;
9047 
9048       SDLoc DL(N);
9049       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9050                          DAG.getConstant(NewMask, DL, MVT::i32));
9051     }
9052   }
9053 
9054   if (VT == MVT::i32 &&
9055       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9056     // and x, (sext cc from i1) => select cc, x, 0
9057     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9058       std::swap(LHS, RHS);
9059     if (isBoolSGPR(RHS.getOperand(0)))
9060       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9061                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9062   }
9063 
9064   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9065   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9066   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9067       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9068     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9069     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9070     if (LHSMask != ~0u && RHSMask != ~0u) {
9071       // Canonicalize the expression in an attempt to have fewer unique masks
9072       // and therefore fewer registers used to hold the masks.
9073       if (LHSMask > RHSMask) {
9074         std::swap(LHSMask, RHSMask);
9075         std::swap(LHS, RHS);
9076       }
9077 
9078       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9079       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9080       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9081       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9082 
9083       // Check of we need to combine values from two sources within a byte.
9084       if (!(LHSUsedLanes & RHSUsedLanes) &&
9085           // If we select high and lower word keep it for SDWA.
9086           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9087           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9088         // Each byte in each mask is either selector mask 0-3, or has higher
9089         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9090         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9091         // mask which is not 0xff wins. By anding both masks we have a correct
9092         // result except that 0x0c shall be corrected to give 0x0c only.
9093         uint32_t Mask = LHSMask & RHSMask;
9094         for (unsigned I = 0; I < 32; I += 8) {
9095           uint32_t ByteSel = 0xff << I;
9096           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9097             Mask &= (0x0c << I) & 0xffffffff;
9098         }
9099 
9100         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9101         // or 0x0c.
9102         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9103         SDLoc DL(N);
9104 
9105         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9106                            LHS.getOperand(0), RHS.getOperand(0),
9107                            DAG.getConstant(Sel, DL, MVT::i32));
9108       }
9109     }
9110   }
9111 
9112   return SDValue();
9113 }
9114 
9115 SDValue SITargetLowering::performOrCombine(SDNode *N,
9116                                            DAGCombinerInfo &DCI) const {
9117   SelectionDAG &DAG = DCI.DAG;
9118   SDValue LHS = N->getOperand(0);
9119   SDValue RHS = N->getOperand(1);
9120 
9121   EVT VT = N->getValueType(0);
9122   if (VT == MVT::i1) {
9123     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9124     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9125         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9126       SDValue Src = LHS.getOperand(0);
9127       if (Src != RHS.getOperand(0))
9128         return SDValue();
9129 
9130       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9131       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9132       if (!CLHS || !CRHS)
9133         return SDValue();
9134 
9135       // Only 10 bits are used.
9136       static const uint32_t MaxMask = 0x3ff;
9137 
9138       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9139       SDLoc DL(N);
9140       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9141                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9142     }
9143 
9144     return SDValue();
9145   }
9146 
9147   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9148   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9149       LHS.getOpcode() == AMDGPUISD::PERM &&
9150       isa<ConstantSDNode>(LHS.getOperand(2))) {
9151     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9152     if (!Sel)
9153       return SDValue();
9154 
9155     Sel |= LHS.getConstantOperandVal(2);
9156     SDLoc DL(N);
9157     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9158                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9159   }
9160 
9161   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9162   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9163   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9164       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9165     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9166     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9167     if (LHSMask != ~0u && RHSMask != ~0u) {
9168       // Canonicalize the expression in an attempt to have fewer unique masks
9169       // and therefore fewer registers used to hold the masks.
9170       if (LHSMask > RHSMask) {
9171         std::swap(LHSMask, RHSMask);
9172         std::swap(LHS, RHS);
9173       }
9174 
9175       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9176       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9177       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9178       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9179 
9180       // Check of we need to combine values from two sources within a byte.
9181       if (!(LHSUsedLanes & RHSUsedLanes) &&
9182           // If we select high and lower word keep it for SDWA.
9183           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9184           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9185         // Kill zero bytes selected by other mask. Zero value is 0xc.
9186         LHSMask &= ~RHSUsedLanes;
9187         RHSMask &= ~LHSUsedLanes;
9188         // Add 4 to each active LHS lane
9189         LHSMask |= LHSUsedLanes & 0x04040404;
9190         // Combine masks
9191         uint32_t Sel = LHSMask | RHSMask;
9192         SDLoc DL(N);
9193 
9194         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9195                            LHS.getOperand(0), RHS.getOperand(0),
9196                            DAG.getConstant(Sel, DL, MVT::i32));
9197       }
9198     }
9199   }
9200 
9201   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9202     return SDValue();
9203 
9204   // TODO: This could be a generic combine with a predicate for extracting the
9205   // high half of an integer being free.
9206 
9207   // (or i64:x, (zero_extend i32:y)) ->
9208   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9209   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9210       RHS.getOpcode() != ISD::ZERO_EXTEND)
9211     std::swap(LHS, RHS);
9212 
9213   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9214     SDValue ExtSrc = RHS.getOperand(0);
9215     EVT SrcVT = ExtSrc.getValueType();
9216     if (SrcVT == MVT::i32) {
9217       SDLoc SL(N);
9218       SDValue LowLHS, HiBits;
9219       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9220       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9221 
9222       DCI.AddToWorklist(LowOr.getNode());
9223       DCI.AddToWorklist(HiBits.getNode());
9224 
9225       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9226                                 LowOr, HiBits);
9227       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9228     }
9229   }
9230 
9231   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9232   if (CRHS) {
9233     if (SDValue Split
9234           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9235       return Split;
9236   }
9237 
9238   return SDValue();
9239 }
9240 
9241 SDValue SITargetLowering::performXorCombine(SDNode *N,
9242                                             DAGCombinerInfo &DCI) const {
9243   EVT VT = N->getValueType(0);
9244   if (VT != MVT::i64)
9245     return SDValue();
9246 
9247   SDValue LHS = N->getOperand(0);
9248   SDValue RHS = N->getOperand(1);
9249 
9250   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9251   if (CRHS) {
9252     if (SDValue Split
9253           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9254       return Split;
9255   }
9256 
9257   return SDValue();
9258 }
9259 
9260 // Instructions that will be lowered with a final instruction that zeros the
9261 // high result bits.
9262 // XXX - probably only need to list legal operations.
9263 static bool fp16SrcZerosHighBits(unsigned Opc) {
9264   switch (Opc) {
9265   case ISD::FADD:
9266   case ISD::FSUB:
9267   case ISD::FMUL:
9268   case ISD::FDIV:
9269   case ISD::FREM:
9270   case ISD::FMA:
9271   case ISD::FMAD:
9272   case ISD::FCANONICALIZE:
9273   case ISD::FP_ROUND:
9274   case ISD::UINT_TO_FP:
9275   case ISD::SINT_TO_FP:
9276   case ISD::FABS:
9277     // Fabs is lowered to a bit operation, but it's an and which will clear the
9278     // high bits anyway.
9279   case ISD::FSQRT:
9280   case ISD::FSIN:
9281   case ISD::FCOS:
9282   case ISD::FPOWI:
9283   case ISD::FPOW:
9284   case ISD::FLOG:
9285   case ISD::FLOG2:
9286   case ISD::FLOG10:
9287   case ISD::FEXP:
9288   case ISD::FEXP2:
9289   case ISD::FCEIL:
9290   case ISD::FTRUNC:
9291   case ISD::FRINT:
9292   case ISD::FNEARBYINT:
9293   case ISD::FROUND:
9294   case ISD::FFLOOR:
9295   case ISD::FMINNUM:
9296   case ISD::FMAXNUM:
9297   case AMDGPUISD::FRACT:
9298   case AMDGPUISD::CLAMP:
9299   case AMDGPUISD::COS_HW:
9300   case AMDGPUISD::SIN_HW:
9301   case AMDGPUISD::FMIN3:
9302   case AMDGPUISD::FMAX3:
9303   case AMDGPUISD::FMED3:
9304   case AMDGPUISD::FMAD_FTZ:
9305   case AMDGPUISD::RCP:
9306   case AMDGPUISD::RSQ:
9307   case AMDGPUISD::RCP_IFLAG:
9308   case AMDGPUISD::LDEXP:
9309     return true;
9310   default:
9311     // fcopysign, select and others may be lowered to 32-bit bit operations
9312     // which don't zero the high bits.
9313     return false;
9314   }
9315 }
9316 
9317 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9318                                                    DAGCombinerInfo &DCI) const {
9319   if (!Subtarget->has16BitInsts() ||
9320       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9321     return SDValue();
9322 
9323   EVT VT = N->getValueType(0);
9324   if (VT != MVT::i32)
9325     return SDValue();
9326 
9327   SDValue Src = N->getOperand(0);
9328   if (Src.getValueType() != MVT::i16)
9329     return SDValue();
9330 
9331   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9332   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9333   if (Src.getOpcode() == ISD::BITCAST) {
9334     SDValue BCSrc = Src.getOperand(0);
9335     if (BCSrc.getValueType() == MVT::f16 &&
9336         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9337       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9338   }
9339 
9340   return SDValue();
9341 }
9342 
9343 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9344                                                         DAGCombinerInfo &DCI)
9345                                                         const {
9346   SDValue Src = N->getOperand(0);
9347   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9348 
9349   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9350       VTSign->getVT() == MVT::i8) ||
9351       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9352       VTSign->getVT() == MVT::i16)) &&
9353       Src.hasOneUse()) {
9354     auto *M = cast<MemSDNode>(Src);
9355     SDValue Ops[] = {
9356       Src.getOperand(0), // Chain
9357       Src.getOperand(1), // rsrc
9358       Src.getOperand(2), // vindex
9359       Src.getOperand(3), // voffset
9360       Src.getOperand(4), // soffset
9361       Src.getOperand(5), // offset
9362       Src.getOperand(6),
9363       Src.getOperand(7)
9364     };
9365     // replace with BUFFER_LOAD_BYTE/SHORT
9366     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9367                                          Src.getOperand(0).getValueType());
9368     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9369                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9370     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9371                                                           ResList,
9372                                                           Ops, M->getMemoryVT(),
9373                                                           M->getMemOperand());
9374     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9375                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9376   }
9377   return SDValue();
9378 }
9379 
9380 SDValue SITargetLowering::performClassCombine(SDNode *N,
9381                                               DAGCombinerInfo &DCI) const {
9382   SelectionDAG &DAG = DCI.DAG;
9383   SDValue Mask = N->getOperand(1);
9384 
9385   // fp_class x, 0 -> false
9386   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9387     if (CMask->isNullValue())
9388       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9389   }
9390 
9391   if (N->getOperand(0).isUndef())
9392     return DAG.getUNDEF(MVT::i1);
9393 
9394   return SDValue();
9395 }
9396 
9397 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9398                                             DAGCombinerInfo &DCI) const {
9399   EVT VT = N->getValueType(0);
9400   SDValue N0 = N->getOperand(0);
9401 
9402   if (N0.isUndef())
9403     return N0;
9404 
9405   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9406                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9407     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9408                            N->getFlags());
9409   }
9410 
9411   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9412     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9413                            N0.getOperand(0), N->getFlags());
9414   }
9415 
9416   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9417 }
9418 
9419 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9420                                        unsigned MaxDepth) const {
9421   unsigned Opcode = Op.getOpcode();
9422   if (Opcode == ISD::FCANONICALIZE)
9423     return true;
9424 
9425   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9426     auto F = CFP->getValueAPF();
9427     if (F.isNaN() && F.isSignaling())
9428       return false;
9429     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9430   }
9431 
9432   // If source is a result of another standard FP operation it is already in
9433   // canonical form.
9434   if (MaxDepth == 0)
9435     return false;
9436 
9437   switch (Opcode) {
9438   // These will flush denorms if required.
9439   case ISD::FADD:
9440   case ISD::FSUB:
9441   case ISD::FMUL:
9442   case ISD::FCEIL:
9443   case ISD::FFLOOR:
9444   case ISD::FMA:
9445   case ISD::FMAD:
9446   case ISD::FSQRT:
9447   case ISD::FDIV:
9448   case ISD::FREM:
9449   case ISD::FP_ROUND:
9450   case ISD::FP_EXTEND:
9451   case AMDGPUISD::FMUL_LEGACY:
9452   case AMDGPUISD::FMAD_FTZ:
9453   case AMDGPUISD::RCP:
9454   case AMDGPUISD::RSQ:
9455   case AMDGPUISD::RSQ_CLAMP:
9456   case AMDGPUISD::RCP_LEGACY:
9457   case AMDGPUISD::RCP_IFLAG:
9458   case AMDGPUISD::DIV_SCALE:
9459   case AMDGPUISD::DIV_FMAS:
9460   case AMDGPUISD::DIV_FIXUP:
9461   case AMDGPUISD::FRACT:
9462   case AMDGPUISD::LDEXP:
9463   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9464   case AMDGPUISD::CVT_F32_UBYTE0:
9465   case AMDGPUISD::CVT_F32_UBYTE1:
9466   case AMDGPUISD::CVT_F32_UBYTE2:
9467   case AMDGPUISD::CVT_F32_UBYTE3:
9468     return true;
9469 
9470   // It can/will be lowered or combined as a bit operation.
9471   // Need to check their input recursively to handle.
9472   case ISD::FNEG:
9473   case ISD::FABS:
9474   case ISD::FCOPYSIGN:
9475     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9476 
9477   case ISD::FSIN:
9478   case ISD::FCOS:
9479   case ISD::FSINCOS:
9480     return Op.getValueType().getScalarType() != MVT::f16;
9481 
9482   case ISD::FMINNUM:
9483   case ISD::FMAXNUM:
9484   case ISD::FMINNUM_IEEE:
9485   case ISD::FMAXNUM_IEEE:
9486   case AMDGPUISD::CLAMP:
9487   case AMDGPUISD::FMED3:
9488   case AMDGPUISD::FMAX3:
9489   case AMDGPUISD::FMIN3: {
9490     // FIXME: Shouldn't treat the generic operations different based these.
9491     // However, we aren't really required to flush the result from
9492     // minnum/maxnum..
9493 
9494     // snans will be quieted, so we only need to worry about denormals.
9495     if (Subtarget->supportsMinMaxDenormModes() ||
9496         denormalsEnabledForType(DAG, Op.getValueType()))
9497       return true;
9498 
9499     // Flushing may be required.
9500     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9501     // targets need to check their input recursively.
9502 
9503     // FIXME: Does this apply with clamp? It's implemented with max.
9504     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9505       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9506         return false;
9507     }
9508 
9509     return true;
9510   }
9511   case ISD::SELECT: {
9512     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9513            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9514   }
9515   case ISD::BUILD_VECTOR: {
9516     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9517       SDValue SrcOp = Op.getOperand(i);
9518       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9519         return false;
9520     }
9521 
9522     return true;
9523   }
9524   case ISD::EXTRACT_VECTOR_ELT:
9525   case ISD::EXTRACT_SUBVECTOR: {
9526     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9527   }
9528   case ISD::INSERT_VECTOR_ELT: {
9529     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9530            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9531   }
9532   case ISD::UNDEF:
9533     // Could be anything.
9534     return false;
9535 
9536   case ISD::BITCAST: {
9537     // Hack round the mess we make when legalizing extract_vector_elt
9538     SDValue Src = Op.getOperand(0);
9539     if (Src.getValueType() == MVT::i16 &&
9540         Src.getOpcode() == ISD::TRUNCATE) {
9541       SDValue TruncSrc = Src.getOperand(0);
9542       if (TruncSrc.getValueType() == MVT::i32 &&
9543           TruncSrc.getOpcode() == ISD::BITCAST &&
9544           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9545         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9546       }
9547     }
9548 
9549     return false;
9550   }
9551   case ISD::INTRINSIC_WO_CHAIN: {
9552     unsigned IntrinsicID
9553       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9554     // TODO: Handle more intrinsics
9555     switch (IntrinsicID) {
9556     case Intrinsic::amdgcn_cvt_pkrtz:
9557     case Intrinsic::amdgcn_cubeid:
9558     case Intrinsic::amdgcn_frexp_mant:
9559     case Intrinsic::amdgcn_fdot2:
9560     case Intrinsic::amdgcn_rcp:
9561     case Intrinsic::amdgcn_rsq:
9562     case Intrinsic::amdgcn_rsq_clamp:
9563     case Intrinsic::amdgcn_rcp_legacy:
9564     case Intrinsic::amdgcn_rsq_legacy:
9565     case Intrinsic::amdgcn_trig_preop:
9566       return true;
9567     default:
9568       break;
9569     }
9570 
9571     LLVM_FALLTHROUGH;
9572   }
9573   default:
9574     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9575            DAG.isKnownNeverSNaN(Op);
9576   }
9577 
9578   llvm_unreachable("invalid operation");
9579 }
9580 
9581 // Constant fold canonicalize.
9582 SDValue SITargetLowering::getCanonicalConstantFP(
9583   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9584   // Flush denormals to 0 if not enabled.
9585   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9586     return DAG.getConstantFP(0.0, SL, VT);
9587 
9588   if (C.isNaN()) {
9589     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9590     if (C.isSignaling()) {
9591       // Quiet a signaling NaN.
9592       // FIXME: Is this supposed to preserve payload bits?
9593       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9594     }
9595 
9596     // Make sure it is the canonical NaN bitpattern.
9597     //
9598     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9599     // immediate?
9600     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9601       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9602   }
9603 
9604   // Already canonical.
9605   return DAG.getConstantFP(C, SL, VT);
9606 }
9607 
9608 static bool vectorEltWillFoldAway(SDValue Op) {
9609   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9610 }
9611 
9612 SDValue SITargetLowering::performFCanonicalizeCombine(
9613   SDNode *N,
9614   DAGCombinerInfo &DCI) const {
9615   SelectionDAG &DAG = DCI.DAG;
9616   SDValue N0 = N->getOperand(0);
9617   EVT VT = N->getValueType(0);
9618 
9619   // fcanonicalize undef -> qnan
9620   if (N0.isUndef()) {
9621     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9622     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9623   }
9624 
9625   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9626     EVT VT = N->getValueType(0);
9627     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9628   }
9629 
9630   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9631   //                                                   (fcanonicalize k)
9632   //
9633   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9634 
9635   // TODO: This could be better with wider vectors that will be split to v2f16,
9636   // and to consider uses since there aren't that many packed operations.
9637   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9638       isTypeLegal(MVT::v2f16)) {
9639     SDLoc SL(N);
9640     SDValue NewElts[2];
9641     SDValue Lo = N0.getOperand(0);
9642     SDValue Hi = N0.getOperand(1);
9643     EVT EltVT = Lo.getValueType();
9644 
9645     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9646       for (unsigned I = 0; I != 2; ++I) {
9647         SDValue Op = N0.getOperand(I);
9648         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9649           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9650                                               CFP->getValueAPF());
9651         } else if (Op.isUndef()) {
9652           // Handled below based on what the other operand is.
9653           NewElts[I] = Op;
9654         } else {
9655           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9656         }
9657       }
9658 
9659       // If one half is undef, and one is constant, perfer a splat vector rather
9660       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9661       // cheaper to use and may be free with a packed operation.
9662       if (NewElts[0].isUndef()) {
9663         if (isa<ConstantFPSDNode>(NewElts[1]))
9664           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9665             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9666       }
9667 
9668       if (NewElts[1].isUndef()) {
9669         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9670           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9671       }
9672 
9673       return DAG.getBuildVector(VT, SL, NewElts);
9674     }
9675   }
9676 
9677   unsigned SrcOpc = N0.getOpcode();
9678 
9679   // If it's free to do so, push canonicalizes further up the source, which may
9680   // find a canonical source.
9681   //
9682   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9683   // sNaNs.
9684   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9685     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9686     if (CRHS && N0.hasOneUse()) {
9687       SDLoc SL(N);
9688       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9689                                    N0.getOperand(0));
9690       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9691       DCI.AddToWorklist(Canon0.getNode());
9692 
9693       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9694     }
9695   }
9696 
9697   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9698 }
9699 
9700 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9701   switch (Opc) {
9702   case ISD::FMAXNUM:
9703   case ISD::FMAXNUM_IEEE:
9704     return AMDGPUISD::FMAX3;
9705   case ISD::SMAX:
9706     return AMDGPUISD::SMAX3;
9707   case ISD::UMAX:
9708     return AMDGPUISD::UMAX3;
9709   case ISD::FMINNUM:
9710   case ISD::FMINNUM_IEEE:
9711     return AMDGPUISD::FMIN3;
9712   case ISD::SMIN:
9713     return AMDGPUISD::SMIN3;
9714   case ISD::UMIN:
9715     return AMDGPUISD::UMIN3;
9716   default:
9717     llvm_unreachable("Not a min/max opcode");
9718   }
9719 }
9720 
9721 SDValue SITargetLowering::performIntMed3ImmCombine(
9722   SelectionDAG &DAG, const SDLoc &SL,
9723   SDValue Op0, SDValue Op1, bool Signed) const {
9724   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9725   if (!K1)
9726     return SDValue();
9727 
9728   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9729   if (!K0)
9730     return SDValue();
9731 
9732   if (Signed) {
9733     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9734       return SDValue();
9735   } else {
9736     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9737       return SDValue();
9738   }
9739 
9740   EVT VT = K0->getValueType(0);
9741   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9742   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9743     return DAG.getNode(Med3Opc, SL, VT,
9744                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9745   }
9746 
9747   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9748   MVT NVT = MVT::i32;
9749   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9750 
9751   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9752   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9753   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9754 
9755   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9756   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9757 }
9758 
9759 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9760   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9761     return C;
9762 
9763   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9764     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9765       return C;
9766   }
9767 
9768   return nullptr;
9769 }
9770 
9771 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9772                                                   const SDLoc &SL,
9773                                                   SDValue Op0,
9774                                                   SDValue Op1) const {
9775   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9776   if (!K1)
9777     return SDValue();
9778 
9779   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9780   if (!K0)
9781     return SDValue();
9782 
9783   // Ordered >= (although NaN inputs should have folded away by now).
9784   if (K0->getValueAPF() > K1->getValueAPF())
9785     return SDValue();
9786 
9787   const MachineFunction &MF = DAG.getMachineFunction();
9788   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9789 
9790   // TODO: Check IEEE bit enabled?
9791   EVT VT = Op0.getValueType();
9792   if (Info->getMode().DX10Clamp) {
9793     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9794     // hardware fmed3 behavior converting to a min.
9795     // FIXME: Should this be allowing -0.0?
9796     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9797       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9798   }
9799 
9800   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9801   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9802     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9803     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9804     // then give the other result, which is different from med3 with a NaN
9805     // input.
9806     SDValue Var = Op0.getOperand(0);
9807     if (!DAG.isKnownNeverSNaN(Var))
9808       return SDValue();
9809 
9810     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9811 
9812     if ((!K0->hasOneUse() ||
9813          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9814         (!K1->hasOneUse() ||
9815          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9816       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9817                          Var, SDValue(K0, 0), SDValue(K1, 0));
9818     }
9819   }
9820 
9821   return SDValue();
9822 }
9823 
9824 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9825                                                DAGCombinerInfo &DCI) const {
9826   SelectionDAG &DAG = DCI.DAG;
9827 
9828   EVT VT = N->getValueType(0);
9829   unsigned Opc = N->getOpcode();
9830   SDValue Op0 = N->getOperand(0);
9831   SDValue Op1 = N->getOperand(1);
9832 
9833   // Only do this if the inner op has one use since this will just increases
9834   // register pressure for no benefit.
9835 
9836   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9837       !VT.isVector() &&
9838       (VT == MVT::i32 || VT == MVT::f32 ||
9839        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9840     // max(max(a, b), c) -> max3(a, b, c)
9841     // min(min(a, b), c) -> min3(a, b, c)
9842     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9843       SDLoc DL(N);
9844       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9845                          DL,
9846                          N->getValueType(0),
9847                          Op0.getOperand(0),
9848                          Op0.getOperand(1),
9849                          Op1);
9850     }
9851 
9852     // Try commuted.
9853     // max(a, max(b, c)) -> max3(a, b, c)
9854     // min(a, min(b, c)) -> min3(a, b, c)
9855     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9856       SDLoc DL(N);
9857       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9858                          DL,
9859                          N->getValueType(0),
9860                          Op0,
9861                          Op1.getOperand(0),
9862                          Op1.getOperand(1));
9863     }
9864   }
9865 
9866   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9867   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9868     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9869       return Med3;
9870   }
9871 
9872   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9873     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9874       return Med3;
9875   }
9876 
9877   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9878   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9879        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9880        (Opc == AMDGPUISD::FMIN_LEGACY &&
9881         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9882       (VT == MVT::f32 || VT == MVT::f64 ||
9883        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9884        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9885       Op0.hasOneUse()) {
9886     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9887       return Res;
9888   }
9889 
9890   return SDValue();
9891 }
9892 
9893 static bool isClampZeroToOne(SDValue A, SDValue B) {
9894   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9895     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9896       // FIXME: Should this be allowing -0.0?
9897       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9898              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9899     }
9900   }
9901 
9902   return false;
9903 }
9904 
9905 // FIXME: Should only worry about snans for version with chain.
9906 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9907                                               DAGCombinerInfo &DCI) const {
9908   EVT VT = N->getValueType(0);
9909   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9910   // NaNs. With a NaN input, the order of the operands may change the result.
9911 
9912   SelectionDAG &DAG = DCI.DAG;
9913   SDLoc SL(N);
9914 
9915   SDValue Src0 = N->getOperand(0);
9916   SDValue Src1 = N->getOperand(1);
9917   SDValue Src2 = N->getOperand(2);
9918 
9919   if (isClampZeroToOne(Src0, Src1)) {
9920     // const_a, const_b, x -> clamp is safe in all cases including signaling
9921     // nans.
9922     // FIXME: Should this be allowing -0.0?
9923     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9924   }
9925 
9926   const MachineFunction &MF = DAG.getMachineFunction();
9927   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9928 
9929   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9930   // handling no dx10-clamp?
9931   if (Info->getMode().DX10Clamp) {
9932     // If NaNs is clamped to 0, we are free to reorder the inputs.
9933 
9934     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9935       std::swap(Src0, Src1);
9936 
9937     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9938       std::swap(Src1, Src2);
9939 
9940     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9941       std::swap(Src0, Src1);
9942 
9943     if (isClampZeroToOne(Src1, Src2))
9944       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9945   }
9946 
9947   return SDValue();
9948 }
9949 
9950 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9951                                                  DAGCombinerInfo &DCI) const {
9952   SDValue Src0 = N->getOperand(0);
9953   SDValue Src1 = N->getOperand(1);
9954   if (Src0.isUndef() && Src1.isUndef())
9955     return DCI.DAG.getUNDEF(N->getValueType(0));
9956   return SDValue();
9957 }
9958 
9959 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9960 // expanded into a set of cmp/select instructions.
9961 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9962                                                 unsigned NumElem,
9963                                                 bool IsDivergentIdx) {
9964   if (UseDivergentRegisterIndexing)
9965     return false;
9966 
9967   unsigned VecSize = EltSize * NumElem;
9968 
9969   // Sub-dword vectors of size 2 dword or less have better implementation.
9970   if (VecSize <= 64 && EltSize < 32)
9971     return false;
9972 
9973   // Always expand the rest of sub-dword instructions, otherwise it will be
9974   // lowered via memory.
9975   if (EltSize < 32)
9976     return true;
9977 
9978   // Always do this if var-idx is divergent, otherwise it will become a loop.
9979   if (IsDivergentIdx)
9980     return true;
9981 
9982   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9983   unsigned NumInsts = NumElem /* Number of compares */ +
9984                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9985   return NumInsts <= 16;
9986 }
9987 
9988 static bool shouldExpandVectorDynExt(SDNode *N) {
9989   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9990   if (isa<ConstantSDNode>(Idx))
9991     return false;
9992 
9993   SDValue Vec = N->getOperand(0);
9994   EVT VecVT = Vec.getValueType();
9995   EVT EltVT = VecVT.getVectorElementType();
9996   unsigned EltSize = EltVT.getSizeInBits();
9997   unsigned NumElem = VecVT.getVectorNumElements();
9998 
9999   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10000                                                     Idx->isDivergent());
10001 }
10002 
10003 SDValue SITargetLowering::performExtractVectorEltCombine(
10004   SDNode *N, DAGCombinerInfo &DCI) const {
10005   SDValue Vec = N->getOperand(0);
10006   SelectionDAG &DAG = DCI.DAG;
10007 
10008   EVT VecVT = Vec.getValueType();
10009   EVT EltVT = VecVT.getVectorElementType();
10010 
10011   if ((Vec.getOpcode() == ISD::FNEG ||
10012        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10013     SDLoc SL(N);
10014     EVT EltVT = N->getValueType(0);
10015     SDValue Idx = N->getOperand(1);
10016     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10017                               Vec.getOperand(0), Idx);
10018     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10019   }
10020 
10021   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10022   //    =>
10023   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10024   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10025   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10026   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10027     SDLoc SL(N);
10028     EVT EltVT = N->getValueType(0);
10029     SDValue Idx = N->getOperand(1);
10030     unsigned Opc = Vec.getOpcode();
10031 
10032     switch(Opc) {
10033     default:
10034       break;
10035       // TODO: Support other binary operations.
10036     case ISD::FADD:
10037     case ISD::FSUB:
10038     case ISD::FMUL:
10039     case ISD::ADD:
10040     case ISD::UMIN:
10041     case ISD::UMAX:
10042     case ISD::SMIN:
10043     case ISD::SMAX:
10044     case ISD::FMAXNUM:
10045     case ISD::FMINNUM:
10046     case ISD::FMAXNUM_IEEE:
10047     case ISD::FMINNUM_IEEE: {
10048       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10049                                  Vec.getOperand(0), Idx);
10050       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10051                                  Vec.getOperand(1), Idx);
10052 
10053       DCI.AddToWorklist(Elt0.getNode());
10054       DCI.AddToWorklist(Elt1.getNode());
10055       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10056     }
10057     }
10058   }
10059 
10060   unsigned VecSize = VecVT.getSizeInBits();
10061   unsigned EltSize = EltVT.getSizeInBits();
10062 
10063   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10064   if (::shouldExpandVectorDynExt(N)) {
10065     SDLoc SL(N);
10066     SDValue Idx = N->getOperand(1);
10067     SDValue V;
10068     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10069       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10070       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10071       if (I == 0)
10072         V = Elt;
10073       else
10074         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10075     }
10076     return V;
10077   }
10078 
10079   if (!DCI.isBeforeLegalize())
10080     return SDValue();
10081 
10082   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10083   // elements. This exposes more load reduction opportunities by replacing
10084   // multiple small extract_vector_elements with a single 32-bit extract.
10085   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10086   if (isa<MemSDNode>(Vec) &&
10087       EltSize <= 16 &&
10088       EltVT.isByteSized() &&
10089       VecSize > 32 &&
10090       VecSize % 32 == 0 &&
10091       Idx) {
10092     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10093 
10094     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10095     unsigned EltIdx = BitIndex / 32;
10096     unsigned LeftoverBitIdx = BitIndex % 32;
10097     SDLoc SL(N);
10098 
10099     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10100     DCI.AddToWorklist(Cast.getNode());
10101 
10102     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10103                               DAG.getConstant(EltIdx, SL, MVT::i32));
10104     DCI.AddToWorklist(Elt.getNode());
10105     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10106                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10107     DCI.AddToWorklist(Srl.getNode());
10108 
10109     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10110     DCI.AddToWorklist(Trunc.getNode());
10111     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10112   }
10113 
10114   return SDValue();
10115 }
10116 
10117 SDValue
10118 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10119                                                 DAGCombinerInfo &DCI) const {
10120   SDValue Vec = N->getOperand(0);
10121   SDValue Idx = N->getOperand(2);
10122   EVT VecVT = Vec.getValueType();
10123   EVT EltVT = VecVT.getVectorElementType();
10124 
10125   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10126   // => BUILD_VECTOR n x select (e, const-idx)
10127   if (!::shouldExpandVectorDynExt(N))
10128     return SDValue();
10129 
10130   SelectionDAG &DAG = DCI.DAG;
10131   SDLoc SL(N);
10132   SDValue Ins = N->getOperand(1);
10133   EVT IdxVT = Idx.getValueType();
10134 
10135   SmallVector<SDValue, 16> Ops;
10136   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10137     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10138     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10139     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10140     Ops.push_back(V);
10141   }
10142 
10143   return DAG.getBuildVector(VecVT, SL, Ops);
10144 }
10145 
10146 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10147                                           const SDNode *N0,
10148                                           const SDNode *N1) const {
10149   EVT VT = N0->getValueType(0);
10150 
10151   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10152   // support denormals ever.
10153   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10154        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10155         getSubtarget()->hasMadF16())) &&
10156        isOperationLegal(ISD::FMAD, VT))
10157     return ISD::FMAD;
10158 
10159   const TargetOptions &Options = DAG.getTarget().Options;
10160   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10161        (N0->getFlags().hasAllowContract() &&
10162         N1->getFlags().hasAllowContract())) &&
10163       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10164     return ISD::FMA;
10165   }
10166 
10167   return 0;
10168 }
10169 
10170 // For a reassociatable opcode perform:
10171 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10172 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10173                                                SelectionDAG &DAG) const {
10174   EVT VT = N->getValueType(0);
10175   if (VT != MVT::i32 && VT != MVT::i64)
10176     return SDValue();
10177 
10178   unsigned Opc = N->getOpcode();
10179   SDValue Op0 = N->getOperand(0);
10180   SDValue Op1 = N->getOperand(1);
10181 
10182   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10183     return SDValue();
10184 
10185   if (Op0->isDivergent())
10186     std::swap(Op0, Op1);
10187 
10188   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10189     return SDValue();
10190 
10191   SDValue Op2 = Op1.getOperand(1);
10192   Op1 = Op1.getOperand(0);
10193   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10194     return SDValue();
10195 
10196   if (Op1->isDivergent())
10197     std::swap(Op1, Op2);
10198 
10199   // If either operand is constant this will conflict with
10200   // DAGCombiner::ReassociateOps().
10201   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10202       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10203     return SDValue();
10204 
10205   SDLoc SL(N);
10206   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10207   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10208 }
10209 
10210 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10211                            EVT VT,
10212                            SDValue N0, SDValue N1, SDValue N2,
10213                            bool Signed) {
10214   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10215   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10216   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10217   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10218 }
10219 
10220 SDValue SITargetLowering::performAddCombine(SDNode *N,
10221                                             DAGCombinerInfo &DCI) const {
10222   SelectionDAG &DAG = DCI.DAG;
10223   EVT VT = N->getValueType(0);
10224   SDLoc SL(N);
10225   SDValue LHS = N->getOperand(0);
10226   SDValue RHS = N->getOperand(1);
10227 
10228   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10229       && Subtarget->hasMad64_32() &&
10230       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10231       VT.getScalarSizeInBits() <= 64) {
10232     if (LHS.getOpcode() != ISD::MUL)
10233       std::swap(LHS, RHS);
10234 
10235     SDValue MulLHS = LHS.getOperand(0);
10236     SDValue MulRHS = LHS.getOperand(1);
10237     SDValue AddRHS = RHS;
10238 
10239     // TODO: Maybe restrict if SGPR inputs.
10240     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10241         numBitsUnsigned(MulRHS, DAG) <= 32) {
10242       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10243       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10244       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10245       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10246     }
10247 
10248     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10249       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10250       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10251       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10252       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10253     }
10254 
10255     return SDValue();
10256   }
10257 
10258   if (SDValue V = reassociateScalarOps(N, DAG)) {
10259     return V;
10260   }
10261 
10262   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10263     return SDValue();
10264 
10265   // add x, zext (setcc) => addcarry x, 0, setcc
10266   // add x, sext (setcc) => subcarry x, 0, setcc
10267   unsigned Opc = LHS.getOpcode();
10268   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10269       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10270     std::swap(RHS, LHS);
10271 
10272   Opc = RHS.getOpcode();
10273   switch (Opc) {
10274   default: break;
10275   case ISD::ZERO_EXTEND:
10276   case ISD::SIGN_EXTEND:
10277   case ISD::ANY_EXTEND: {
10278     auto Cond = RHS.getOperand(0);
10279     // If this won't be a real VOPC output, we would still need to insert an
10280     // extra instruction anyway.
10281     if (!isBoolSGPR(Cond))
10282       break;
10283     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10284     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10285     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10286     return DAG.getNode(Opc, SL, VTList, Args);
10287   }
10288   case ISD::ADDCARRY: {
10289     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10290     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10291     if (!C || C->getZExtValue() != 0) break;
10292     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10293     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10294   }
10295   }
10296   return SDValue();
10297 }
10298 
10299 SDValue SITargetLowering::performSubCombine(SDNode *N,
10300                                             DAGCombinerInfo &DCI) const {
10301   SelectionDAG &DAG = DCI.DAG;
10302   EVT VT = N->getValueType(0);
10303 
10304   if (VT != MVT::i32)
10305     return SDValue();
10306 
10307   SDLoc SL(N);
10308   SDValue LHS = N->getOperand(0);
10309   SDValue RHS = N->getOperand(1);
10310 
10311   // sub x, zext (setcc) => subcarry x, 0, setcc
10312   // sub x, sext (setcc) => addcarry x, 0, setcc
10313   unsigned Opc = RHS.getOpcode();
10314   switch (Opc) {
10315   default: break;
10316   case ISD::ZERO_EXTEND:
10317   case ISD::SIGN_EXTEND:
10318   case ISD::ANY_EXTEND: {
10319     auto Cond = RHS.getOperand(0);
10320     // If this won't be a real VOPC output, we would still need to insert an
10321     // extra instruction anyway.
10322     if (!isBoolSGPR(Cond))
10323       break;
10324     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10325     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10326     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10327     return DAG.getNode(Opc, SL, VTList, Args);
10328   }
10329   }
10330 
10331   if (LHS.getOpcode() == ISD::SUBCARRY) {
10332     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10333     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10334     if (!C || !C->isNullValue())
10335       return SDValue();
10336     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10337     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10338   }
10339   return SDValue();
10340 }
10341 
10342 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10343   DAGCombinerInfo &DCI) const {
10344 
10345   if (N->getValueType(0) != MVT::i32)
10346     return SDValue();
10347 
10348   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10349   if (!C || C->getZExtValue() != 0)
10350     return SDValue();
10351 
10352   SelectionDAG &DAG = DCI.DAG;
10353   SDValue LHS = N->getOperand(0);
10354 
10355   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10356   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10357   unsigned LHSOpc = LHS.getOpcode();
10358   unsigned Opc = N->getOpcode();
10359   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10360       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10361     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10362     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10363   }
10364   return SDValue();
10365 }
10366 
10367 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10368                                              DAGCombinerInfo &DCI) const {
10369   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10370     return SDValue();
10371 
10372   SelectionDAG &DAG = DCI.DAG;
10373   EVT VT = N->getValueType(0);
10374 
10375   SDLoc SL(N);
10376   SDValue LHS = N->getOperand(0);
10377   SDValue RHS = N->getOperand(1);
10378 
10379   // These should really be instruction patterns, but writing patterns with
10380   // source modiifiers is a pain.
10381 
10382   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10383   if (LHS.getOpcode() == ISD::FADD) {
10384     SDValue A = LHS.getOperand(0);
10385     if (A == LHS.getOperand(1)) {
10386       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10387       if (FusedOp != 0) {
10388         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10389         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10390       }
10391     }
10392   }
10393 
10394   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10395   if (RHS.getOpcode() == ISD::FADD) {
10396     SDValue A = RHS.getOperand(0);
10397     if (A == RHS.getOperand(1)) {
10398       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10399       if (FusedOp != 0) {
10400         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10401         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10402       }
10403     }
10404   }
10405 
10406   return SDValue();
10407 }
10408 
10409 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10410                                              DAGCombinerInfo &DCI) const {
10411   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10412     return SDValue();
10413 
10414   SelectionDAG &DAG = DCI.DAG;
10415   SDLoc SL(N);
10416   EVT VT = N->getValueType(0);
10417   assert(!VT.isVector());
10418 
10419   // Try to get the fneg to fold into the source modifier. This undoes generic
10420   // DAG combines and folds them into the mad.
10421   //
10422   // Only do this if we are not trying to support denormals. v_mad_f32 does
10423   // not support denormals ever.
10424   SDValue LHS = N->getOperand(0);
10425   SDValue RHS = N->getOperand(1);
10426   if (LHS.getOpcode() == ISD::FADD) {
10427     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10428     SDValue A = LHS.getOperand(0);
10429     if (A == LHS.getOperand(1)) {
10430       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10431       if (FusedOp != 0){
10432         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10433         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10434 
10435         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10436       }
10437     }
10438   }
10439 
10440   if (RHS.getOpcode() == ISD::FADD) {
10441     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10442 
10443     SDValue A = RHS.getOperand(0);
10444     if (A == RHS.getOperand(1)) {
10445       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10446       if (FusedOp != 0){
10447         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10448         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10449       }
10450     }
10451   }
10452 
10453   return SDValue();
10454 }
10455 
10456 SDValue SITargetLowering::performFMACombine(SDNode *N,
10457                                             DAGCombinerInfo &DCI) const {
10458   SelectionDAG &DAG = DCI.DAG;
10459   EVT VT = N->getValueType(0);
10460   SDLoc SL(N);
10461 
10462   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10463     return SDValue();
10464 
10465   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10466   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10467   SDValue Op1 = N->getOperand(0);
10468   SDValue Op2 = N->getOperand(1);
10469   SDValue FMA = N->getOperand(2);
10470 
10471   if (FMA.getOpcode() != ISD::FMA ||
10472       Op1.getOpcode() != ISD::FP_EXTEND ||
10473       Op2.getOpcode() != ISD::FP_EXTEND)
10474     return SDValue();
10475 
10476   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10477   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10478   // is sufficient to allow generaing fdot2.
10479   const TargetOptions &Options = DAG.getTarget().Options;
10480   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10481       (N->getFlags().hasAllowContract() &&
10482        FMA->getFlags().hasAllowContract())) {
10483     Op1 = Op1.getOperand(0);
10484     Op2 = Op2.getOperand(0);
10485     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10486         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10487       return SDValue();
10488 
10489     SDValue Vec1 = Op1.getOperand(0);
10490     SDValue Idx1 = Op1.getOperand(1);
10491     SDValue Vec2 = Op2.getOperand(0);
10492 
10493     SDValue FMAOp1 = FMA.getOperand(0);
10494     SDValue FMAOp2 = FMA.getOperand(1);
10495     SDValue FMAAcc = FMA.getOperand(2);
10496 
10497     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10498         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10499       return SDValue();
10500 
10501     FMAOp1 = FMAOp1.getOperand(0);
10502     FMAOp2 = FMAOp2.getOperand(0);
10503     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10504         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10505       return SDValue();
10506 
10507     SDValue Vec3 = FMAOp1.getOperand(0);
10508     SDValue Vec4 = FMAOp2.getOperand(0);
10509     SDValue Idx2 = FMAOp1.getOperand(1);
10510 
10511     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10512         // Idx1 and Idx2 cannot be the same.
10513         Idx1 == Idx2)
10514       return SDValue();
10515 
10516     if (Vec1 == Vec2 || Vec3 == Vec4)
10517       return SDValue();
10518 
10519     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10520       return SDValue();
10521 
10522     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10523         (Vec1 == Vec4 && Vec2 == Vec3)) {
10524       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10525                          DAG.getTargetConstant(0, SL, MVT::i1));
10526     }
10527   }
10528   return SDValue();
10529 }
10530 
10531 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10532                                               DAGCombinerInfo &DCI) const {
10533   SelectionDAG &DAG = DCI.DAG;
10534   SDLoc SL(N);
10535 
10536   SDValue LHS = N->getOperand(0);
10537   SDValue RHS = N->getOperand(1);
10538   EVT VT = LHS.getValueType();
10539   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10540 
10541   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10542   if (!CRHS) {
10543     CRHS = dyn_cast<ConstantSDNode>(LHS);
10544     if (CRHS) {
10545       std::swap(LHS, RHS);
10546       CC = getSetCCSwappedOperands(CC);
10547     }
10548   }
10549 
10550   if (CRHS) {
10551     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10552         isBoolSGPR(LHS.getOperand(0))) {
10553       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10554       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10555       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10556       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10557       if ((CRHS->isAllOnesValue() &&
10558            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10559           (CRHS->isNullValue() &&
10560            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10561         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10562                            DAG.getConstant(-1, SL, MVT::i1));
10563       if ((CRHS->isAllOnesValue() &&
10564            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10565           (CRHS->isNullValue() &&
10566            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10567         return LHS.getOperand(0);
10568     }
10569 
10570     uint64_t CRHSVal = CRHS->getZExtValue();
10571     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10572         LHS.getOpcode() == ISD::SELECT &&
10573         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10574         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10575         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10576         isBoolSGPR(LHS.getOperand(0))) {
10577       // Given CT != FT:
10578       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10579       // setcc (select cc, CT, CF), CF, ne => cc
10580       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10581       // setcc (select cc, CT, CF), CT, eq => cc
10582       uint64_t CT = LHS.getConstantOperandVal(1);
10583       uint64_t CF = LHS.getConstantOperandVal(2);
10584 
10585       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10586           (CT == CRHSVal && CC == ISD::SETNE))
10587         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10588                            DAG.getConstant(-1, SL, MVT::i1));
10589       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10590           (CT == CRHSVal && CC == ISD::SETEQ))
10591         return LHS.getOperand(0);
10592     }
10593   }
10594 
10595   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10596                                            VT != MVT::f16))
10597     return SDValue();
10598 
10599   // Match isinf/isfinite pattern
10600   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10601   // (fcmp one (fabs x), inf) -> (fp_class x,
10602   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10603   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10604     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10605     if (!CRHS)
10606       return SDValue();
10607 
10608     const APFloat &APF = CRHS->getValueAPF();
10609     if (APF.isInfinity() && !APF.isNegative()) {
10610       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10611                                  SIInstrFlags::N_INFINITY;
10612       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10613                                     SIInstrFlags::P_ZERO |
10614                                     SIInstrFlags::N_NORMAL |
10615                                     SIInstrFlags::P_NORMAL |
10616                                     SIInstrFlags::N_SUBNORMAL |
10617                                     SIInstrFlags::P_SUBNORMAL;
10618       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10619       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10620                          DAG.getConstant(Mask, SL, MVT::i32));
10621     }
10622   }
10623 
10624   return SDValue();
10625 }
10626 
10627 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10628                                                      DAGCombinerInfo &DCI) const {
10629   SelectionDAG &DAG = DCI.DAG;
10630   SDLoc SL(N);
10631   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10632 
10633   SDValue Src = N->getOperand(0);
10634   SDValue Shift = N->getOperand(0);
10635 
10636   // TODO: Extend type shouldn't matter (assuming legal types).
10637   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10638     Shift = Shift.getOperand(0);
10639 
10640   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10641     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10642     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10643     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10644     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10645     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10646     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10647       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10648                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10649 
10650       unsigned ShiftOffset = 8 * Offset;
10651       if (Shift.getOpcode() == ISD::SHL)
10652         ShiftOffset -= C->getZExtValue();
10653       else
10654         ShiftOffset += C->getZExtValue();
10655 
10656       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10657         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10658                            MVT::f32, Shift);
10659       }
10660     }
10661   }
10662 
10663   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10664   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10665   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10666     // We simplified Src. If this node is not dead, visit it again so it is
10667     // folded properly.
10668     if (N->getOpcode() != ISD::DELETED_NODE)
10669       DCI.AddToWorklist(N);
10670     return SDValue(N, 0);
10671   }
10672 
10673   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10674   if (SDValue DemandedSrc =
10675           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10676     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10677 
10678   return SDValue();
10679 }
10680 
10681 SDValue SITargetLowering::performClampCombine(SDNode *N,
10682                                               DAGCombinerInfo &DCI) const {
10683   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10684   if (!CSrc)
10685     return SDValue();
10686 
10687   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10688   const APFloat &F = CSrc->getValueAPF();
10689   APFloat Zero = APFloat::getZero(F.getSemantics());
10690   if (F < Zero ||
10691       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10692     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10693   }
10694 
10695   APFloat One(F.getSemantics(), "1.0");
10696   if (F > One)
10697     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10698 
10699   return SDValue(CSrc, 0);
10700 }
10701 
10702 
10703 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10704                                             DAGCombinerInfo &DCI) const {
10705   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10706     return SDValue();
10707   switch (N->getOpcode()) {
10708   case ISD::ADD:
10709     return performAddCombine(N, DCI);
10710   case ISD::SUB:
10711     return performSubCombine(N, DCI);
10712   case ISD::ADDCARRY:
10713   case ISD::SUBCARRY:
10714     return performAddCarrySubCarryCombine(N, DCI);
10715   case ISD::FADD:
10716     return performFAddCombine(N, DCI);
10717   case ISD::FSUB:
10718     return performFSubCombine(N, DCI);
10719   case ISD::SETCC:
10720     return performSetCCCombine(N, DCI);
10721   case ISD::FMAXNUM:
10722   case ISD::FMINNUM:
10723   case ISD::FMAXNUM_IEEE:
10724   case ISD::FMINNUM_IEEE:
10725   case ISD::SMAX:
10726   case ISD::SMIN:
10727   case ISD::UMAX:
10728   case ISD::UMIN:
10729   case AMDGPUISD::FMIN_LEGACY:
10730   case AMDGPUISD::FMAX_LEGACY:
10731     return performMinMaxCombine(N, DCI);
10732   case ISD::FMA:
10733     return performFMACombine(N, DCI);
10734   case ISD::AND:
10735     return performAndCombine(N, DCI);
10736   case ISD::OR:
10737     return performOrCombine(N, DCI);
10738   case ISD::XOR:
10739     return performXorCombine(N, DCI);
10740   case ISD::ZERO_EXTEND:
10741     return performZeroExtendCombine(N, DCI);
10742   case ISD::SIGN_EXTEND_INREG:
10743     return performSignExtendInRegCombine(N , DCI);
10744   case AMDGPUISD::FP_CLASS:
10745     return performClassCombine(N, DCI);
10746   case ISD::FCANONICALIZE:
10747     return performFCanonicalizeCombine(N, DCI);
10748   case AMDGPUISD::RCP:
10749     return performRcpCombine(N, DCI);
10750   case AMDGPUISD::FRACT:
10751   case AMDGPUISD::RSQ:
10752   case AMDGPUISD::RCP_LEGACY:
10753   case AMDGPUISD::RCP_IFLAG:
10754   case AMDGPUISD::RSQ_CLAMP:
10755   case AMDGPUISD::LDEXP: {
10756     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10757     SDValue Src = N->getOperand(0);
10758     if (Src.isUndef())
10759       return Src;
10760     break;
10761   }
10762   case ISD::SINT_TO_FP:
10763   case ISD::UINT_TO_FP:
10764     return performUCharToFloatCombine(N, DCI);
10765   case AMDGPUISD::CVT_F32_UBYTE0:
10766   case AMDGPUISD::CVT_F32_UBYTE1:
10767   case AMDGPUISD::CVT_F32_UBYTE2:
10768   case AMDGPUISD::CVT_F32_UBYTE3:
10769     return performCvtF32UByteNCombine(N, DCI);
10770   case AMDGPUISD::FMED3:
10771     return performFMed3Combine(N, DCI);
10772   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10773     return performCvtPkRTZCombine(N, DCI);
10774   case AMDGPUISD::CLAMP:
10775     return performClampCombine(N, DCI);
10776   case ISD::SCALAR_TO_VECTOR: {
10777     SelectionDAG &DAG = DCI.DAG;
10778     EVT VT = N->getValueType(0);
10779 
10780     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10781     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10782       SDLoc SL(N);
10783       SDValue Src = N->getOperand(0);
10784       EVT EltVT = Src.getValueType();
10785       if (EltVT == MVT::f16)
10786         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10787 
10788       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10789       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10790     }
10791 
10792     break;
10793   }
10794   case ISD::EXTRACT_VECTOR_ELT:
10795     return performExtractVectorEltCombine(N, DCI);
10796   case ISD::INSERT_VECTOR_ELT:
10797     return performInsertVectorEltCombine(N, DCI);
10798   case ISD::LOAD: {
10799     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10800       return Widended;
10801     LLVM_FALLTHROUGH;
10802   }
10803   default: {
10804     if (!DCI.isBeforeLegalize()) {
10805       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10806         return performMemSDNodeCombine(MemNode, DCI);
10807     }
10808 
10809     break;
10810   }
10811   }
10812 
10813   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10814 }
10815 
10816 /// Helper function for adjustWritemask
10817 static unsigned SubIdx2Lane(unsigned Idx) {
10818   switch (Idx) {
10819   default: return 0;
10820   case AMDGPU::sub0: return 0;
10821   case AMDGPU::sub1: return 1;
10822   case AMDGPU::sub2: return 2;
10823   case AMDGPU::sub3: return 3;
10824   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10825   }
10826 }
10827 
10828 /// Adjust the writemask of MIMG instructions
10829 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10830                                           SelectionDAG &DAG) const {
10831   unsigned Opcode = Node->getMachineOpcode();
10832 
10833   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10834   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10835   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10836     return Node; // not implemented for D16
10837 
10838   SDNode *Users[5] = { nullptr };
10839   unsigned Lane = 0;
10840   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10841   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10842   unsigned NewDmask = 0;
10843   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10844   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10845   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10846                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10847   unsigned TFCLane = 0;
10848   bool HasChain = Node->getNumValues() > 1;
10849 
10850   if (OldDmask == 0) {
10851     // These are folded out, but on the chance it happens don't assert.
10852     return Node;
10853   }
10854 
10855   unsigned OldBitsSet = countPopulation(OldDmask);
10856   // Work out which is the TFE/LWE lane if that is enabled.
10857   if (UsesTFC) {
10858     TFCLane = OldBitsSet;
10859   }
10860 
10861   // Try to figure out the used register components
10862   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10863        I != E; ++I) {
10864 
10865     // Don't look at users of the chain.
10866     if (I.getUse().getResNo() != 0)
10867       continue;
10868 
10869     // Abort if we can't understand the usage
10870     if (!I->isMachineOpcode() ||
10871         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10872       return Node;
10873 
10874     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10875     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10876     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10877     // set, etc.
10878     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10879 
10880     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10881     if (UsesTFC && Lane == TFCLane) {
10882       Users[Lane] = *I;
10883     } else {
10884       // Set which texture component corresponds to the lane.
10885       unsigned Comp;
10886       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10887         Comp = countTrailingZeros(Dmask);
10888         Dmask &= ~(1 << Comp);
10889       }
10890 
10891       // Abort if we have more than one user per component.
10892       if (Users[Lane])
10893         return Node;
10894 
10895       Users[Lane] = *I;
10896       NewDmask |= 1 << Comp;
10897     }
10898   }
10899 
10900   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10901   bool NoChannels = !NewDmask;
10902   if (NoChannels) {
10903     if (!UsesTFC) {
10904       // No uses of the result and not using TFC. Then do nothing.
10905       return Node;
10906     }
10907     // If the original dmask has one channel - then nothing to do
10908     if (OldBitsSet == 1)
10909       return Node;
10910     // Use an arbitrary dmask - required for the instruction to work
10911     NewDmask = 1;
10912   }
10913   // Abort if there's no change
10914   if (NewDmask == OldDmask)
10915     return Node;
10916 
10917   unsigned BitsSet = countPopulation(NewDmask);
10918 
10919   // Check for TFE or LWE - increase the number of channels by one to account
10920   // for the extra return value
10921   // This will need adjustment for D16 if this is also included in
10922   // adjustWriteMask (this function) but at present D16 are excluded.
10923   unsigned NewChannels = BitsSet + UsesTFC;
10924 
10925   int NewOpcode =
10926       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10927   assert(NewOpcode != -1 &&
10928          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10929          "failed to find equivalent MIMG op");
10930 
10931   // Adjust the writemask in the node
10932   SmallVector<SDValue, 12> Ops;
10933   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10934   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10935   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10936 
10937   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10938 
10939   MVT ResultVT = NewChannels == 1 ?
10940     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10941                            NewChannels == 5 ? 8 : NewChannels);
10942   SDVTList NewVTList = HasChain ?
10943     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10944 
10945 
10946   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10947                                               NewVTList, Ops);
10948 
10949   if (HasChain) {
10950     // Update chain.
10951     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10952     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10953   }
10954 
10955   if (NewChannels == 1) {
10956     assert(Node->hasNUsesOfValue(1, 0));
10957     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10958                                       SDLoc(Node), Users[Lane]->getValueType(0),
10959                                       SDValue(NewNode, 0));
10960     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10961     return nullptr;
10962   }
10963 
10964   // Update the users of the node with the new indices
10965   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10966     SDNode *User = Users[i];
10967     if (!User) {
10968       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10969       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10970       if (i || !NoChannels)
10971         continue;
10972     } else {
10973       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10974       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10975     }
10976 
10977     switch (Idx) {
10978     default: break;
10979     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10980     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10981     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10982     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10983     }
10984   }
10985 
10986   DAG.RemoveDeadNode(Node);
10987   return nullptr;
10988 }
10989 
10990 static bool isFrameIndexOp(SDValue Op) {
10991   if (Op.getOpcode() == ISD::AssertZext)
10992     Op = Op.getOperand(0);
10993 
10994   return isa<FrameIndexSDNode>(Op);
10995 }
10996 
10997 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10998 /// with frame index operands.
10999 /// LLVM assumes that inputs are to these instructions are registers.
11000 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11001                                                         SelectionDAG &DAG) const {
11002   if (Node->getOpcode() == ISD::CopyToReg) {
11003     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11004     SDValue SrcVal = Node->getOperand(2);
11005 
11006     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11007     // to try understanding copies to physical registers.
11008     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11009       SDLoc SL(Node);
11010       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11011       SDValue VReg = DAG.getRegister(
11012         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11013 
11014       SDNode *Glued = Node->getGluedNode();
11015       SDValue ToVReg
11016         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11017                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11018       SDValue ToResultReg
11019         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11020                            VReg, ToVReg.getValue(1));
11021       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11022       DAG.RemoveDeadNode(Node);
11023       return ToResultReg.getNode();
11024     }
11025   }
11026 
11027   SmallVector<SDValue, 8> Ops;
11028   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11029     if (!isFrameIndexOp(Node->getOperand(i))) {
11030       Ops.push_back(Node->getOperand(i));
11031       continue;
11032     }
11033 
11034     SDLoc DL(Node);
11035     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11036                                      Node->getOperand(i).getValueType(),
11037                                      Node->getOperand(i)), 0));
11038   }
11039 
11040   return DAG.UpdateNodeOperands(Node, Ops);
11041 }
11042 
11043 /// Fold the instructions after selecting them.
11044 /// Returns null if users were already updated.
11045 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11046                                           SelectionDAG &DAG) const {
11047   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11048   unsigned Opcode = Node->getMachineOpcode();
11049 
11050   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11051       !TII->isGather4(Opcode) &&
11052       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11053     return adjustWritemask(Node, DAG);
11054   }
11055 
11056   if (Opcode == AMDGPU::INSERT_SUBREG ||
11057       Opcode == AMDGPU::REG_SEQUENCE) {
11058     legalizeTargetIndependentNode(Node, DAG);
11059     return Node;
11060   }
11061 
11062   switch (Opcode) {
11063   case AMDGPU::V_DIV_SCALE_F32:
11064   case AMDGPU::V_DIV_SCALE_F64: {
11065     // Satisfy the operand register constraint when one of the inputs is
11066     // undefined. Ordinarily each undef value will have its own implicit_def of
11067     // a vreg, so force these to use a single register.
11068     SDValue Src0 = Node->getOperand(0);
11069     SDValue Src1 = Node->getOperand(1);
11070     SDValue Src2 = Node->getOperand(2);
11071 
11072     if ((Src0.isMachineOpcode() &&
11073          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11074         (Src0 == Src1 || Src0 == Src2))
11075       break;
11076 
11077     MVT VT = Src0.getValueType().getSimpleVT();
11078     const TargetRegisterClass *RC =
11079         getRegClassFor(VT, Src0.getNode()->isDivergent());
11080 
11081     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11082     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11083 
11084     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11085                                       UndefReg, Src0, SDValue());
11086 
11087     // src0 must be the same register as src1 or src2, even if the value is
11088     // undefined, so make sure we don't violate this constraint.
11089     if (Src0.isMachineOpcode() &&
11090         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11091       if (Src1.isMachineOpcode() &&
11092           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11093         Src0 = Src1;
11094       else if (Src2.isMachineOpcode() &&
11095                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11096         Src0 = Src2;
11097       else {
11098         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11099         Src0 = UndefReg;
11100         Src1 = UndefReg;
11101       }
11102     } else
11103       break;
11104 
11105     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
11106     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
11107       Ops.push_back(Node->getOperand(I));
11108 
11109     Ops.push_back(ImpDef.getValue(1));
11110     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11111   }
11112   default:
11113     break;
11114   }
11115 
11116   return Node;
11117 }
11118 
11119 /// Assign the register class depending on the number of
11120 /// bits set in the writemask
11121 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11122                                                      SDNode *Node) const {
11123   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11124 
11125   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11126 
11127   if (TII->isVOP3(MI.getOpcode())) {
11128     // Make sure constant bus requirements are respected.
11129     TII->legalizeOperandsVOP3(MRI, MI);
11130 
11131     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11132     // This saves a chain-copy of registers and better ballance register
11133     // use between vgpr and agpr as agpr tuples tend to be big.
11134     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11135       unsigned Opc = MI.getOpcode();
11136       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11137       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11138                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11139         if (I == -1)
11140           break;
11141         MachineOperand &Op = MI.getOperand(I);
11142         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11143              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11144             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11145           continue;
11146         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11147         if (!Src || !Src->isCopy() ||
11148             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11149           continue;
11150         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11151         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11152         // All uses of agpr64 and agpr32 can also accept vgpr except for
11153         // v_accvgpr_read, but we do not produce agpr reads during selection,
11154         // so no use checks are needed.
11155         MRI.setRegClass(Op.getReg(), NewRC);
11156       }
11157     }
11158 
11159     return;
11160   }
11161 
11162   // Replace unused atomics with the no return version.
11163   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11164   if (NoRetAtomicOp != -1) {
11165     if (!Node->hasAnyUseOfValue(0)) {
11166       MI.setDesc(TII->get(NoRetAtomicOp));
11167       MI.RemoveOperand(0);
11168       return;
11169     }
11170 
11171     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11172     // instruction, because the return type of these instructions is a vec2 of
11173     // the memory type, so it can be tied to the input operand.
11174     // This means these instructions always have a use, so we need to add a
11175     // special case to check if the atomic has only one extract_subreg use,
11176     // which itself has no uses.
11177     if ((Node->hasNUsesOfValue(1, 0) &&
11178          Node->use_begin()->isMachineOpcode() &&
11179          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11180          !Node->use_begin()->hasAnyUseOfValue(0))) {
11181       Register Def = MI.getOperand(0).getReg();
11182 
11183       // Change this into a noret atomic.
11184       MI.setDesc(TII->get(NoRetAtomicOp));
11185       MI.RemoveOperand(0);
11186 
11187       // If we only remove the def operand from the atomic instruction, the
11188       // extract_subreg will be left with a use of a vreg without a def.
11189       // So we need to insert an implicit_def to avoid machine verifier
11190       // errors.
11191       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11192               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11193     }
11194     return;
11195   }
11196 }
11197 
11198 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11199                               uint64_t Val) {
11200   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11201   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11202 }
11203 
11204 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11205                                                 const SDLoc &DL,
11206                                                 SDValue Ptr) const {
11207   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11208 
11209   // Build the half of the subregister with the constants before building the
11210   // full 128-bit register. If we are building multiple resource descriptors,
11211   // this will allow CSEing of the 2-component register.
11212   const SDValue Ops0[] = {
11213     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11214     buildSMovImm32(DAG, DL, 0),
11215     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11216     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11217     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11218   };
11219 
11220   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11221                                                 MVT::v2i32, Ops0), 0);
11222 
11223   // Combine the constants and the pointer.
11224   const SDValue Ops1[] = {
11225     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11226     Ptr,
11227     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11228     SubRegHi,
11229     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11230   };
11231 
11232   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11233 }
11234 
11235 /// Return a resource descriptor with the 'Add TID' bit enabled
11236 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11237 ///        of the resource descriptor) to create an offset, which is added to
11238 ///        the resource pointer.
11239 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11240                                            SDValue Ptr, uint32_t RsrcDword1,
11241                                            uint64_t RsrcDword2And3) const {
11242   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11243   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11244   if (RsrcDword1) {
11245     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11246                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11247                     0);
11248   }
11249 
11250   SDValue DataLo = buildSMovImm32(DAG, DL,
11251                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11252   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11253 
11254   const SDValue Ops[] = {
11255     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11256     PtrLo,
11257     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11258     PtrHi,
11259     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11260     DataLo,
11261     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11262     DataHi,
11263     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11264   };
11265 
11266   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11267 }
11268 
11269 //===----------------------------------------------------------------------===//
11270 //                         SI Inline Assembly Support
11271 //===----------------------------------------------------------------------===//
11272 
11273 std::pair<unsigned, const TargetRegisterClass *>
11274 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11275                                                StringRef Constraint,
11276                                                MVT VT) const {
11277   const TargetRegisterClass *RC = nullptr;
11278   if (Constraint.size() == 1) {
11279     const unsigned BitWidth = VT.getSizeInBits();
11280     switch (Constraint[0]) {
11281     default:
11282       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11283     case 's':
11284     case 'r':
11285       switch (BitWidth) {
11286       case 16:
11287         RC = &AMDGPU::SReg_32RegClass;
11288         break;
11289       case 64:
11290         RC = &AMDGPU::SGPR_64RegClass;
11291         break;
11292       default:
11293         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11294         if (!RC)
11295           return std::make_pair(0U, nullptr);
11296         break;
11297       }
11298       break;
11299     case 'v':
11300       switch (BitWidth) {
11301       case 16:
11302         RC = &AMDGPU::VGPR_32RegClass;
11303         break;
11304       default:
11305         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11306         if (!RC)
11307           return std::make_pair(0U, nullptr);
11308         break;
11309       }
11310       break;
11311     case 'a':
11312       if (!Subtarget->hasMAIInsts())
11313         break;
11314       switch (BitWidth) {
11315       case 16:
11316         RC = &AMDGPU::AGPR_32RegClass;
11317         break;
11318       default:
11319         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11320         if (!RC)
11321           return std::make_pair(0U, nullptr);
11322         break;
11323       }
11324       break;
11325     }
11326     // We actually support i128, i16 and f16 as inline parameters
11327     // even if they are not reported as legal
11328     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11329                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11330       return std::make_pair(0U, RC);
11331   }
11332 
11333   if (Constraint.size() > 1) {
11334     if (Constraint[1] == 'v') {
11335       RC = &AMDGPU::VGPR_32RegClass;
11336     } else if (Constraint[1] == 's') {
11337       RC = &AMDGPU::SGPR_32RegClass;
11338     } else if (Constraint[1] == 'a') {
11339       RC = &AMDGPU::AGPR_32RegClass;
11340     }
11341 
11342     if (RC) {
11343       uint32_t Idx;
11344       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11345       if (!Failed && Idx < RC->getNumRegs())
11346         return std::make_pair(RC->getRegister(Idx), RC);
11347     }
11348   }
11349 
11350   // FIXME: Returns VS_32 for physical SGPR constraints
11351   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11352 }
11353 
11354 static bool isImmConstraint(StringRef Constraint) {
11355   if (Constraint.size() == 1) {
11356     switch (Constraint[0]) {
11357     default: break;
11358     case 'I':
11359     case 'J':
11360     case 'A':
11361     case 'B':
11362     case 'C':
11363       return true;
11364     }
11365   } else if (Constraint == "DA" ||
11366              Constraint == "DB") {
11367     return true;
11368   }
11369   return false;
11370 }
11371 
11372 SITargetLowering::ConstraintType
11373 SITargetLowering::getConstraintType(StringRef Constraint) const {
11374   if (Constraint.size() == 1) {
11375     switch (Constraint[0]) {
11376     default: break;
11377     case 's':
11378     case 'v':
11379     case 'a':
11380       return C_RegisterClass;
11381     }
11382   }
11383   if (isImmConstraint(Constraint)) {
11384     return C_Other;
11385   }
11386   return TargetLowering::getConstraintType(Constraint);
11387 }
11388 
11389 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11390   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11391     Val = Val & maskTrailingOnes<uint64_t>(Size);
11392   }
11393   return Val;
11394 }
11395 
11396 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11397                                                     std::string &Constraint,
11398                                                     std::vector<SDValue> &Ops,
11399                                                     SelectionDAG &DAG) const {
11400   if (isImmConstraint(Constraint)) {
11401     uint64_t Val;
11402     if (getAsmOperandConstVal(Op, Val) &&
11403         checkAsmConstraintVal(Op, Constraint, Val)) {
11404       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11405       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11406     }
11407   } else {
11408     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11409   }
11410 }
11411 
11412 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11413   unsigned Size = Op.getScalarValueSizeInBits();
11414   if (Size > 64)
11415     return false;
11416 
11417   if (Size == 16 && !Subtarget->has16BitInsts())
11418     return false;
11419 
11420   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11421     Val = C->getSExtValue();
11422     return true;
11423   }
11424   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11425     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11426     return true;
11427   }
11428   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11429     if (Size != 16 || Op.getNumOperands() != 2)
11430       return false;
11431     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11432       return false;
11433     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11434       Val = C->getSExtValue();
11435       return true;
11436     }
11437     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11438       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11439       return true;
11440     }
11441   }
11442 
11443   return false;
11444 }
11445 
11446 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11447                                              const std::string &Constraint,
11448                                              uint64_t Val) const {
11449   if (Constraint.size() == 1) {
11450     switch (Constraint[0]) {
11451     case 'I':
11452       return AMDGPU::isInlinableIntLiteral(Val);
11453     case 'J':
11454       return isInt<16>(Val);
11455     case 'A':
11456       return checkAsmConstraintValA(Op, Val);
11457     case 'B':
11458       return isInt<32>(Val);
11459     case 'C':
11460       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11461              AMDGPU::isInlinableIntLiteral(Val);
11462     default:
11463       break;
11464     }
11465   } else if (Constraint.size() == 2) {
11466     if (Constraint == "DA") {
11467       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11468       int64_t LoBits = static_cast<int32_t>(Val);
11469       return checkAsmConstraintValA(Op, HiBits, 32) &&
11470              checkAsmConstraintValA(Op, LoBits, 32);
11471     }
11472     if (Constraint == "DB") {
11473       return true;
11474     }
11475   }
11476   llvm_unreachable("Invalid asm constraint");
11477 }
11478 
11479 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11480                                               uint64_t Val,
11481                                               unsigned MaxSize) const {
11482   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11483   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11484   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11485       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11486       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11487     return true;
11488   }
11489   return false;
11490 }
11491 
11492 // Figure out which registers should be reserved for stack access. Only after
11493 // the function is legalized do we know all of the non-spill stack objects or if
11494 // calls are present.
11495 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11496   MachineRegisterInfo &MRI = MF.getRegInfo();
11497   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11498   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11499   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11500 
11501   if (Info->isEntryFunction()) {
11502     // Callable functions have fixed registers used for stack access.
11503     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11504   }
11505 
11506   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11507                              Info->getStackPtrOffsetReg()));
11508   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11509     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11510 
11511   // We need to worry about replacing the default register with itself in case
11512   // of MIR testcases missing the MFI.
11513   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11514     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11515 
11516   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11517     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11518 
11519   Info->limitOccupancy(MF);
11520 
11521   if (ST.isWave32() && !MF.empty()) {
11522     // Add VCC_HI def because many instructions marked as imp-use VCC where
11523     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11524     // having a use of undef.
11525 
11526     const SIInstrInfo *TII = ST.getInstrInfo();
11527     DebugLoc DL;
11528 
11529     MachineBasicBlock &MBB = MF.front();
11530     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11531     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11532 
11533     for (auto &MBB : MF) {
11534       for (auto &MI : MBB) {
11535         TII->fixImplicitOperands(MI);
11536       }
11537     }
11538   }
11539 
11540   TargetLoweringBase::finalizeLowering(MF);
11541 
11542   // Allocate a VGPR for future SGPR Spill if
11543   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11544   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11545   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11546       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11547     Info->reserveVGPRforSGPRSpills(MF);
11548 }
11549 
11550 void SITargetLowering::computeKnownBitsForFrameIndex(
11551   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11552   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11553 
11554   // Set the high bits to zero based on the maximum allowed scratch size per
11555   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11556   // calculation won't overflow, so assume the sign bit is never set.
11557   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11558 }
11559 
11560 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11561                                    KnownBits &Known, unsigned Dim) {
11562   unsigned MaxValue =
11563       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11564   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11565 }
11566 
11567 void SITargetLowering::computeKnownBitsForTargetInstr(
11568     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11569     const MachineRegisterInfo &MRI, unsigned Depth) const {
11570   const MachineInstr *MI = MRI.getVRegDef(R);
11571   switch (MI->getOpcode()) {
11572   case AMDGPU::G_INTRINSIC: {
11573     switch (MI->getIntrinsicID()) {
11574     case Intrinsic::amdgcn_workitem_id_x:
11575       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11576       break;
11577     case Intrinsic::amdgcn_workitem_id_y:
11578       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11579       break;
11580     case Intrinsic::amdgcn_workitem_id_z:
11581       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11582       break;
11583     case Intrinsic::amdgcn_mbcnt_lo:
11584     case Intrinsic::amdgcn_mbcnt_hi: {
11585       // These return at most the wavefront size - 1.
11586       unsigned Size = MRI.getType(R).getSizeInBits();
11587       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11588       break;
11589     }
11590     case Intrinsic::amdgcn_groupstaticsize: {
11591       // We can report everything over the maximum size as 0. We can't report
11592       // based on the actual size because we don't know if it's accurate or not
11593       // at any given point.
11594       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11595       break;
11596     }
11597     default:
11598       break;
11599     }
11600   }
11601   }
11602 }
11603 
11604 Align SITargetLowering::computeKnownAlignForTargetInstr(
11605   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11606   unsigned Depth) const {
11607   const MachineInstr *MI = MRI.getVRegDef(R);
11608   switch (MI->getOpcode()) {
11609   case AMDGPU::G_INTRINSIC:
11610   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11611     // FIXME: Can this move to generic code? What about the case where the call
11612     // site specifies a lower alignment?
11613     Intrinsic::ID IID = MI->getIntrinsicID();
11614     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11615     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11616     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11617       return *RetAlign;
11618     return Align(1);
11619   }
11620   default:
11621     return Align(1);
11622   }
11623 }
11624 
11625 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11626   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11627   const Align CacheLineAlign = Align(64);
11628 
11629   // Pre-GFX10 target did not benefit from loop alignment
11630   if (!ML || DisableLoopAlignment ||
11631       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11632       getSubtarget()->hasInstFwdPrefetchBug())
11633     return PrefAlign;
11634 
11635   // On GFX10 I$ is 4 x 64 bytes cache lines.
11636   // By default prefetcher keeps one cache line behind and reads two ahead.
11637   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11638   // behind and one ahead.
11639   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11640   // If loop fits 64 bytes it always spans no more than two cache lines and
11641   // does not need an alignment.
11642   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11643   // Else if loop is less or equal 192 bytes we need two lines behind.
11644 
11645   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11646   const MachineBasicBlock *Header = ML->getHeader();
11647   if (Header->getAlignment() != PrefAlign)
11648     return Header->getAlignment(); // Already processed.
11649 
11650   unsigned LoopSize = 0;
11651   for (const MachineBasicBlock *MBB : ML->blocks()) {
11652     // If inner loop block is aligned assume in average half of the alignment
11653     // size to be added as nops.
11654     if (MBB != Header)
11655       LoopSize += MBB->getAlignment().value() / 2;
11656 
11657     for (const MachineInstr &MI : *MBB) {
11658       LoopSize += TII->getInstSizeInBytes(MI);
11659       if (LoopSize > 192)
11660         return PrefAlign;
11661     }
11662   }
11663 
11664   if (LoopSize <= 64)
11665     return PrefAlign;
11666 
11667   if (LoopSize <= 128)
11668     return CacheLineAlign;
11669 
11670   // If any of parent loops is surrounded by prefetch instructions do not
11671   // insert new for inner loop, which would reset parent's settings.
11672   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11673     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11674       auto I = Exit->getFirstNonDebugInstr();
11675       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11676         return CacheLineAlign;
11677     }
11678   }
11679 
11680   MachineBasicBlock *Pre = ML->getLoopPreheader();
11681   MachineBasicBlock *Exit = ML->getExitBlock();
11682 
11683   if (Pre && Exit) {
11684     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11685             TII->get(AMDGPU::S_INST_PREFETCH))
11686       .addImm(1); // prefetch 2 lines behind PC
11687 
11688     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11689             TII->get(AMDGPU::S_INST_PREFETCH))
11690       .addImm(2); // prefetch 1 line behind PC
11691   }
11692 
11693   return CacheLineAlign;
11694 }
11695 
11696 LLVM_ATTRIBUTE_UNUSED
11697 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11698   assert(N->getOpcode() == ISD::CopyFromReg);
11699   do {
11700     // Follow the chain until we find an INLINEASM node.
11701     N = N->getOperand(0).getNode();
11702     if (N->getOpcode() == ISD::INLINEASM ||
11703         N->getOpcode() == ISD::INLINEASM_BR)
11704       return true;
11705   } while (N->getOpcode() == ISD::CopyFromReg);
11706   return false;
11707 }
11708 
11709 bool SITargetLowering::isSDNodeSourceOfDivergence(
11710     const SDNode *N, FunctionLoweringInfo *FLI,
11711     LegacyDivergenceAnalysis *KDA) const {
11712   switch (N->getOpcode()) {
11713   case ISD::CopyFromReg: {
11714     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11715     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11716     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11717     Register Reg = R->getReg();
11718 
11719     // FIXME: Why does this need to consider isLiveIn?
11720     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11721       return !TRI->isSGPRReg(MRI, Reg);
11722 
11723     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11724       return KDA->isDivergent(V);
11725 
11726     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11727     return !TRI->isSGPRReg(MRI, Reg);
11728   }
11729   case ISD::LOAD: {
11730     const LoadSDNode *L = cast<LoadSDNode>(N);
11731     unsigned AS = L->getAddressSpace();
11732     // A flat load may access private memory.
11733     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11734   }
11735   case ISD::CALLSEQ_END:
11736     return true;
11737   case ISD::INTRINSIC_WO_CHAIN:
11738     return AMDGPU::isIntrinsicSourceOfDivergence(
11739         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11740   case ISD::INTRINSIC_W_CHAIN:
11741     return AMDGPU::isIntrinsicSourceOfDivergence(
11742         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11743   }
11744   return false;
11745 }
11746 
11747 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11748                                                EVT VT) const {
11749   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11750   case MVT::f32:
11751     return hasFP32Denormals(DAG.getMachineFunction());
11752   case MVT::f64:
11753   case MVT::f16:
11754     return hasFP64FP16Denormals(DAG.getMachineFunction());
11755   default:
11756     return false;
11757   }
11758 }
11759 
11760 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11761                                                     const SelectionDAG &DAG,
11762                                                     bool SNaN,
11763                                                     unsigned Depth) const {
11764   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11765     const MachineFunction &MF = DAG.getMachineFunction();
11766     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11767 
11768     if (Info->getMode().DX10Clamp)
11769       return true; // Clamped to 0.
11770     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11771   }
11772 
11773   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11774                                                             SNaN, Depth);
11775 }
11776 
11777 // Global FP atomic instructions have a hardcoded FP mode and do not support
11778 // FP32 denormals, and only support v2f16 denormals.
11779 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
11780   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
11781   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
11782   if (&Flt == &APFloat::IEEEsingle())
11783     return DenormMode == DenormalMode::getPreserveSign();
11784   return DenormMode == DenormalMode::getIEEE();
11785 }
11786 
11787 TargetLowering::AtomicExpansionKind
11788 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11789   switch (RMW->getOperation()) {
11790   case AtomicRMWInst::FAdd: {
11791     Type *Ty = RMW->getType();
11792 
11793     // We don't have a way to support 16-bit atomics now, so just leave them
11794     // as-is.
11795     if (Ty->isHalfTy())
11796       return AtomicExpansionKind::None;
11797 
11798     if (!Ty->isFloatTy())
11799       return AtomicExpansionKind::CmpXChg;
11800 
11801     // TODO: Do have these for flat. Older targets also had them for buffers.
11802     unsigned AS = RMW->getPointerAddressSpace();
11803 
11804     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11805       if (!fpModeMatchesGlobalFPAtomicMode(RMW))
11806         return AtomicExpansionKind::CmpXChg;
11807 
11808       return RMW->use_empty() ? AtomicExpansionKind::None :
11809                                 AtomicExpansionKind::CmpXChg;
11810     }
11811 
11812     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
11813     // to round-to-nearest-even.
11814     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11815       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11816   }
11817   default:
11818     break;
11819   }
11820 
11821   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11822 }
11823 
11824 const TargetRegisterClass *
11825 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11826   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11827   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11828   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11829     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11830                                                : &AMDGPU::SReg_32RegClass;
11831   if (!TRI->isSGPRClass(RC) && !isDivergent)
11832     return TRI->getEquivalentSGPRClass(RC);
11833   else if (TRI->isSGPRClass(RC) && isDivergent)
11834     return TRI->getEquivalentVGPRClass(RC);
11835 
11836   return RC;
11837 }
11838 
11839 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11840 // uniform values (as produced by the mask results of control flow intrinsics)
11841 // used outside of divergent blocks. The phi users need to also be treated as
11842 // always uniform.
11843 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11844                       unsigned WaveSize) {
11845   // FIXME: We asssume we never cast the mask results of a control flow
11846   // intrinsic.
11847   // Early exit if the type won't be consistent as a compile time hack.
11848   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11849   if (!IT || IT->getBitWidth() != WaveSize)
11850     return false;
11851 
11852   if (!isa<Instruction>(V))
11853     return false;
11854   if (!Visited.insert(V).second)
11855     return false;
11856   bool Result = false;
11857   for (auto U : V->users()) {
11858     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11859       if (V == U->getOperand(1)) {
11860         switch (Intrinsic->getIntrinsicID()) {
11861         default:
11862           Result = false;
11863           break;
11864         case Intrinsic::amdgcn_if_break:
11865         case Intrinsic::amdgcn_if:
11866         case Intrinsic::amdgcn_else:
11867           Result = true;
11868           break;
11869         }
11870       }
11871       if (V == U->getOperand(0)) {
11872         switch (Intrinsic->getIntrinsicID()) {
11873         default:
11874           Result = false;
11875           break;
11876         case Intrinsic::amdgcn_end_cf:
11877         case Intrinsic::amdgcn_loop:
11878           Result = true;
11879           break;
11880         }
11881       }
11882     } else {
11883       Result = hasCFUser(U, Visited, WaveSize);
11884     }
11885     if (Result)
11886       break;
11887   }
11888   return Result;
11889 }
11890 
11891 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11892                                                const Value *V) const {
11893   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11894     if (CI->isInlineAsm()) {
11895       // FIXME: This cannot give a correct answer. This should only trigger in
11896       // the case where inline asm returns mixed SGPR and VGPR results, used
11897       // outside the defining block. We don't have a specific result to
11898       // consider, so this assumes if any value is SGPR, the overall register
11899       // also needs to be SGPR.
11900       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11901       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11902           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11903       for (auto &TC : TargetConstraints) {
11904         if (TC.Type == InlineAsm::isOutput) {
11905           ComputeConstraintToUse(TC, SDValue());
11906           unsigned AssignedReg;
11907           const TargetRegisterClass *RC;
11908           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11909               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11910           if (RC) {
11911             MachineRegisterInfo &MRI = MF.getRegInfo();
11912             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11913               return true;
11914             else if (SIRI->isSGPRClass(RC))
11915               return true;
11916           }
11917         }
11918       }
11919     }
11920   }
11921   SmallPtrSet<const Value *, 16> Visited;
11922   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11923 }
11924 
11925 std::pair<int, MVT>
11926 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11927                                           Type *Ty) const {
11928   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11929   auto Size = DL.getTypeSizeInBits(Ty);
11930   // Maximum load or store can handle 8 dwords for scalar and 4 for
11931   // vector ALU. Let's assume anything above 8 dwords is expensive
11932   // even if legal.
11933   if (Size <= 256)
11934     return Cost;
11935 
11936   Cost.first = (Size + 255) / 256;
11937   return Cost;
11938 }
11939