1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUSubtarget.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
19 #include "SIDefines.h"
20 #include "SIInstrInfo.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "SIRegisterInfo.h"
23 #include "Utils/AMDGPUBaseInfo.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/DAGCombine.h"
37 #include "llvm/CodeGen/FunctionLoweringInfo.h"
38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/SelectionDAG.h"
51 #include "llvm/CodeGen/SelectionDAGNodes.h"
52 #include "llvm/CodeGen/TargetCallingConv.h"
53 #include "llvm/CodeGen/TargetRegisterInfo.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/IR/Constants.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/DebugLoc.h"
58 #include "llvm/IR/DerivedTypes.h"
59 #include "llvm/IR/DiagnosticInfo.h"
60 #include "llvm/IR/Function.h"
61 #include "llvm/IR/GlobalValue.h"
62 #include "llvm/IR/InstrTypes.h"
63 #include "llvm/IR/Instruction.h"
64 #include "llvm/IR/Instructions.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/Type.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CodeGen.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/KnownBits.h"
73 #include "llvm/Support/MachineValueType.h"
74 #include "llvm/Support/MathExtras.h"
75 #include "llvm/Target/TargetOptions.h"
76 #include <cassert>
77 #include <cmath>
78 #include <cstdint>
79 #include <iterator>
80 #include <tuple>
81 #include <utility>
82 #include <vector>
83 
84 using namespace llvm;
85 
86 #define DEBUG_TYPE "si-lower"
87 
88 STATISTIC(NumTailCalls, "Number of tail calls");
89 
90 static cl::opt<bool> DisableLoopAlignment(
91   "amdgpu-disable-loop-alignment",
92   cl::desc("Do not align and prefetch loops"),
93   cl::init(false));
94 
95 static cl::opt<bool> VGPRReserveforSGPRSpill(
96     "amdgpu-reserve-vgpr-for-sgpr-spill",
97     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
98 
99 static cl::opt<bool> UseDivergentRegisterIndexing(
100   "amdgpu-use-divergent-register-indexing",
101   cl::Hidden,
102   cl::desc("Use indirect register addressing for divergent indexes"),
103   cl::init(false));
104 
105 static bool hasFP32Denormals(const MachineFunction &MF) {
106   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
107   return Info->getMode().allFP32Denormals();
108 }
109 
110 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
111   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
112   return Info->getMode().allFP64FP16Denormals();
113 }
114 
115 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
116   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
117   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
118     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
119       return AMDGPU::SGPR0 + Reg;
120     }
121   }
122   llvm_unreachable("Cannot allocate sgpr");
123 }
124 
125 SITargetLowering::SITargetLowering(const TargetMachine &TM,
126                                    const GCNSubtarget &STI)
127     : AMDGPUTargetLowering(TM, STI),
128       Subtarget(&STI) {
129   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
130   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
131 
132   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
133   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
134 
135   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
136   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
137   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
138 
139   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
140   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
141 
142   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
143   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
144 
145   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
146   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
147 
148   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
149   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
150 
151   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
152   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
153 
154   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
155   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
156 
157   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
158   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
159 
160   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
161   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
162 
163   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
164   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
165 
166   if (Subtarget->has16BitInsts()) {
167     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
168     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
169 
170     // Unless there are also VOP3P operations, not operations are really legal.
171     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
172     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
173     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
174     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
175   }
176 
177   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
178   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
179 
180   computeRegisterProperties(Subtarget->getRegisterInfo());
181 
182   // The boolean content concept here is too inflexible. Compares only ever
183   // really produce a 1-bit result. Any copy/extend from these will turn into a
184   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
185   // it's what most targets use.
186   setBooleanContents(ZeroOrOneBooleanContent);
187   setBooleanVectorContents(ZeroOrOneBooleanContent);
188 
189   // We need to custom lower vector stores from local memory
190   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
195   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
196   setOperationAction(ISD::LOAD, MVT::i1, Custom);
197   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
198 
199   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
202   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
203   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
204   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
205   setOperationAction(ISD::STORE, MVT::i1, Custom);
206   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
207 
208   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
209   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
210   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
211   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
212   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
213   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
214   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
215   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
216   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
217   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
218   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
219   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
220   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
221   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
222   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
223   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
224 
225   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
226   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
227   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
228   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
229   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
230 
231   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
232   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
233 
234   setOperationAction(ISD::SELECT, MVT::i1, Promote);
235   setOperationAction(ISD::SELECT, MVT::i64, Custom);
236   setOperationAction(ISD::SELECT, MVT::f64, Promote);
237   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
238 
239   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
241   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
242   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
243   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
244 
245   setOperationAction(ISD::SETCC, MVT::i1, Promote);
246   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
247   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
248   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
249 
250   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
251   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
252   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
253   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
254   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
255   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
256   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
257   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
258 
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
266   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
267 
268   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
269   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
270   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
271   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
272   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
273   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
274 
275   setOperationAction(ISD::UADDO, MVT::i32, Legal);
276   setOperationAction(ISD::USUBO, MVT::i32, Legal);
277 
278   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
279   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
280 
281   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
282   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
283   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
284 
285 #if 0
286   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
287   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
288 #endif
289 
290   // We only support LOAD/STORE and vector manipulation ops for vectors
291   // with > 4 elements.
292   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
293                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
294                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
295                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
296     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
297       switch (Op) {
298       case ISD::LOAD:
299       case ISD::STORE:
300       case ISD::BUILD_VECTOR:
301       case ISD::BITCAST:
302       case ISD::EXTRACT_VECTOR_ELT:
303       case ISD::INSERT_VECTOR_ELT:
304       case ISD::INSERT_SUBVECTOR:
305       case ISD::EXTRACT_SUBVECTOR:
306       case ISD::SCALAR_TO_VECTOR:
307         break;
308       case ISD::CONCAT_VECTORS:
309         setOperationAction(Op, VT, Custom);
310         break;
311       default:
312         setOperationAction(Op, VT, Expand);
313         break;
314       }
315     }
316   }
317 
318   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
319 
320   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
321   // is expanded to avoid having two separate loops in case the index is a VGPR.
322 
323   // Most operations are naturally 32-bit vector operations. We only support
324   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
325   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
326     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
327     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
328 
329     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
330     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
331 
332     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
333     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
334 
335     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
336     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
337   }
338 
339   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
340     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
341     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
342 
343     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
344     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
345 
346     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
347     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
348 
349     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
350     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
351   }
352 
353   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
354     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
355     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
356 
357     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
358     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
359 
360     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
361     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
362 
363     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
364     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
365   }
366 
367   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
368     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
369     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
370 
371     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
372     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
373 
374     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
375     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
376 
377     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
378     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
379   }
380 
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
382   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
383   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
384   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
385 
386   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
387   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
388 
389   // Avoid stack access for these.
390   // TODO: Generalize to more vector types.
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
395 
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
400   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
401 
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
403   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
404   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
405 
406   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
407   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
408   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
409   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
410 
411   // Deal with vec3 vector operations when widened to vec4.
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
416 
417   // Deal with vec5 vector operations when widened to vec8.
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
419   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
420   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
421   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
422 
423   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
424   // and output demarshalling
425   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
426   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
427 
428   // We can't return success/failure, only the old value,
429   // let LLVM add the comparison
430   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
431   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
432 
433   if (Subtarget->hasFlatAddressSpace()) {
434     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
435     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
436   }
437 
438   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
439 
440   // FIXME: This should be narrowed to i32, but that only happens if i64 is
441   // illegal.
442   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
443   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
444   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
445 
446   // On SI this is s_memtime and s_memrealtime on VI.
447   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
448   setOperationAction(ISD::TRAP, MVT::Other, Custom);
449   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
450 
451   if (Subtarget->has16BitInsts()) {
452     setOperationAction(ISD::FPOW, MVT::f16, Promote);
453     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
454     setOperationAction(ISD::FLOG, MVT::f16, Custom);
455     setOperationAction(ISD::FEXP, MVT::f16, Custom);
456     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
457   }
458 
459   if (Subtarget->hasMadMacF32Insts())
460     setOperationAction(ISD::FMAD, MVT::f32, Legal);
461 
462   if (!Subtarget->hasBFI()) {
463     // fcopysign can be done in a single instruction with BFI.
464     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
465     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
466   }
467 
468   if (!Subtarget->hasBCNT(32))
469     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
470 
471   if (!Subtarget->hasBCNT(64))
472     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
473 
474   if (Subtarget->hasFFBH())
475     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
476 
477   if (Subtarget->hasFFBL())
478     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
479 
480   // We only really have 32-bit BFE instructions (and 16-bit on VI).
481   //
482   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
483   // effort to match them now. We want this to be false for i64 cases when the
484   // extraction isn't restricted to the upper or lower half. Ideally we would
485   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
486   // span the midpoint are probably relatively rare, so don't worry about them
487   // for now.
488   if (Subtarget->hasBFE())
489     setHasExtractBitsInsn(true);
490 
491   // Clamp modifier on add/sub
492   if (Subtarget->hasIntClamp()) {
493     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
494     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
495   }
496 
497   if (Subtarget->hasAddNoCarry()) {
498     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
500     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
501     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
502   }
503 
504   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
506   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
507   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
508 
509 
510   // These are really only legal for ieee_mode functions. We should be avoiding
511   // them for functions that don't have ieee_mode enabled, so just say they are
512   // legal.
513   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
515   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
516   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
517 
518 
519   if (Subtarget->haveRoundOpsF64()) {
520     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
521     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
522     setOperationAction(ISD::FRINT, MVT::f64, Legal);
523   } else {
524     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
525     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
526     setOperationAction(ISD::FRINT, MVT::f64, Custom);
527     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
528   }
529 
530   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
531 
532   setOperationAction(ISD::FSIN, MVT::f32, Custom);
533   setOperationAction(ISD::FCOS, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f32, Custom);
535   setOperationAction(ISD::FDIV, MVT::f64, Custom);
536 
537   if (Subtarget->has16BitInsts()) {
538     setOperationAction(ISD::Constant, MVT::i16, Legal);
539 
540     setOperationAction(ISD::SMIN, MVT::i16, Legal);
541     setOperationAction(ISD::SMAX, MVT::i16, Legal);
542 
543     setOperationAction(ISD::UMIN, MVT::i16, Legal);
544     setOperationAction(ISD::UMAX, MVT::i16, Legal);
545 
546     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
547     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
548 
549     setOperationAction(ISD::ROTR, MVT::i16, Expand);
550     setOperationAction(ISD::ROTL, MVT::i16, Expand);
551 
552     setOperationAction(ISD::SDIV, MVT::i16, Promote);
553     setOperationAction(ISD::UDIV, MVT::i16, Promote);
554     setOperationAction(ISD::SREM, MVT::i16, Promote);
555     setOperationAction(ISD::UREM, MVT::i16, Promote);
556     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
557     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
558 
559     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
560 
561     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
564     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
565     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
566 
567     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
568 
569     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
570 
571     setOperationAction(ISD::LOAD, MVT::i16, Custom);
572 
573     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
574 
575     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
576     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
577     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
578     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
579 
580     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
581     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
582 
583     // F16 - Constant Actions.
584     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
585 
586     // F16 - Load/Store Actions.
587     setOperationAction(ISD::LOAD, MVT::f16, Promote);
588     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
589     setOperationAction(ISD::STORE, MVT::f16, Promote);
590     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
591 
592     // F16 - VOP1 Actions.
593     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
594     setOperationAction(ISD::FCOS, MVT::f16, Custom);
595     setOperationAction(ISD::FSIN, MVT::f16, Custom);
596 
597     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
598     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
599 
600     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
601     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
602     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
604     setOperationAction(ISD::FROUND, MVT::f16, Custom);
605 
606     // F16 - VOP2 Actions.
607     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
608     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
609 
610     setOperationAction(ISD::FDIV, MVT::f16, Custom);
611 
612     // F16 - VOP3 Actions.
613     setOperationAction(ISD::FMA, MVT::f16, Legal);
614     if (STI.hasMadF16())
615       setOperationAction(ISD::FMAD, MVT::f16, Legal);
616 
617     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
618       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
619         switch (Op) {
620         case ISD::LOAD:
621         case ISD::STORE:
622         case ISD::BUILD_VECTOR:
623         case ISD::BITCAST:
624         case ISD::EXTRACT_VECTOR_ELT:
625         case ISD::INSERT_VECTOR_ELT:
626         case ISD::INSERT_SUBVECTOR:
627         case ISD::EXTRACT_SUBVECTOR:
628         case ISD::SCALAR_TO_VECTOR:
629           break;
630         case ISD::CONCAT_VECTORS:
631           setOperationAction(Op, VT, Custom);
632           break;
633         default:
634           setOperationAction(Op, VT, Expand);
635           break;
636         }
637       }
638     }
639 
640     // v_perm_b32 can handle either of these.
641     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
642     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
643     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
644 
645     // XXX - Do these do anything? Vector constants turn into build_vector.
646     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
647     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
648 
649     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
650     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
651 
652     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
653     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
654     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
655     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
656 
657     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
658     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
659     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
660     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
661 
662     setOperationAction(ISD::AND, MVT::v2i16, Promote);
663     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
664     setOperationAction(ISD::OR, MVT::v2i16, Promote);
665     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
666     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
667     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
668 
669     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
670     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
671     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
672     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
673 
674     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
675     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
676     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
677     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
678 
679     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
680     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
682     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
683 
684     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
685     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
686     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
687 
688     if (!Subtarget->hasVOP3PInsts()) {
689       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
690       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
691     }
692 
693     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
694     // This isn't really legal, but this avoids the legalizer unrolling it (and
695     // allows matching fneg (fabs x) patterns)
696     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
697 
698     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
699     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
700     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
701     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
702 
703     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
704     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
705 
706     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
707     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
708   }
709 
710   if (Subtarget->hasVOP3PInsts()) {
711     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
712     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
713     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
714     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
716     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
717     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
718     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
719     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
720     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
721 
722     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
723     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
725     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
726 
727     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
728     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
729     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
730 
731     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
732     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
733 
734     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
735 
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
737     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
738 
739     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
740     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
741 
742     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
743     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
744     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
745     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
746     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
747     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
748 
749     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
750     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
751     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
752     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
753 
754     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
755     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
757     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
758 
759     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
760     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
761     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
762 
763     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
764     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
765 
766     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
767     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
768     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
769 
770     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
771     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
772     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
773   }
774 
775   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
776   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
777 
778   if (Subtarget->has16BitInsts()) {
779     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
780     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
781     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
782     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
783   } else {
784     // Legalization hack.
785     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
786     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
787 
788     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
789     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
790   }
791 
792   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
793     setOperationAction(ISD::SELECT, VT, Custom);
794   }
795 
796   setOperationAction(ISD::SMULO, MVT::i64, Custom);
797   setOperationAction(ISD::UMULO, MVT::i64, Custom);
798 
799   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
800   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
801   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
802   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
803   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
804   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
805   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
806 
807   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
808   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
809   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
810   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
811   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
812   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
813   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
814   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
815   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
816   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
817   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
818 
819   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
820   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
821   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
822   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
823   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
824   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
825   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
826   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
827   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
828   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
829 
830   setTargetDAGCombine(ISD::ADD);
831   setTargetDAGCombine(ISD::ADDCARRY);
832   setTargetDAGCombine(ISD::SUB);
833   setTargetDAGCombine(ISD::SUBCARRY);
834   setTargetDAGCombine(ISD::FADD);
835   setTargetDAGCombine(ISD::FSUB);
836   setTargetDAGCombine(ISD::FMINNUM);
837   setTargetDAGCombine(ISD::FMAXNUM);
838   setTargetDAGCombine(ISD::FMINNUM_IEEE);
839   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
840   setTargetDAGCombine(ISD::FMA);
841   setTargetDAGCombine(ISD::SMIN);
842   setTargetDAGCombine(ISD::SMAX);
843   setTargetDAGCombine(ISD::UMIN);
844   setTargetDAGCombine(ISD::UMAX);
845   setTargetDAGCombine(ISD::SETCC);
846   setTargetDAGCombine(ISD::AND);
847   setTargetDAGCombine(ISD::OR);
848   setTargetDAGCombine(ISD::XOR);
849   setTargetDAGCombine(ISD::SINT_TO_FP);
850   setTargetDAGCombine(ISD::UINT_TO_FP);
851   setTargetDAGCombine(ISD::FCANONICALIZE);
852   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
853   setTargetDAGCombine(ISD::ZERO_EXTEND);
854   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
855   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
856   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
857 
858   // All memory operations. Some folding on the pointer operand is done to help
859   // matching the constant offsets in the addressing modes.
860   setTargetDAGCombine(ISD::LOAD);
861   setTargetDAGCombine(ISD::STORE);
862   setTargetDAGCombine(ISD::ATOMIC_LOAD);
863   setTargetDAGCombine(ISD::ATOMIC_STORE);
864   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
865   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
866   setTargetDAGCombine(ISD::ATOMIC_SWAP);
867   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
868   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
869   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
870   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
871   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
872   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
873   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
874   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
875   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
876   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
877   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
878   setTargetDAGCombine(ISD::INTRINSIC_VOID);
879   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
880 
881   // FIXME: In other contexts we pretend this is a per-function property.
882   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
883 
884   setSchedulingPreference(Sched::RegPressure);
885 }
886 
887 const GCNSubtarget *SITargetLowering::getSubtarget() const {
888   return Subtarget;
889 }
890 
891 //===----------------------------------------------------------------------===//
892 // TargetLowering queries
893 //===----------------------------------------------------------------------===//
894 
895 // v_mad_mix* support a conversion from f16 to f32.
896 //
897 // There is only one special case when denormals are enabled we don't currently,
898 // where this is OK to use.
899 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
900                                        EVT DestVT, EVT SrcVT) const {
901   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
902           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
903     DestVT.getScalarType() == MVT::f32 &&
904     SrcVT.getScalarType() == MVT::f16 &&
905     // TODO: This probably only requires no input flushing?
906     !hasFP32Denormals(DAG.getMachineFunction());
907 }
908 
909 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
910   // SI has some legal vector types, but no legal vector operations. Say no
911   // shuffles are legal in order to prefer scalarizing some vector operations.
912   return false;
913 }
914 
915 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
916                                                     CallingConv::ID CC,
917                                                     EVT VT) const {
918   if (CC == CallingConv::AMDGPU_KERNEL)
919     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
920 
921   if (VT.isVector()) {
922     EVT ScalarVT = VT.getScalarType();
923     unsigned Size = ScalarVT.getSizeInBits();
924     if (Size == 16) {
925       if (Subtarget->has16BitInsts())
926         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
927       return VT.isInteger() ? MVT::i32 : MVT::f32;
928     }
929 
930     if (Size < 16)
931       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
932     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
933   }
934 
935   if (VT.getSizeInBits() > 32)
936     return MVT::i32;
937 
938   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
939 }
940 
941 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
942                                                          CallingConv::ID CC,
943                                                          EVT VT) const {
944   if (CC == CallingConv::AMDGPU_KERNEL)
945     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
946 
947   if (VT.isVector()) {
948     unsigned NumElts = VT.getVectorNumElements();
949     EVT ScalarVT = VT.getScalarType();
950     unsigned Size = ScalarVT.getSizeInBits();
951 
952     // FIXME: Should probably promote 8-bit vectors to i16.
953     if (Size == 16 && Subtarget->has16BitInsts())
954       return (NumElts + 1) / 2;
955 
956     if (Size <= 32)
957       return NumElts;
958 
959     if (Size > 32)
960       return NumElts * ((Size + 31) / 32);
961   } else if (VT.getSizeInBits() > 32)
962     return (VT.getSizeInBits() + 31) / 32;
963 
964   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
965 }
966 
967 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
968   LLVMContext &Context, CallingConv::ID CC,
969   EVT VT, EVT &IntermediateVT,
970   unsigned &NumIntermediates, MVT &RegisterVT) const {
971   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
972     unsigned NumElts = VT.getVectorNumElements();
973     EVT ScalarVT = VT.getScalarType();
974     unsigned Size = ScalarVT.getSizeInBits();
975     // FIXME: We should fix the ABI to be the same on targets without 16-bit
976     // support, but unless we can properly handle 3-vectors, it will be still be
977     // inconsistent.
978     if (Size == 16 && Subtarget->has16BitInsts()) {
979       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
980       IntermediateVT = RegisterVT;
981       NumIntermediates = (NumElts + 1) / 2;
982       return NumIntermediates;
983     }
984 
985     if (Size == 32) {
986       RegisterVT = ScalarVT.getSimpleVT();
987       IntermediateVT = RegisterVT;
988       NumIntermediates = NumElts;
989       return NumIntermediates;
990     }
991 
992     if (Size < 16 && Subtarget->has16BitInsts()) {
993       // FIXME: Should probably form v2i16 pieces
994       RegisterVT = MVT::i16;
995       IntermediateVT = ScalarVT;
996       NumIntermediates = NumElts;
997       return NumIntermediates;
998     }
999 
1000 
1001     if (Size != 16 && Size <= 32) {
1002       RegisterVT = MVT::i32;
1003       IntermediateVT = ScalarVT;
1004       NumIntermediates = NumElts;
1005       return NumIntermediates;
1006     }
1007 
1008     if (Size > 32) {
1009       RegisterVT = MVT::i32;
1010       IntermediateVT = RegisterVT;
1011       NumIntermediates = NumElts * ((Size + 31) / 32);
1012       return NumIntermediates;
1013     }
1014   }
1015 
1016   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1017     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1018 }
1019 
1020 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1021   assert(DMaskLanes != 0);
1022 
1023   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1024     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1025     return EVT::getVectorVT(Ty->getContext(),
1026                             EVT::getEVT(VT->getElementType()),
1027                             NumElts);
1028   }
1029 
1030   return EVT::getEVT(Ty);
1031 }
1032 
1033 // Peek through TFE struct returns to only use the data size.
1034 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1035   auto *ST = dyn_cast<StructType>(Ty);
1036   if (!ST)
1037     return memVTFromImageData(Ty, DMaskLanes);
1038 
1039   // Some intrinsics return an aggregate type - special case to work out the
1040   // correct memVT.
1041   //
1042   // Only limited forms of aggregate type currently expected.
1043   if (ST->getNumContainedTypes() != 2 ||
1044       !ST->getContainedType(1)->isIntegerTy(32))
1045     return EVT();
1046   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1047 }
1048 
1049 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1050                                           const CallInst &CI,
1051                                           MachineFunction &MF,
1052                                           unsigned IntrID) const {
1053   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1054           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1055     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1056                                                   (Intrinsic::ID)IntrID);
1057     if (Attr.hasFnAttribute(Attribute::ReadNone))
1058       return false;
1059 
1060     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1061 
1062     if (RsrcIntr->IsImage) {
1063       Info.ptrVal = MFI->getImagePSV(
1064         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1065         CI.getArgOperand(RsrcIntr->RsrcArg));
1066       Info.align.reset();
1067     } else {
1068       Info.ptrVal = MFI->getBufferPSV(
1069         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1070         CI.getArgOperand(RsrcIntr->RsrcArg));
1071     }
1072 
1073     Info.flags = MachineMemOperand::MODereferenceable;
1074     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1075       unsigned DMaskLanes = 4;
1076 
1077       if (RsrcIntr->IsImage) {
1078         const AMDGPU::ImageDimIntrinsicInfo *Intr
1079           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1080         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1081           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1082 
1083         if (!BaseOpcode->Gather4) {
1084           // If this isn't a gather, we may have excess loaded elements in the
1085           // IR type. Check the dmask for the real number of elements loaded.
1086           unsigned DMask
1087             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1088           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1089         }
1090 
1091         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1092       } else
1093         Info.memVT = EVT::getEVT(CI.getType());
1094 
1095       // FIXME: What does alignment mean for an image?
1096       Info.opc = ISD::INTRINSIC_W_CHAIN;
1097       Info.flags |= MachineMemOperand::MOLoad;
1098     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1099       Info.opc = ISD::INTRINSIC_VOID;
1100 
1101       Type *DataTy = CI.getArgOperand(0)->getType();
1102       if (RsrcIntr->IsImage) {
1103         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1104         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1105         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1106       } else
1107         Info.memVT = EVT::getEVT(DataTy);
1108 
1109       Info.flags |= MachineMemOperand::MOStore;
1110     } else {
1111       // Atomic
1112       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1113                                             ISD::INTRINSIC_W_CHAIN;
1114       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1115       Info.flags = MachineMemOperand::MOLoad |
1116                    MachineMemOperand::MOStore |
1117                    MachineMemOperand::MODereferenceable;
1118 
1119       // XXX - Should this be volatile without known ordering?
1120       Info.flags |= MachineMemOperand::MOVolatile;
1121     }
1122     return true;
1123   }
1124 
1125   switch (IntrID) {
1126   case Intrinsic::amdgcn_atomic_inc:
1127   case Intrinsic::amdgcn_atomic_dec:
1128   case Intrinsic::amdgcn_ds_ordered_add:
1129   case Intrinsic::amdgcn_ds_ordered_swap:
1130   case Intrinsic::amdgcn_ds_fadd:
1131   case Intrinsic::amdgcn_ds_fmin:
1132   case Intrinsic::amdgcn_ds_fmax: {
1133     Info.opc = ISD::INTRINSIC_W_CHAIN;
1134     Info.memVT = MVT::getVT(CI.getType());
1135     Info.ptrVal = CI.getOperand(0);
1136     Info.align.reset();
1137     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1138 
1139     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1140     if (!Vol->isZero())
1141       Info.flags |= MachineMemOperand::MOVolatile;
1142 
1143     return true;
1144   }
1145   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1146     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1147 
1148     Info.opc = ISD::INTRINSIC_W_CHAIN;
1149     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1150     Info.ptrVal = MFI->getBufferPSV(
1151       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1152       CI.getArgOperand(1));
1153     Info.align.reset();
1154     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1155 
1156     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1157     if (!Vol || !Vol->isZero())
1158       Info.flags |= MachineMemOperand::MOVolatile;
1159 
1160     return true;
1161   }
1162   case Intrinsic::amdgcn_ds_append:
1163   case Intrinsic::amdgcn_ds_consume: {
1164     Info.opc = ISD::INTRINSIC_W_CHAIN;
1165     Info.memVT = MVT::getVT(CI.getType());
1166     Info.ptrVal = CI.getOperand(0);
1167     Info.align.reset();
1168     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1169 
1170     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1171     if (!Vol->isZero())
1172       Info.flags |= MachineMemOperand::MOVolatile;
1173 
1174     return true;
1175   }
1176   case Intrinsic::amdgcn_global_atomic_csub: {
1177     Info.opc = ISD::INTRINSIC_W_CHAIN;
1178     Info.memVT = MVT::getVT(CI.getType());
1179     Info.ptrVal = CI.getOperand(0);
1180     Info.align.reset();
1181     Info.flags = MachineMemOperand::MOLoad |
1182                  MachineMemOperand::MOStore |
1183                  MachineMemOperand::MOVolatile;
1184     return true;
1185   }
1186   case Intrinsic::amdgcn_global_atomic_fadd: {
1187     Info.opc = ISD::INTRINSIC_W_CHAIN;
1188     Info.memVT = MVT::getVT(CI.getType());
1189     Info.ptrVal = CI.getOperand(0);
1190     Info.align.reset();
1191     Info.flags = MachineMemOperand::MOLoad |
1192                  MachineMemOperand::MOStore |
1193                  MachineMemOperand::MODereferenceable |
1194                  MachineMemOperand::MOVolatile;
1195     return true;
1196   }
1197   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1198     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1199     Info.opc = ISD::INTRINSIC_W_CHAIN;
1200     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1201     Info.ptrVal = MFI->getImagePSV(
1202         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), CI.getArgOperand(5));
1203     Info.align.reset();
1204     Info.flags = MachineMemOperand::MOLoad |
1205                  MachineMemOperand::MODereferenceable;
1206     return true;
1207   }
1208   case Intrinsic::amdgcn_ds_gws_init:
1209   case Intrinsic::amdgcn_ds_gws_barrier:
1210   case Intrinsic::amdgcn_ds_gws_sema_v:
1211   case Intrinsic::amdgcn_ds_gws_sema_br:
1212   case Intrinsic::amdgcn_ds_gws_sema_p:
1213   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1214     Info.opc = ISD::INTRINSIC_VOID;
1215 
1216     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1217     Info.ptrVal =
1218         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1219 
1220     // This is an abstract access, but we need to specify a type and size.
1221     Info.memVT = MVT::i32;
1222     Info.size = 4;
1223     Info.align = Align(4);
1224 
1225     Info.flags = MachineMemOperand::MOStore;
1226     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1227       Info.flags = MachineMemOperand::MOLoad;
1228     return true;
1229   }
1230   default:
1231     return false;
1232   }
1233 }
1234 
1235 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1236                                             SmallVectorImpl<Value*> &Ops,
1237                                             Type *&AccessTy) const {
1238   switch (II->getIntrinsicID()) {
1239   case Intrinsic::amdgcn_atomic_inc:
1240   case Intrinsic::amdgcn_atomic_dec:
1241   case Intrinsic::amdgcn_ds_ordered_add:
1242   case Intrinsic::amdgcn_ds_ordered_swap:
1243   case Intrinsic::amdgcn_ds_append:
1244   case Intrinsic::amdgcn_ds_consume:
1245   case Intrinsic::amdgcn_ds_fadd:
1246   case Intrinsic::amdgcn_ds_fmin:
1247   case Intrinsic::amdgcn_ds_fmax:
1248   case Intrinsic::amdgcn_global_atomic_fadd:
1249   case Intrinsic::amdgcn_global_atomic_csub: {
1250     Value *Ptr = II->getArgOperand(0);
1251     AccessTy = II->getType();
1252     Ops.push_back(Ptr);
1253     return true;
1254   }
1255   default:
1256     return false;
1257   }
1258 }
1259 
1260 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1261   if (!Subtarget->hasFlatInstOffsets()) {
1262     // Flat instructions do not have offsets, and only have the register
1263     // address.
1264     return AM.BaseOffs == 0 && AM.Scale == 0;
1265   }
1266 
1267   return AM.Scale == 0 &&
1268          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1269                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1270                                   /*Signed=*/false));
1271 }
1272 
1273 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1274   if (Subtarget->hasFlatGlobalInsts())
1275     return AM.Scale == 0 &&
1276            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1277                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1278                                     /*Signed=*/true));
1279 
1280   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1281       // Assume the we will use FLAT for all global memory accesses
1282       // on VI.
1283       // FIXME: This assumption is currently wrong.  On VI we still use
1284       // MUBUF instructions for the r + i addressing mode.  As currently
1285       // implemented, the MUBUF instructions only work on buffer < 4GB.
1286       // It may be possible to support > 4GB buffers with MUBUF instructions,
1287       // by setting the stride value in the resource descriptor which would
1288       // increase the size limit to (stride * 4GB).  However, this is risky,
1289       // because it has never been validated.
1290     return isLegalFlatAddressingMode(AM);
1291   }
1292 
1293   return isLegalMUBUFAddressingMode(AM);
1294 }
1295 
1296 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1297   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1298   // additionally can do r + r + i with addr64. 32-bit has more addressing
1299   // mode options. Depending on the resource constant, it can also do
1300   // (i64 r0) + (i32 r1) * (i14 i).
1301   //
1302   // Private arrays end up using a scratch buffer most of the time, so also
1303   // assume those use MUBUF instructions. Scratch loads / stores are currently
1304   // implemented as mubuf instructions with offen bit set, so slightly
1305   // different than the normal addr64.
1306   if (!isUInt<12>(AM.BaseOffs))
1307     return false;
1308 
1309   // FIXME: Since we can split immediate into soffset and immediate offset,
1310   // would it make sense to allow any immediate?
1311 
1312   switch (AM.Scale) {
1313   case 0: // r + i or just i, depending on HasBaseReg.
1314     return true;
1315   case 1:
1316     return true; // We have r + r or r + i.
1317   case 2:
1318     if (AM.HasBaseReg) {
1319       // Reject 2 * r + r.
1320       return false;
1321     }
1322 
1323     // Allow 2 * r as r + r
1324     // Or  2 * r + i is allowed as r + r + i.
1325     return true;
1326   default: // Don't allow n * r
1327     return false;
1328   }
1329 }
1330 
1331 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1332                                              const AddrMode &AM, Type *Ty,
1333                                              unsigned AS, Instruction *I) const {
1334   // No global is ever allowed as a base.
1335   if (AM.BaseGV)
1336     return false;
1337 
1338   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1339     return isLegalGlobalAddressingMode(AM);
1340 
1341   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1342       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1343       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1344     // If the offset isn't a multiple of 4, it probably isn't going to be
1345     // correctly aligned.
1346     // FIXME: Can we get the real alignment here?
1347     if (AM.BaseOffs % 4 != 0)
1348       return isLegalMUBUFAddressingMode(AM);
1349 
1350     // There are no SMRD extloads, so if we have to do a small type access we
1351     // will use a MUBUF load.
1352     // FIXME?: We also need to do this if unaligned, but we don't know the
1353     // alignment here.
1354     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1355       return isLegalGlobalAddressingMode(AM);
1356 
1357     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1358       // SMRD instructions have an 8-bit, dword offset on SI.
1359       if (!isUInt<8>(AM.BaseOffs / 4))
1360         return false;
1361     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1362       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1363       // in 8-bits, it can use a smaller encoding.
1364       if (!isUInt<32>(AM.BaseOffs / 4))
1365         return false;
1366     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1367       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1368       if (!isUInt<20>(AM.BaseOffs))
1369         return false;
1370     } else
1371       llvm_unreachable("unhandled generation");
1372 
1373     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1374       return true;
1375 
1376     if (AM.Scale == 1 && AM.HasBaseReg)
1377       return true;
1378 
1379     return false;
1380 
1381   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1382     return isLegalMUBUFAddressingMode(AM);
1383   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1384              AS == AMDGPUAS::REGION_ADDRESS) {
1385     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1386     // field.
1387     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1388     // an 8-bit dword offset but we don't know the alignment here.
1389     if (!isUInt<16>(AM.BaseOffs))
1390       return false;
1391 
1392     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1393       return true;
1394 
1395     if (AM.Scale == 1 && AM.HasBaseReg)
1396       return true;
1397 
1398     return false;
1399   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1400              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1401     // For an unknown address space, this usually means that this is for some
1402     // reason being used for pure arithmetic, and not based on some addressing
1403     // computation. We don't have instructions that compute pointers with any
1404     // addressing modes, so treat them as having no offset like flat
1405     // instructions.
1406     return isLegalFlatAddressingMode(AM);
1407   }
1408 
1409   // Assume a user alias of global for unknown address spaces.
1410   return isLegalGlobalAddressingMode(AM);
1411 }
1412 
1413 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1414                                         const SelectionDAG &DAG) const {
1415   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1416     return (MemVT.getSizeInBits() <= 4 * 32);
1417   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1418     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1419     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1420   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1421     return (MemVT.getSizeInBits() <= 2 * 32);
1422   }
1423   return true;
1424 }
1425 
1426 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1427     unsigned Size, unsigned AddrSpace, Align Alignment,
1428     MachineMemOperand::Flags Flags, bool *IsFast) const {
1429   if (IsFast)
1430     *IsFast = false;
1431 
1432   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1433       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1434     // Check if alignment requirements for ds_read/write instructions are
1435     // disabled.
1436     if (Subtarget->hasUnalignedDSAccessEnabled() &&
1437         !Subtarget->hasLDSMisalignedBug()) {
1438       if (IsFast)
1439         *IsFast = Alignment != Align(2);
1440       return true;
1441     }
1442 
1443     if (Size == 64) {
1444       // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1445       // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1446       // with adjacent offsets.
1447       bool AlignedBy4 = Alignment >= Align(4);
1448       if (IsFast)
1449         *IsFast = AlignedBy4;
1450 
1451       return AlignedBy4;
1452     }
1453     if (Size == 96) {
1454       // ds_read/write_b96 require 16-byte alignment on gfx8 and older.
1455       bool Aligned = Alignment >= Align(16);
1456       if (IsFast)
1457         *IsFast = Aligned;
1458 
1459       return Aligned;
1460     }
1461     if (Size == 128) {
1462       // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we
1463       // can do a 8 byte aligned, 16 byte access in a single operation using
1464       // ds_read2/write2_b64.
1465       bool Aligned = Alignment >= Align(8);
1466       if (IsFast)
1467         *IsFast = Aligned;
1468 
1469       return Aligned;
1470     }
1471   }
1472 
1473   // FIXME: We have to be conservative here and assume that flat operations
1474   // will access scratch.  If we had access to the IR function, then we
1475   // could determine if any private memory was used in the function.
1476   if (!Subtarget->hasUnalignedScratchAccess() &&
1477       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1478        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1479     bool AlignedBy4 = Alignment >= Align(4);
1480     if (IsFast)
1481       *IsFast = AlignedBy4;
1482 
1483     return AlignedBy4;
1484   }
1485 
1486   if (Subtarget->hasUnalignedBufferAccessEnabled() &&
1487       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1488         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1489     // If we have an uniform constant load, it still requires using a slow
1490     // buffer instruction if unaligned.
1491     if (IsFast) {
1492       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1493       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1494       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1495                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1496         Alignment >= Align(4) : Alignment != Align(2);
1497     }
1498 
1499     return true;
1500   }
1501 
1502   // Smaller than dword value must be aligned.
1503   if (Size < 32)
1504     return false;
1505 
1506   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1507   // byte-address are ignored, thus forcing Dword alignment.
1508   // This applies to private, global, and constant memory.
1509   if (IsFast)
1510     *IsFast = true;
1511 
1512   return Size >= 32 && Alignment >= Align(4);
1513 }
1514 
1515 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1516     EVT VT, unsigned AddrSpace, unsigned Alignment,
1517     MachineMemOperand::Flags Flags, bool *IsFast) const {
1518   if (IsFast)
1519     *IsFast = false;
1520 
1521   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1522   // which isn't a simple VT.
1523   // Until MVT is extended to handle this, simply check for the size and
1524   // rely on the condition below: allow accesses if the size is a multiple of 4.
1525   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1526                            VT.getStoreSize() > 16)) {
1527     return false;
1528   }
1529 
1530   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1531                                             Align(Alignment), Flags, IsFast);
1532 }
1533 
1534 EVT SITargetLowering::getOptimalMemOpType(
1535     const MemOp &Op, const AttributeList &FuncAttributes) const {
1536   // FIXME: Should account for address space here.
1537 
1538   // The default fallback uses the private pointer size as a guess for a type to
1539   // use. Make sure we switch these to 64-bit accesses.
1540 
1541   if (Op.size() >= 16 &&
1542       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1543     return MVT::v4i32;
1544 
1545   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1546     return MVT::v2i32;
1547 
1548   // Use the default.
1549   return MVT::Other;
1550 }
1551 
1552 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1553   const MemSDNode *MemNode = cast<MemSDNode>(N);
1554   const Value *Ptr = MemNode->getMemOperand()->getValue();
1555   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1556   return I && I->getMetadata("amdgpu.noclobber");
1557 }
1558 
1559 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1560                                            unsigned DestAS) const {
1561   // Flat -> private/local is a simple truncate.
1562   // Flat -> global is no-op
1563   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1564     return true;
1565 
1566   const GCNTargetMachine &TM =
1567       static_cast<const GCNTargetMachine &>(getTargetMachine());
1568   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1569 }
1570 
1571 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1572   const MemSDNode *MemNode = cast<MemSDNode>(N);
1573 
1574   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1575 }
1576 
1577 TargetLoweringBase::LegalizeTypeAction
1578 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1579   int NumElts = VT.getVectorNumElements();
1580   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1581     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1582   return TargetLoweringBase::getPreferredVectorAction(VT);
1583 }
1584 
1585 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1586                                                          Type *Ty) const {
1587   // FIXME: Could be smarter if called for vector constants.
1588   return true;
1589 }
1590 
1591 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1592   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1593     switch (Op) {
1594     case ISD::LOAD:
1595     case ISD::STORE:
1596 
1597     // These operations are done with 32-bit instructions anyway.
1598     case ISD::AND:
1599     case ISD::OR:
1600     case ISD::XOR:
1601     case ISD::SELECT:
1602       // TODO: Extensions?
1603       return true;
1604     default:
1605       return false;
1606     }
1607   }
1608 
1609   // SimplifySetCC uses this function to determine whether or not it should
1610   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1611   if (VT == MVT::i1 && Op == ISD::SETCC)
1612     return false;
1613 
1614   return TargetLowering::isTypeDesirableForOp(Op, VT);
1615 }
1616 
1617 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1618                                                    const SDLoc &SL,
1619                                                    SDValue Chain,
1620                                                    uint64_t Offset) const {
1621   const DataLayout &DL = DAG.getDataLayout();
1622   MachineFunction &MF = DAG.getMachineFunction();
1623   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1624 
1625   const ArgDescriptor *InputPtrReg;
1626   const TargetRegisterClass *RC;
1627   LLT ArgTy;
1628 
1629   std::tie(InputPtrReg, RC, ArgTy) =
1630       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1631 
1632   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1633   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1634   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1635     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1636 
1637   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1638 }
1639 
1640 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1641                                             const SDLoc &SL) const {
1642   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1643                                                FIRST_IMPLICIT);
1644   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1645 }
1646 
1647 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1648                                          const SDLoc &SL, SDValue Val,
1649                                          bool Signed,
1650                                          const ISD::InputArg *Arg) const {
1651   // First, if it is a widened vector, narrow it.
1652   if (VT.isVector() &&
1653       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1654     EVT NarrowedVT =
1655         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1656                          VT.getVectorNumElements());
1657     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1658                       DAG.getConstant(0, SL, MVT::i32));
1659   }
1660 
1661   // Then convert the vector elements or scalar value.
1662   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1663       VT.bitsLT(MemVT)) {
1664     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1665     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1666   }
1667 
1668   if (MemVT.isFloatingPoint())
1669     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1670   else if (Signed)
1671     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1672   else
1673     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1674 
1675   return Val;
1676 }
1677 
1678 SDValue SITargetLowering::lowerKernargMemParameter(
1679     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1680     uint64_t Offset, Align Alignment, bool Signed,
1681     const ISD::InputArg *Arg) const {
1682   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1683 
1684   // Try to avoid using an extload by loading earlier than the argument address,
1685   // and extracting the relevant bits. The load should hopefully be merged with
1686   // the previous argument.
1687   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1688     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1689     int64_t AlignDownOffset = alignDown(Offset, 4);
1690     int64_t OffsetDiff = Offset - AlignDownOffset;
1691 
1692     EVT IntVT = MemVT.changeTypeToInteger();
1693 
1694     // TODO: If we passed in the base kernel offset we could have a better
1695     // alignment than 4, but we don't really need it.
1696     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1697     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1698                                MachineMemOperand::MODereferenceable |
1699                                    MachineMemOperand::MOInvariant);
1700 
1701     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1702     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1703 
1704     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1705     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1706     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1707 
1708 
1709     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1710   }
1711 
1712   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1713   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1714                              MachineMemOperand::MODereferenceable |
1715                                  MachineMemOperand::MOInvariant);
1716 
1717   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1718   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1719 }
1720 
1721 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1722                                               const SDLoc &SL, SDValue Chain,
1723                                               const ISD::InputArg &Arg) const {
1724   MachineFunction &MF = DAG.getMachineFunction();
1725   MachineFrameInfo &MFI = MF.getFrameInfo();
1726 
1727   if (Arg.Flags.isByVal()) {
1728     unsigned Size = Arg.Flags.getByValSize();
1729     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1730     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1731   }
1732 
1733   unsigned ArgOffset = VA.getLocMemOffset();
1734   unsigned ArgSize = VA.getValVT().getStoreSize();
1735 
1736   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1737 
1738   // Create load nodes to retrieve arguments from the stack.
1739   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1740   SDValue ArgValue;
1741 
1742   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1743   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1744   MVT MemVT = VA.getValVT();
1745 
1746   switch (VA.getLocInfo()) {
1747   default:
1748     break;
1749   case CCValAssign::BCvt:
1750     MemVT = VA.getLocVT();
1751     break;
1752   case CCValAssign::SExt:
1753     ExtType = ISD::SEXTLOAD;
1754     break;
1755   case CCValAssign::ZExt:
1756     ExtType = ISD::ZEXTLOAD;
1757     break;
1758   case CCValAssign::AExt:
1759     ExtType = ISD::EXTLOAD;
1760     break;
1761   }
1762 
1763   ArgValue = DAG.getExtLoad(
1764     ExtType, SL, VA.getLocVT(), Chain, FIN,
1765     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1766     MemVT);
1767   return ArgValue;
1768 }
1769 
1770 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1771   const SIMachineFunctionInfo &MFI,
1772   EVT VT,
1773   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1774   const ArgDescriptor *Reg;
1775   const TargetRegisterClass *RC;
1776   LLT Ty;
1777 
1778   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1779   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1780 }
1781 
1782 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1783                                    CallingConv::ID CallConv,
1784                                    ArrayRef<ISD::InputArg> Ins,
1785                                    BitVector &Skipped,
1786                                    FunctionType *FType,
1787                                    SIMachineFunctionInfo *Info) {
1788   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1789     const ISD::InputArg *Arg = &Ins[I];
1790 
1791     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1792            "vector type argument should have been split");
1793 
1794     // First check if it's a PS input addr.
1795     if (CallConv == CallingConv::AMDGPU_PS &&
1796         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1797       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1798 
1799       // Inconveniently only the first part of the split is marked as isSplit,
1800       // so skip to the end. We only want to increment PSInputNum once for the
1801       // entire split argument.
1802       if (Arg->Flags.isSplit()) {
1803         while (!Arg->Flags.isSplitEnd()) {
1804           assert((!Arg->VT.isVector() ||
1805                   Arg->VT.getScalarSizeInBits() == 16) &&
1806                  "unexpected vector split in ps argument type");
1807           if (!SkipArg)
1808             Splits.push_back(*Arg);
1809           Arg = &Ins[++I];
1810         }
1811       }
1812 
1813       if (SkipArg) {
1814         // We can safely skip PS inputs.
1815         Skipped.set(Arg->getOrigArgIndex());
1816         ++PSInputNum;
1817         continue;
1818       }
1819 
1820       Info->markPSInputAllocated(PSInputNum);
1821       if (Arg->Used)
1822         Info->markPSInputEnabled(PSInputNum);
1823 
1824       ++PSInputNum;
1825     }
1826 
1827     Splits.push_back(*Arg);
1828   }
1829 }
1830 
1831 // Allocate special inputs passed in VGPRs.
1832 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1833                                                       MachineFunction &MF,
1834                                                       const SIRegisterInfo &TRI,
1835                                                       SIMachineFunctionInfo &Info) const {
1836   const LLT S32 = LLT::scalar(32);
1837   MachineRegisterInfo &MRI = MF.getRegInfo();
1838 
1839   if (Info.hasWorkItemIDX()) {
1840     Register Reg = AMDGPU::VGPR0;
1841     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1842 
1843     CCInfo.AllocateReg(Reg);
1844     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1845   }
1846 
1847   if (Info.hasWorkItemIDY()) {
1848     Register Reg = AMDGPU::VGPR1;
1849     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1850 
1851     CCInfo.AllocateReg(Reg);
1852     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1853   }
1854 
1855   if (Info.hasWorkItemIDZ()) {
1856     Register Reg = AMDGPU::VGPR2;
1857     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1858 
1859     CCInfo.AllocateReg(Reg);
1860     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1861   }
1862 }
1863 
1864 // Try to allocate a VGPR at the end of the argument list, or if no argument
1865 // VGPRs are left allocating a stack slot.
1866 // If \p Mask is is given it indicates bitfield position in the register.
1867 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1868 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1869                                          ArgDescriptor Arg = ArgDescriptor()) {
1870   if (Arg.isSet())
1871     return ArgDescriptor::createArg(Arg, Mask);
1872 
1873   ArrayRef<MCPhysReg> ArgVGPRs
1874     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1875   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1876   if (RegIdx == ArgVGPRs.size()) {
1877     // Spill to stack required.
1878     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1879 
1880     return ArgDescriptor::createStack(Offset, Mask);
1881   }
1882 
1883   unsigned Reg = ArgVGPRs[RegIdx];
1884   Reg = CCInfo.AllocateReg(Reg);
1885   assert(Reg != AMDGPU::NoRegister);
1886 
1887   MachineFunction &MF = CCInfo.getMachineFunction();
1888   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1889   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1890   return ArgDescriptor::createRegister(Reg, Mask);
1891 }
1892 
1893 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1894                                              const TargetRegisterClass *RC,
1895                                              unsigned NumArgRegs) {
1896   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1897   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1898   if (RegIdx == ArgSGPRs.size())
1899     report_fatal_error("ran out of SGPRs for arguments");
1900 
1901   unsigned Reg = ArgSGPRs[RegIdx];
1902   Reg = CCInfo.AllocateReg(Reg);
1903   assert(Reg != AMDGPU::NoRegister);
1904 
1905   MachineFunction &MF = CCInfo.getMachineFunction();
1906   MF.addLiveIn(Reg, RC);
1907   return ArgDescriptor::createRegister(Reg);
1908 }
1909 
1910 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1911   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1912 }
1913 
1914 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1915   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1916 }
1917 
1918 /// Allocate implicit function VGPR arguments at the end of allocated user
1919 /// arguments.
1920 void SITargetLowering::allocateSpecialInputVGPRs(
1921   CCState &CCInfo, MachineFunction &MF,
1922   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1923   const unsigned Mask = 0x3ff;
1924   ArgDescriptor Arg;
1925 
1926   if (Info.hasWorkItemIDX()) {
1927     Arg = allocateVGPR32Input(CCInfo, Mask);
1928     Info.setWorkItemIDX(Arg);
1929   }
1930 
1931   if (Info.hasWorkItemIDY()) {
1932     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1933     Info.setWorkItemIDY(Arg);
1934   }
1935 
1936   if (Info.hasWorkItemIDZ())
1937     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1938 }
1939 
1940 /// Allocate implicit function VGPR arguments in fixed registers.
1941 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1942   CCState &CCInfo, MachineFunction &MF,
1943   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1944   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1945   if (!Reg)
1946     report_fatal_error("failed to allocated VGPR for implicit arguments");
1947 
1948   const unsigned Mask = 0x3ff;
1949   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1950   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1951   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1952 }
1953 
1954 void SITargetLowering::allocateSpecialInputSGPRs(
1955   CCState &CCInfo,
1956   MachineFunction &MF,
1957   const SIRegisterInfo &TRI,
1958   SIMachineFunctionInfo &Info) const {
1959   auto &ArgInfo = Info.getArgInfo();
1960 
1961   // TODO: Unify handling with private memory pointers.
1962 
1963   if (Info.hasDispatchPtr())
1964     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1965 
1966   if (Info.hasQueuePtr())
1967     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1968 
1969   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1970   // constant offset from the kernarg segment.
1971   if (Info.hasImplicitArgPtr())
1972     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1973 
1974   if (Info.hasDispatchID())
1975     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1976 
1977   // flat_scratch_init is not applicable for non-kernel functions.
1978 
1979   if (Info.hasWorkGroupIDX())
1980     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1981 
1982   if (Info.hasWorkGroupIDY())
1983     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1984 
1985   if (Info.hasWorkGroupIDZ())
1986     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1987 }
1988 
1989 // Allocate special inputs passed in user SGPRs.
1990 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1991                                             MachineFunction &MF,
1992                                             const SIRegisterInfo &TRI,
1993                                             SIMachineFunctionInfo &Info) const {
1994   if (Info.hasImplicitBufferPtr()) {
1995     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1996     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1997     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1998   }
1999 
2000   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2001   if (Info.hasPrivateSegmentBuffer()) {
2002     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2003     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2004     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2005   }
2006 
2007   if (Info.hasDispatchPtr()) {
2008     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2009     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2010     CCInfo.AllocateReg(DispatchPtrReg);
2011   }
2012 
2013   if (Info.hasQueuePtr()) {
2014     Register QueuePtrReg = Info.addQueuePtr(TRI);
2015     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2016     CCInfo.AllocateReg(QueuePtrReg);
2017   }
2018 
2019   if (Info.hasKernargSegmentPtr()) {
2020     MachineRegisterInfo &MRI = MF.getRegInfo();
2021     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2022     CCInfo.AllocateReg(InputPtrReg);
2023 
2024     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2025     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2026   }
2027 
2028   if (Info.hasDispatchID()) {
2029     Register DispatchIDReg = Info.addDispatchID(TRI);
2030     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2031     CCInfo.AllocateReg(DispatchIDReg);
2032   }
2033 
2034   if (Info.hasFlatScratchInit()) {
2035     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2036     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2037     CCInfo.AllocateReg(FlatScratchInitReg);
2038   }
2039 
2040   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2041   // these from the dispatch pointer.
2042 }
2043 
2044 // Allocate special input registers that are initialized per-wave.
2045 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2046                                            MachineFunction &MF,
2047                                            SIMachineFunctionInfo &Info,
2048                                            CallingConv::ID CallConv,
2049                                            bool IsShader) const {
2050   if (Info.hasWorkGroupIDX()) {
2051     Register Reg = Info.addWorkGroupIDX();
2052     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2053     CCInfo.AllocateReg(Reg);
2054   }
2055 
2056   if (Info.hasWorkGroupIDY()) {
2057     Register Reg = Info.addWorkGroupIDY();
2058     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2059     CCInfo.AllocateReg(Reg);
2060   }
2061 
2062   if (Info.hasWorkGroupIDZ()) {
2063     Register Reg = Info.addWorkGroupIDZ();
2064     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2065     CCInfo.AllocateReg(Reg);
2066   }
2067 
2068   if (Info.hasWorkGroupInfo()) {
2069     Register Reg = Info.addWorkGroupInfo();
2070     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2071     CCInfo.AllocateReg(Reg);
2072   }
2073 
2074   if (Info.hasPrivateSegmentWaveByteOffset()) {
2075     // Scratch wave offset passed in system SGPR.
2076     unsigned PrivateSegmentWaveByteOffsetReg;
2077 
2078     if (IsShader) {
2079       PrivateSegmentWaveByteOffsetReg =
2080         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2081 
2082       // This is true if the scratch wave byte offset doesn't have a fixed
2083       // location.
2084       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2085         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2086         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2087       }
2088     } else
2089       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2090 
2091     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2092     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2093   }
2094 }
2095 
2096 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2097                                      MachineFunction &MF,
2098                                      const SIRegisterInfo &TRI,
2099                                      SIMachineFunctionInfo &Info) {
2100   // Now that we've figured out where the scratch register inputs are, see if
2101   // should reserve the arguments and use them directly.
2102   MachineFrameInfo &MFI = MF.getFrameInfo();
2103   bool HasStackObjects = MFI.hasStackObjects();
2104   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2105 
2106   // Record that we know we have non-spill stack objects so we don't need to
2107   // check all stack objects later.
2108   if (HasStackObjects)
2109     Info.setHasNonSpillStackObjects(true);
2110 
2111   // Everything live out of a block is spilled with fast regalloc, so it's
2112   // almost certain that spilling will be required.
2113   if (TM.getOptLevel() == CodeGenOpt::None)
2114     HasStackObjects = true;
2115 
2116   // For now assume stack access is needed in any callee functions, so we need
2117   // the scratch registers to pass in.
2118   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2119 
2120   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2121     // If we have stack objects, we unquestionably need the private buffer
2122     // resource. For the Code Object V2 ABI, this will be the first 4 user
2123     // SGPR inputs. We can reserve those and use them directly.
2124 
2125     Register PrivateSegmentBufferReg =
2126         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2127     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2128   } else {
2129     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2130     // We tentatively reserve the last registers (skipping the last registers
2131     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2132     // we'll replace these with the ones immediately after those which were
2133     // really allocated. In the prologue copies will be inserted from the
2134     // argument to these reserved registers.
2135 
2136     // Without HSA, relocations are used for the scratch pointer and the
2137     // buffer resource setup is always inserted in the prologue. Scratch wave
2138     // offset is still in an input SGPR.
2139     Info.setScratchRSrcReg(ReservedBufferReg);
2140   }
2141 
2142   MachineRegisterInfo &MRI = MF.getRegInfo();
2143 
2144   // For entry functions we have to set up the stack pointer if we use it,
2145   // whereas non-entry functions get this "for free". This means there is no
2146   // intrinsic advantage to using S32 over S34 in cases where we do not have
2147   // calls but do need a frame pointer (i.e. if we are requested to have one
2148   // because frame pointer elimination is disabled). To keep things simple we
2149   // only ever use S32 as the call ABI stack pointer, and so using it does not
2150   // imply we need a separate frame pointer.
2151   //
2152   // Try to use s32 as the SP, but move it if it would interfere with input
2153   // arguments. This won't work with calls though.
2154   //
2155   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2156   // registers.
2157   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2158     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2159   } else {
2160     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2161 
2162     if (MFI.hasCalls())
2163       report_fatal_error("call in graphics shader with too many input SGPRs");
2164 
2165     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2166       if (!MRI.isLiveIn(Reg)) {
2167         Info.setStackPtrOffsetReg(Reg);
2168         break;
2169       }
2170     }
2171 
2172     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2173       report_fatal_error("failed to find register for SP");
2174   }
2175 
2176   // hasFP should be accurate for entry functions even before the frame is
2177   // finalized, because it does not rely on the known stack size, only
2178   // properties like whether variable sized objects are present.
2179   if (ST.getFrameLowering()->hasFP(MF)) {
2180     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2181   }
2182 }
2183 
2184 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2185   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2186   return !Info->isEntryFunction();
2187 }
2188 
2189 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2190 
2191 }
2192 
2193 void SITargetLowering::insertCopiesSplitCSR(
2194   MachineBasicBlock *Entry,
2195   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2196   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2197 
2198   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2199   if (!IStart)
2200     return;
2201 
2202   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2203   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2204   MachineBasicBlock::iterator MBBI = Entry->begin();
2205   for (const MCPhysReg *I = IStart; *I; ++I) {
2206     const TargetRegisterClass *RC = nullptr;
2207     if (AMDGPU::SReg_64RegClass.contains(*I))
2208       RC = &AMDGPU::SGPR_64RegClass;
2209     else if (AMDGPU::SReg_32RegClass.contains(*I))
2210       RC = &AMDGPU::SGPR_32RegClass;
2211     else
2212       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2213 
2214     Register NewVR = MRI->createVirtualRegister(RC);
2215     // Create copy from CSR to a virtual register.
2216     Entry->addLiveIn(*I);
2217     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2218       .addReg(*I);
2219 
2220     // Insert the copy-back instructions right before the terminator.
2221     for (auto *Exit : Exits)
2222       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2223               TII->get(TargetOpcode::COPY), *I)
2224         .addReg(NewVR);
2225   }
2226 }
2227 
2228 SDValue SITargetLowering::LowerFormalArguments(
2229     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2230     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2231     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2232   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2233 
2234   MachineFunction &MF = DAG.getMachineFunction();
2235   const Function &Fn = MF.getFunction();
2236   FunctionType *FType = MF.getFunction().getFunctionType();
2237   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2238 
2239   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2240     DiagnosticInfoUnsupported NoGraphicsHSA(
2241         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2242     DAG.getContext()->diagnose(NoGraphicsHSA);
2243     return DAG.getEntryNode();
2244   }
2245 
2246   SmallVector<ISD::InputArg, 16> Splits;
2247   SmallVector<CCValAssign, 16> ArgLocs;
2248   BitVector Skipped(Ins.size());
2249   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2250                  *DAG.getContext());
2251 
2252   bool IsShader = AMDGPU::isShader(CallConv);
2253   bool IsKernel = AMDGPU::isKernel(CallConv);
2254   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2255 
2256   if (IsShader) {
2257     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2258 
2259     // At least one interpolation mode must be enabled or else the GPU will
2260     // hang.
2261     //
2262     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2263     // set PSInputAddr, the user wants to enable some bits after the compilation
2264     // based on run-time states. Since we can't know what the final PSInputEna
2265     // will look like, so we shouldn't do anything here and the user should take
2266     // responsibility for the correct programming.
2267     //
2268     // Otherwise, the following restrictions apply:
2269     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2270     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2271     //   enabled too.
2272     if (CallConv == CallingConv::AMDGPU_PS) {
2273       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2274            ((Info->getPSInputAddr() & 0xF) == 0 &&
2275             Info->isPSInputAllocated(11))) {
2276         CCInfo.AllocateReg(AMDGPU::VGPR0);
2277         CCInfo.AllocateReg(AMDGPU::VGPR1);
2278         Info->markPSInputAllocated(0);
2279         Info->markPSInputEnabled(0);
2280       }
2281       if (Subtarget->isAmdPalOS()) {
2282         // For isAmdPalOS, the user does not enable some bits after compilation
2283         // based on run-time states; the register values being generated here are
2284         // the final ones set in hardware. Therefore we need to apply the
2285         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2286         // a bit is set in PSInputAddr but not PSInputEnable is where the
2287         // frontend set up an input arg for a particular interpolation mode, but
2288         // nothing uses that input arg. Really we should have an earlier pass
2289         // that removes such an arg.)
2290         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2291         if ((PsInputBits & 0x7F) == 0 ||
2292             ((PsInputBits & 0xF) == 0 &&
2293              (PsInputBits >> 11 & 1)))
2294           Info->markPSInputEnabled(
2295               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2296       }
2297     }
2298 
2299     assert(!Info->hasDispatchPtr() &&
2300            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2301            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2302            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2303            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2304            !Info->hasWorkItemIDZ());
2305   } else if (IsKernel) {
2306     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2307   } else {
2308     Splits.append(Ins.begin(), Ins.end());
2309   }
2310 
2311   if (IsEntryFunc) {
2312     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2313     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2314   } else {
2315     // For the fixed ABI, pass workitem IDs in the last argument register.
2316     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2317       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2318   }
2319 
2320   if (IsKernel) {
2321     analyzeFormalArgumentsCompute(CCInfo, Ins);
2322   } else {
2323     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2324     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2325   }
2326 
2327   SmallVector<SDValue, 16> Chains;
2328 
2329   // FIXME: This is the minimum kernel argument alignment. We should improve
2330   // this to the maximum alignment of the arguments.
2331   //
2332   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2333   // kern arg offset.
2334   const Align KernelArgBaseAlign = Align(16);
2335 
2336   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2337     const ISD::InputArg &Arg = Ins[i];
2338     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2339       InVals.push_back(DAG.getUNDEF(Arg.VT));
2340       continue;
2341     }
2342 
2343     CCValAssign &VA = ArgLocs[ArgIdx++];
2344     MVT VT = VA.getLocVT();
2345 
2346     if (IsEntryFunc && VA.isMemLoc()) {
2347       VT = Ins[i].VT;
2348       EVT MemVT = VA.getLocVT();
2349 
2350       const uint64_t Offset = VA.getLocMemOffset();
2351       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2352 
2353       if (Arg.Flags.isByRef()) {
2354         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2355 
2356         const GCNTargetMachine &TM =
2357             static_cast<const GCNTargetMachine &>(getTargetMachine());
2358         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2359                                     Arg.Flags.getPointerAddrSpace())) {
2360           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2361                                      Arg.Flags.getPointerAddrSpace());
2362         }
2363 
2364         InVals.push_back(Ptr);
2365         continue;
2366       }
2367 
2368       SDValue Arg = lowerKernargMemParameter(
2369         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2370       Chains.push_back(Arg.getValue(1));
2371 
2372       auto *ParamTy =
2373         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2374       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2375           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2376                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2377         // On SI local pointers are just offsets into LDS, so they are always
2378         // less than 16-bits.  On CI and newer they could potentially be
2379         // real pointers, so we can't guarantee their size.
2380         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2381                           DAG.getValueType(MVT::i16));
2382       }
2383 
2384       InVals.push_back(Arg);
2385       continue;
2386     } else if (!IsEntryFunc && VA.isMemLoc()) {
2387       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2388       InVals.push_back(Val);
2389       if (!Arg.Flags.isByVal())
2390         Chains.push_back(Val.getValue(1));
2391       continue;
2392     }
2393 
2394     assert(VA.isRegLoc() && "Parameter must be in a register!");
2395 
2396     Register Reg = VA.getLocReg();
2397     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2398     EVT ValVT = VA.getValVT();
2399 
2400     Reg = MF.addLiveIn(Reg, RC);
2401     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2402 
2403     if (Arg.Flags.isSRet()) {
2404       // The return object should be reasonably addressable.
2405 
2406       // FIXME: This helps when the return is a real sret. If it is a
2407       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2408       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2409       unsigned NumBits
2410         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2411       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2412         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2413     }
2414 
2415     // If this is an 8 or 16-bit value, it is really passed promoted
2416     // to 32 bits. Insert an assert[sz]ext to capture this, then
2417     // truncate to the right size.
2418     switch (VA.getLocInfo()) {
2419     case CCValAssign::Full:
2420       break;
2421     case CCValAssign::BCvt:
2422       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2423       break;
2424     case CCValAssign::SExt:
2425       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2426                         DAG.getValueType(ValVT));
2427       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2428       break;
2429     case CCValAssign::ZExt:
2430       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2431                         DAG.getValueType(ValVT));
2432       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2433       break;
2434     case CCValAssign::AExt:
2435       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2436       break;
2437     default:
2438       llvm_unreachable("Unknown loc info!");
2439     }
2440 
2441     InVals.push_back(Val);
2442   }
2443 
2444   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2445     // Special inputs come after user arguments.
2446     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2447   }
2448 
2449   // Start adding system SGPRs.
2450   if (IsEntryFunc) {
2451     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2452   } else {
2453     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2454     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2455   }
2456 
2457   auto &ArgUsageInfo =
2458     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2459   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2460 
2461   unsigned StackArgSize = CCInfo.getNextStackOffset();
2462   Info->setBytesInStackArgArea(StackArgSize);
2463 
2464   return Chains.empty() ? Chain :
2465     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2466 }
2467 
2468 // TODO: If return values can't fit in registers, we should return as many as
2469 // possible in registers before passing on stack.
2470 bool SITargetLowering::CanLowerReturn(
2471   CallingConv::ID CallConv,
2472   MachineFunction &MF, bool IsVarArg,
2473   const SmallVectorImpl<ISD::OutputArg> &Outs,
2474   LLVMContext &Context) const {
2475   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2476   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2477   // for shaders. Vector types should be explicitly handled by CC.
2478   if (AMDGPU::isEntryFunctionCC(CallConv))
2479     return true;
2480 
2481   SmallVector<CCValAssign, 16> RVLocs;
2482   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2483   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2484 }
2485 
2486 SDValue
2487 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2488                               bool isVarArg,
2489                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2490                               const SmallVectorImpl<SDValue> &OutVals,
2491                               const SDLoc &DL, SelectionDAG &DAG) const {
2492   MachineFunction &MF = DAG.getMachineFunction();
2493   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2494 
2495   if (AMDGPU::isKernel(CallConv)) {
2496     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2497                                              OutVals, DL, DAG);
2498   }
2499 
2500   bool IsShader = AMDGPU::isShader(CallConv);
2501 
2502   Info->setIfReturnsVoid(Outs.empty());
2503   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2504 
2505   // CCValAssign - represent the assignment of the return value to a location.
2506   SmallVector<CCValAssign, 48> RVLocs;
2507   SmallVector<ISD::OutputArg, 48> Splits;
2508 
2509   // CCState - Info about the registers and stack slots.
2510   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2511                  *DAG.getContext());
2512 
2513   // Analyze outgoing return values.
2514   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2515 
2516   SDValue Flag;
2517   SmallVector<SDValue, 48> RetOps;
2518   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2519 
2520   // Add return address for callable functions.
2521   if (!Info->isEntryFunction()) {
2522     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2523     SDValue ReturnAddrReg = CreateLiveInRegister(
2524       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2525 
2526     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2527         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2528         MVT::i64);
2529     Chain =
2530         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2531     Flag = Chain.getValue(1);
2532     RetOps.push_back(ReturnAddrVirtualReg);
2533   }
2534 
2535   // Copy the result values into the output registers.
2536   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2537        ++I, ++RealRVLocIdx) {
2538     CCValAssign &VA = RVLocs[I];
2539     assert(VA.isRegLoc() && "Can only return in registers!");
2540     // TODO: Partially return in registers if return values don't fit.
2541     SDValue Arg = OutVals[RealRVLocIdx];
2542 
2543     // Copied from other backends.
2544     switch (VA.getLocInfo()) {
2545     case CCValAssign::Full:
2546       break;
2547     case CCValAssign::BCvt:
2548       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2549       break;
2550     case CCValAssign::SExt:
2551       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2552       break;
2553     case CCValAssign::ZExt:
2554       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2555       break;
2556     case CCValAssign::AExt:
2557       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2558       break;
2559     default:
2560       llvm_unreachable("Unknown loc info!");
2561     }
2562 
2563     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2564     Flag = Chain.getValue(1);
2565     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2566   }
2567 
2568   // FIXME: Does sret work properly?
2569   if (!Info->isEntryFunction()) {
2570     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2571     const MCPhysReg *I =
2572       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2573     if (I) {
2574       for (; *I; ++I) {
2575         if (AMDGPU::SReg_64RegClass.contains(*I))
2576           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2577         else if (AMDGPU::SReg_32RegClass.contains(*I))
2578           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2579         else
2580           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2581       }
2582     }
2583   }
2584 
2585   // Update chain and glue.
2586   RetOps[0] = Chain;
2587   if (Flag.getNode())
2588     RetOps.push_back(Flag);
2589 
2590   unsigned Opc = AMDGPUISD::ENDPGM;
2591   if (!IsWaveEnd)
2592     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2593   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2594 }
2595 
2596 SDValue SITargetLowering::LowerCallResult(
2597     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2598     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2599     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2600     SDValue ThisVal) const {
2601   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2602 
2603   // Assign locations to each value returned by this call.
2604   SmallVector<CCValAssign, 16> RVLocs;
2605   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2606                  *DAG.getContext());
2607   CCInfo.AnalyzeCallResult(Ins, RetCC);
2608 
2609   // Copy all of the result registers out of their specified physreg.
2610   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2611     CCValAssign VA = RVLocs[i];
2612     SDValue Val;
2613 
2614     if (VA.isRegLoc()) {
2615       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2616       Chain = Val.getValue(1);
2617       InFlag = Val.getValue(2);
2618     } else if (VA.isMemLoc()) {
2619       report_fatal_error("TODO: return values in memory");
2620     } else
2621       llvm_unreachable("unknown argument location type");
2622 
2623     switch (VA.getLocInfo()) {
2624     case CCValAssign::Full:
2625       break;
2626     case CCValAssign::BCvt:
2627       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2628       break;
2629     case CCValAssign::ZExt:
2630       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2631                         DAG.getValueType(VA.getValVT()));
2632       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2633       break;
2634     case CCValAssign::SExt:
2635       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2636                         DAG.getValueType(VA.getValVT()));
2637       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2638       break;
2639     case CCValAssign::AExt:
2640       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2641       break;
2642     default:
2643       llvm_unreachable("Unknown loc info!");
2644     }
2645 
2646     InVals.push_back(Val);
2647   }
2648 
2649   return Chain;
2650 }
2651 
2652 // Add code to pass special inputs required depending on used features separate
2653 // from the explicit user arguments present in the IR.
2654 void SITargetLowering::passSpecialInputs(
2655     CallLoweringInfo &CLI,
2656     CCState &CCInfo,
2657     const SIMachineFunctionInfo &Info,
2658     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2659     SmallVectorImpl<SDValue> &MemOpChains,
2660     SDValue Chain) const {
2661   // If we don't have a call site, this was a call inserted by
2662   // legalization. These can never use special inputs.
2663   if (!CLI.CB)
2664     return;
2665 
2666   SelectionDAG &DAG = CLI.DAG;
2667   const SDLoc &DL = CLI.DL;
2668 
2669   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2670   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2671 
2672   const AMDGPUFunctionArgInfo *CalleeArgInfo
2673     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2674   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2675     auto &ArgUsageInfo =
2676       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2677     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2678   }
2679 
2680   // TODO: Unify with private memory register handling. This is complicated by
2681   // the fact that at least in kernels, the input argument is not necessarily
2682   // in the same location as the input.
2683   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2684     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2685     AMDGPUFunctionArgInfo::QUEUE_PTR,
2686     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2687     AMDGPUFunctionArgInfo::DISPATCH_ID,
2688     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2689     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2690     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2691   };
2692 
2693   for (auto InputID : InputRegs) {
2694     const ArgDescriptor *OutgoingArg;
2695     const TargetRegisterClass *ArgRC;
2696     LLT ArgTy;
2697 
2698     std::tie(OutgoingArg, ArgRC, ArgTy) =
2699         CalleeArgInfo->getPreloadedValue(InputID);
2700     if (!OutgoingArg)
2701       continue;
2702 
2703     const ArgDescriptor *IncomingArg;
2704     const TargetRegisterClass *IncomingArgRC;
2705     LLT Ty;
2706     std::tie(IncomingArg, IncomingArgRC, Ty) =
2707         CallerArgInfo.getPreloadedValue(InputID);
2708     assert(IncomingArgRC == ArgRC);
2709 
2710     // All special arguments are ints for now.
2711     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2712     SDValue InputReg;
2713 
2714     if (IncomingArg) {
2715       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2716     } else {
2717       // The implicit arg ptr is special because it doesn't have a corresponding
2718       // input for kernels, and is computed from the kernarg segment pointer.
2719       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2720       InputReg = getImplicitArgPtr(DAG, DL);
2721     }
2722 
2723     if (OutgoingArg->isRegister()) {
2724       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2725       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2726         report_fatal_error("failed to allocate implicit input argument");
2727     } else {
2728       unsigned SpecialArgOffset =
2729           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2730       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2731                                               SpecialArgOffset);
2732       MemOpChains.push_back(ArgStore);
2733     }
2734   }
2735 
2736   // Pack workitem IDs into a single register or pass it as is if already
2737   // packed.
2738   const ArgDescriptor *OutgoingArg;
2739   const TargetRegisterClass *ArgRC;
2740   LLT Ty;
2741 
2742   std::tie(OutgoingArg, ArgRC, Ty) =
2743       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2744   if (!OutgoingArg)
2745     std::tie(OutgoingArg, ArgRC, Ty) =
2746         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2747   if (!OutgoingArg)
2748     std::tie(OutgoingArg, ArgRC, Ty) =
2749         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2750   if (!OutgoingArg)
2751     return;
2752 
2753   const ArgDescriptor *IncomingArgX = std::get<0>(
2754       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2755   const ArgDescriptor *IncomingArgY = std::get<0>(
2756       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2757   const ArgDescriptor *IncomingArgZ = std::get<0>(
2758       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2759 
2760   SDValue InputReg;
2761   SDLoc SL;
2762 
2763   // If incoming ids are not packed we need to pack them.
2764   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2765     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2766 
2767   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2768     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2769     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2770                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2771     InputReg = InputReg.getNode() ?
2772                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2773   }
2774 
2775   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2776     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2777     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2778                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2779     InputReg = InputReg.getNode() ?
2780                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2781   }
2782 
2783   if (!InputReg.getNode()) {
2784     // Workitem ids are already packed, any of present incoming arguments
2785     // will carry all required fields.
2786     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2787       IncomingArgX ? *IncomingArgX :
2788       IncomingArgY ? *IncomingArgY :
2789                      *IncomingArgZ, ~0u);
2790     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2791   }
2792 
2793   if (OutgoingArg->isRegister()) {
2794     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2795     CCInfo.AllocateReg(OutgoingArg->getRegister());
2796   } else {
2797     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2798     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2799                                             SpecialArgOffset);
2800     MemOpChains.push_back(ArgStore);
2801   }
2802 }
2803 
2804 static bool canGuaranteeTCO(CallingConv::ID CC) {
2805   return CC == CallingConv::Fast;
2806 }
2807 
2808 /// Return true if we might ever do TCO for calls with this calling convention.
2809 static bool mayTailCallThisCC(CallingConv::ID CC) {
2810   switch (CC) {
2811   case CallingConv::C:
2812     return true;
2813   default:
2814     return canGuaranteeTCO(CC);
2815   }
2816 }
2817 
2818 bool SITargetLowering::isEligibleForTailCallOptimization(
2819     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2820     const SmallVectorImpl<ISD::OutputArg> &Outs,
2821     const SmallVectorImpl<SDValue> &OutVals,
2822     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2823   if (!mayTailCallThisCC(CalleeCC))
2824     return false;
2825 
2826   MachineFunction &MF = DAG.getMachineFunction();
2827   const Function &CallerF = MF.getFunction();
2828   CallingConv::ID CallerCC = CallerF.getCallingConv();
2829   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2830   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2831 
2832   // Kernels aren't callable, and don't have a live in return address so it
2833   // doesn't make sense to do a tail call with entry functions.
2834   if (!CallerPreserved)
2835     return false;
2836 
2837   bool CCMatch = CallerCC == CalleeCC;
2838 
2839   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2840     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2841       return true;
2842     return false;
2843   }
2844 
2845   // TODO: Can we handle var args?
2846   if (IsVarArg)
2847     return false;
2848 
2849   for (const Argument &Arg : CallerF.args()) {
2850     if (Arg.hasByValAttr())
2851       return false;
2852   }
2853 
2854   LLVMContext &Ctx = *DAG.getContext();
2855 
2856   // Check that the call results are passed in the same way.
2857   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2858                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2859                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2860     return false;
2861 
2862   // The callee has to preserve all registers the caller needs to preserve.
2863   if (!CCMatch) {
2864     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2865     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2866       return false;
2867   }
2868 
2869   // Nothing more to check if the callee is taking no arguments.
2870   if (Outs.empty())
2871     return true;
2872 
2873   SmallVector<CCValAssign, 16> ArgLocs;
2874   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2875 
2876   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2877 
2878   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2879   // If the stack arguments for this call do not fit into our own save area then
2880   // the call cannot be made tail.
2881   // TODO: Is this really necessary?
2882   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2883     return false;
2884 
2885   const MachineRegisterInfo &MRI = MF.getRegInfo();
2886   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2887 }
2888 
2889 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2890   if (!CI->isTailCall())
2891     return false;
2892 
2893   const Function *ParentFn = CI->getParent()->getParent();
2894   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2895     return false;
2896   return true;
2897 }
2898 
2899 // The wave scratch offset register is used as the global base pointer.
2900 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2901                                     SmallVectorImpl<SDValue> &InVals) const {
2902   SelectionDAG &DAG = CLI.DAG;
2903   const SDLoc &DL = CLI.DL;
2904   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2905   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2906   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2907   SDValue Chain = CLI.Chain;
2908   SDValue Callee = CLI.Callee;
2909   bool &IsTailCall = CLI.IsTailCall;
2910   CallingConv::ID CallConv = CLI.CallConv;
2911   bool IsVarArg = CLI.IsVarArg;
2912   bool IsSibCall = false;
2913   bool IsThisReturn = false;
2914   MachineFunction &MF = DAG.getMachineFunction();
2915 
2916   if (Callee.isUndef() || isNullConstant(Callee)) {
2917     if (!CLI.IsTailCall) {
2918       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2919         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2920     }
2921 
2922     return Chain;
2923   }
2924 
2925   if (IsVarArg) {
2926     return lowerUnhandledCall(CLI, InVals,
2927                               "unsupported call to variadic function ");
2928   }
2929 
2930   if (!CLI.CB)
2931     report_fatal_error("unsupported libcall legalization");
2932 
2933   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2934       !CLI.CB->getCalledFunction()) {
2935     return lowerUnhandledCall(CLI, InVals,
2936                               "unsupported indirect call to function ");
2937   }
2938 
2939   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2940     return lowerUnhandledCall(CLI, InVals,
2941                               "unsupported required tail call to function ");
2942   }
2943 
2944   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2945     // Note the issue is with the CC of the calling function, not of the call
2946     // itself.
2947     return lowerUnhandledCall(CLI, InVals,
2948                           "unsupported call from graphics shader of function ");
2949   }
2950 
2951   if (IsTailCall) {
2952     IsTailCall = isEligibleForTailCallOptimization(
2953       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2954     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2955       report_fatal_error("failed to perform tail call elimination on a call "
2956                          "site marked musttail");
2957     }
2958 
2959     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2960 
2961     // A sibling call is one where we're under the usual C ABI and not planning
2962     // to change that but can still do a tail call:
2963     if (!TailCallOpt && IsTailCall)
2964       IsSibCall = true;
2965 
2966     if (IsTailCall)
2967       ++NumTailCalls;
2968   }
2969 
2970   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2971   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2972   SmallVector<SDValue, 8> MemOpChains;
2973 
2974   // Analyze operands of the call, assigning locations to each operand.
2975   SmallVector<CCValAssign, 16> ArgLocs;
2976   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2977   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2978 
2979   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2980     // With a fixed ABI, allocate fixed registers before user arguments.
2981     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2982   }
2983 
2984   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2985 
2986   // Get a count of how many bytes are to be pushed on the stack.
2987   unsigned NumBytes = CCInfo.getNextStackOffset();
2988 
2989   if (IsSibCall) {
2990     // Since we're not changing the ABI to make this a tail call, the memory
2991     // operands are already available in the caller's incoming argument space.
2992     NumBytes = 0;
2993   }
2994 
2995   // FPDiff is the byte offset of the call's argument area from the callee's.
2996   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2997   // by this amount for a tail call. In a sibling call it must be 0 because the
2998   // caller will deallocate the entire stack and the callee still expects its
2999   // arguments to begin at SP+0. Completely unused for non-tail calls.
3000   int32_t FPDiff = 0;
3001   MachineFrameInfo &MFI = MF.getFrameInfo();
3002 
3003   // Adjust the stack pointer for the new arguments...
3004   // These operations are automatically eliminated by the prolog/epilog pass
3005   if (!IsSibCall) {
3006     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3007 
3008     SmallVector<SDValue, 4> CopyFromChains;
3009 
3010     // In the HSA case, this should be an identity copy.
3011     SDValue ScratchRSrcReg
3012       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3013     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3014     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3015     Chain = DAG.getTokenFactor(DL, CopyFromChains);
3016   }
3017 
3018   MVT PtrVT = MVT::i32;
3019 
3020   // Walk the register/memloc assignments, inserting copies/loads.
3021   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3022     CCValAssign &VA = ArgLocs[i];
3023     SDValue Arg = OutVals[i];
3024 
3025     // Promote the value if needed.
3026     switch (VA.getLocInfo()) {
3027     case CCValAssign::Full:
3028       break;
3029     case CCValAssign::BCvt:
3030       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3031       break;
3032     case CCValAssign::ZExt:
3033       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3034       break;
3035     case CCValAssign::SExt:
3036       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3037       break;
3038     case CCValAssign::AExt:
3039       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3040       break;
3041     case CCValAssign::FPExt:
3042       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3043       break;
3044     default:
3045       llvm_unreachable("Unknown loc info!");
3046     }
3047 
3048     if (VA.isRegLoc()) {
3049       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3050     } else {
3051       assert(VA.isMemLoc());
3052 
3053       SDValue DstAddr;
3054       MachinePointerInfo DstInfo;
3055 
3056       unsigned LocMemOffset = VA.getLocMemOffset();
3057       int32_t Offset = LocMemOffset;
3058 
3059       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3060       MaybeAlign Alignment;
3061 
3062       if (IsTailCall) {
3063         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3064         unsigned OpSize = Flags.isByVal() ?
3065           Flags.getByValSize() : VA.getValVT().getStoreSize();
3066 
3067         // FIXME: We can have better than the minimum byval required alignment.
3068         Alignment =
3069             Flags.isByVal()
3070                 ? Flags.getNonZeroByValAlign()
3071                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3072 
3073         Offset = Offset + FPDiff;
3074         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3075 
3076         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3077         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3078 
3079         // Make sure any stack arguments overlapping with where we're storing
3080         // are loaded before this eventual operation. Otherwise they'll be
3081         // clobbered.
3082 
3083         // FIXME: Why is this really necessary? This seems to just result in a
3084         // lot of code to copy the stack and write them back to the same
3085         // locations, which are supposed to be immutable?
3086         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3087       } else {
3088         DstAddr = PtrOff;
3089         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3090         Alignment =
3091             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3092       }
3093 
3094       if (Outs[i].Flags.isByVal()) {
3095         SDValue SizeNode =
3096             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3097         SDValue Cpy =
3098             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3099                           Outs[i].Flags.getNonZeroByValAlign(),
3100                           /*isVol = */ false, /*AlwaysInline = */ true,
3101                           /*isTailCall = */ false, DstInfo,
3102                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3103 
3104         MemOpChains.push_back(Cpy);
3105       } else {
3106         SDValue Store =
3107             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3108         MemOpChains.push_back(Store);
3109       }
3110     }
3111   }
3112 
3113   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
3114     // Copy special input registers after user input arguments.
3115     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3116   }
3117 
3118   if (!MemOpChains.empty())
3119     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3120 
3121   // Build a sequence of copy-to-reg nodes chained together with token chain
3122   // and flag operands which copy the outgoing args into the appropriate regs.
3123   SDValue InFlag;
3124   for (auto &RegToPass : RegsToPass) {
3125     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3126                              RegToPass.second, InFlag);
3127     InFlag = Chain.getValue(1);
3128   }
3129 
3130 
3131   SDValue PhysReturnAddrReg;
3132   if (IsTailCall) {
3133     // Since the return is being combined with the call, we need to pass on the
3134     // return address.
3135 
3136     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3137     SDValue ReturnAddrReg = CreateLiveInRegister(
3138       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3139 
3140     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3141                                         MVT::i64);
3142     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3143     InFlag = Chain.getValue(1);
3144   }
3145 
3146   // We don't usually want to end the call-sequence here because we would tidy
3147   // the frame up *after* the call, however in the ABI-changing tail-call case
3148   // we've carefully laid out the parameters so that when sp is reset they'll be
3149   // in the correct location.
3150   if (IsTailCall && !IsSibCall) {
3151     Chain = DAG.getCALLSEQ_END(Chain,
3152                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3153                                DAG.getTargetConstant(0, DL, MVT::i32),
3154                                InFlag, DL);
3155     InFlag = Chain.getValue(1);
3156   }
3157 
3158   std::vector<SDValue> Ops;
3159   Ops.push_back(Chain);
3160   Ops.push_back(Callee);
3161   // Add a redundant copy of the callee global which will not be legalized, as
3162   // we need direct access to the callee later.
3163   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3164     const GlobalValue *GV = GSD->getGlobal();
3165     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3166   } else {
3167     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3168   }
3169 
3170   if (IsTailCall) {
3171     // Each tail call may have to adjust the stack by a different amount, so
3172     // this information must travel along with the operation for eventual
3173     // consumption by emitEpilogue.
3174     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3175 
3176     Ops.push_back(PhysReturnAddrReg);
3177   }
3178 
3179   // Add argument registers to the end of the list so that they are known live
3180   // into the call.
3181   for (auto &RegToPass : RegsToPass) {
3182     Ops.push_back(DAG.getRegister(RegToPass.first,
3183                                   RegToPass.second.getValueType()));
3184   }
3185 
3186   // Add a register mask operand representing the call-preserved registers.
3187 
3188   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3189   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3190   assert(Mask && "Missing call preserved mask for calling convention");
3191   Ops.push_back(DAG.getRegisterMask(Mask));
3192 
3193   if (InFlag.getNode())
3194     Ops.push_back(InFlag);
3195 
3196   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3197 
3198   // If we're doing a tall call, use a TC_RETURN here rather than an
3199   // actual call instruction.
3200   if (IsTailCall) {
3201     MFI.setHasTailCall();
3202     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3203   }
3204 
3205   // Returns a chain and a flag for retval copy to use.
3206   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3207   Chain = Call.getValue(0);
3208   InFlag = Call.getValue(1);
3209 
3210   uint64_t CalleePopBytes = NumBytes;
3211   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3212                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3213                              InFlag, DL);
3214   if (!Ins.empty())
3215     InFlag = Chain.getValue(1);
3216 
3217   // Handle result values, copying them out of physregs into vregs that we
3218   // return.
3219   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3220                          InVals, IsThisReturn,
3221                          IsThisReturn ? OutVals[0] : SDValue());
3222 }
3223 
3224 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3225 // except for applying the wave size scale to the increment amount.
3226 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3227     SDValue Op, SelectionDAG &DAG) const {
3228   const MachineFunction &MF = DAG.getMachineFunction();
3229   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3230 
3231   SDLoc dl(Op);
3232   EVT VT = Op.getValueType();
3233   SDValue Tmp1 = Op;
3234   SDValue Tmp2 = Op.getValue(1);
3235   SDValue Tmp3 = Op.getOperand(2);
3236   SDValue Chain = Tmp1.getOperand(0);
3237 
3238   Register SPReg = Info->getStackPtrOffsetReg();
3239 
3240   // Chain the dynamic stack allocation so that it doesn't modify the stack
3241   // pointer when other instructions are using the stack.
3242   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3243 
3244   SDValue Size  = Tmp2.getOperand(1);
3245   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3246   Chain = SP.getValue(1);
3247   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3248   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3249   const TargetFrameLowering *TFL = ST.getFrameLowering();
3250   unsigned Opc =
3251     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3252     ISD::ADD : ISD::SUB;
3253 
3254   SDValue ScaledSize = DAG.getNode(
3255       ISD::SHL, dl, VT, Size,
3256       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3257 
3258   Align StackAlign = TFL->getStackAlign();
3259   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3260   if (Alignment && *Alignment > StackAlign) {
3261     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3262                        DAG.getConstant(-(uint64_t)Alignment->value()
3263                                            << ST.getWavefrontSizeLog2(),
3264                                        dl, VT));
3265   }
3266 
3267   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3268   Tmp2 = DAG.getCALLSEQ_END(
3269       Chain, DAG.getIntPtrConstant(0, dl, true),
3270       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3271 
3272   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3273 }
3274 
3275 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3276                                                   SelectionDAG &DAG) const {
3277   // We only handle constant sizes here to allow non-entry block, static sized
3278   // allocas. A truly dynamic value is more difficult to support because we
3279   // don't know if the size value is uniform or not. If the size isn't uniform,
3280   // we would need to do a wave reduction to get the maximum size to know how
3281   // much to increment the uniform stack pointer.
3282   SDValue Size = Op.getOperand(1);
3283   if (isa<ConstantSDNode>(Size))
3284       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3285 
3286   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3287 }
3288 
3289 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3290                                              const MachineFunction &MF) const {
3291   Register Reg = StringSwitch<Register>(RegName)
3292     .Case("m0", AMDGPU::M0)
3293     .Case("exec", AMDGPU::EXEC)
3294     .Case("exec_lo", AMDGPU::EXEC_LO)
3295     .Case("exec_hi", AMDGPU::EXEC_HI)
3296     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3297     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3298     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3299     .Default(Register());
3300 
3301   if (Reg == AMDGPU::NoRegister) {
3302     report_fatal_error(Twine("invalid register name \""
3303                              + StringRef(RegName)  + "\"."));
3304 
3305   }
3306 
3307   if (!Subtarget->hasFlatScrRegister() &&
3308        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3309     report_fatal_error(Twine("invalid register \""
3310                              + StringRef(RegName)  + "\" for subtarget."));
3311   }
3312 
3313   switch (Reg) {
3314   case AMDGPU::M0:
3315   case AMDGPU::EXEC_LO:
3316   case AMDGPU::EXEC_HI:
3317   case AMDGPU::FLAT_SCR_LO:
3318   case AMDGPU::FLAT_SCR_HI:
3319     if (VT.getSizeInBits() == 32)
3320       return Reg;
3321     break;
3322   case AMDGPU::EXEC:
3323   case AMDGPU::FLAT_SCR:
3324     if (VT.getSizeInBits() == 64)
3325       return Reg;
3326     break;
3327   default:
3328     llvm_unreachable("missing register type checking");
3329   }
3330 
3331   report_fatal_error(Twine("invalid type for register \""
3332                            + StringRef(RegName) + "\"."));
3333 }
3334 
3335 // If kill is not the last instruction, split the block so kill is always a
3336 // proper terminator.
3337 MachineBasicBlock *
3338 SITargetLowering::splitKillBlock(MachineInstr &MI,
3339                                  MachineBasicBlock *BB) const {
3340   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3341   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3342   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3343   return SplitBB;
3344 }
3345 
3346 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3347 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3348 // be the first instruction in the remainder block.
3349 //
3350 /// \returns { LoopBody, Remainder }
3351 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3352 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3353   MachineFunction *MF = MBB.getParent();
3354   MachineBasicBlock::iterator I(&MI);
3355 
3356   // To insert the loop we need to split the block. Move everything after this
3357   // point to a new block, and insert a new empty block between the two.
3358   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3359   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3360   MachineFunction::iterator MBBI(MBB);
3361   ++MBBI;
3362 
3363   MF->insert(MBBI, LoopBB);
3364   MF->insert(MBBI, RemainderBB);
3365 
3366   LoopBB->addSuccessor(LoopBB);
3367   LoopBB->addSuccessor(RemainderBB);
3368 
3369   // Move the rest of the block into a new block.
3370   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3371 
3372   if (InstInLoop) {
3373     auto Next = std::next(I);
3374 
3375     // Move instruction to loop body.
3376     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3377 
3378     // Move the rest of the block.
3379     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3380   } else {
3381     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3382   }
3383 
3384   MBB.addSuccessor(LoopBB);
3385 
3386   return std::make_pair(LoopBB, RemainderBB);
3387 }
3388 
3389 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3390 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3391   MachineBasicBlock *MBB = MI.getParent();
3392   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3393   auto I = MI.getIterator();
3394   auto E = std::next(I);
3395 
3396   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3397     .addImm(0);
3398 
3399   MIBundleBuilder Bundler(*MBB, I, E);
3400   finalizeBundle(*MBB, Bundler.begin());
3401 }
3402 
3403 MachineBasicBlock *
3404 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3405                                          MachineBasicBlock *BB) const {
3406   const DebugLoc &DL = MI.getDebugLoc();
3407 
3408   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3409 
3410   MachineBasicBlock *LoopBB;
3411   MachineBasicBlock *RemainderBB;
3412   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3413 
3414   // Apparently kill flags are only valid if the def is in the same block?
3415   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3416     Src->setIsKill(false);
3417 
3418   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3419 
3420   MachineBasicBlock::iterator I = LoopBB->end();
3421 
3422   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3423     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3424 
3425   // Clear TRAP_STS.MEM_VIOL
3426   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3427     .addImm(0)
3428     .addImm(EncodedReg);
3429 
3430   bundleInstWithWaitcnt(MI);
3431 
3432   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3433 
3434   // Load and check TRAP_STS.MEM_VIOL
3435   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3436     .addImm(EncodedReg);
3437 
3438   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3439   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3440     .addReg(Reg, RegState::Kill)
3441     .addImm(0);
3442   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3443     .addMBB(LoopBB);
3444 
3445   return RemainderBB;
3446 }
3447 
3448 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3449 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3450 // will only do one iteration. In the worst case, this will loop 64 times.
3451 //
3452 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3453 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3454   const SIInstrInfo *TII,
3455   MachineRegisterInfo &MRI,
3456   MachineBasicBlock &OrigBB,
3457   MachineBasicBlock &LoopBB,
3458   const DebugLoc &DL,
3459   const MachineOperand &IdxReg,
3460   unsigned InitReg,
3461   unsigned ResultReg,
3462   unsigned PhiReg,
3463   unsigned InitSaveExecReg,
3464   int Offset,
3465   bool UseGPRIdxMode,
3466   bool IsIndirectSrc) {
3467   MachineFunction *MF = OrigBB.getParent();
3468   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3469   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3470   MachineBasicBlock::iterator I = LoopBB.begin();
3471 
3472   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3473   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3474   Register NewExec = MRI.createVirtualRegister(BoolRC);
3475   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3476   Register CondReg = MRI.createVirtualRegister(BoolRC);
3477 
3478   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3479     .addReg(InitReg)
3480     .addMBB(&OrigBB)
3481     .addReg(ResultReg)
3482     .addMBB(&LoopBB);
3483 
3484   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3485     .addReg(InitSaveExecReg)
3486     .addMBB(&OrigBB)
3487     .addReg(NewExec)
3488     .addMBB(&LoopBB);
3489 
3490   // Read the next variant <- also loop target.
3491   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3492     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3493 
3494   // Compare the just read M0 value to all possible Idx values.
3495   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3496     .addReg(CurrentIdxReg)
3497     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3498 
3499   // Update EXEC, save the original EXEC value to VCC.
3500   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3501                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3502           NewExec)
3503     .addReg(CondReg, RegState::Kill);
3504 
3505   MRI.setSimpleHint(NewExec, CondReg);
3506 
3507   if (UseGPRIdxMode) {
3508     unsigned IdxReg;
3509     if (Offset == 0) {
3510       IdxReg = CurrentIdxReg;
3511     } else {
3512       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3513       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3514         .addReg(CurrentIdxReg, RegState::Kill)
3515         .addImm(Offset);
3516     }
3517     unsigned IdxMode = IsIndirectSrc ?
3518       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3519     MachineInstr *SetOn =
3520       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3521       .addReg(IdxReg, RegState::Kill)
3522       .addImm(IdxMode);
3523     SetOn->getOperand(3).setIsUndef();
3524   } else {
3525     // Move index from VCC into M0
3526     if (Offset == 0) {
3527       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3528         .addReg(CurrentIdxReg, RegState::Kill);
3529     } else {
3530       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3531         .addReg(CurrentIdxReg, RegState::Kill)
3532         .addImm(Offset);
3533     }
3534   }
3535 
3536   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3537   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3538   MachineInstr *InsertPt =
3539     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3540                                                   : AMDGPU::S_XOR_B64_term), Exec)
3541       .addReg(Exec)
3542       .addReg(NewExec);
3543 
3544   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3545   // s_cbranch_scc0?
3546 
3547   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3548   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3549     .addMBB(&LoopBB);
3550 
3551   return InsertPt->getIterator();
3552 }
3553 
3554 // This has slightly sub-optimal regalloc when the source vector is killed by
3555 // the read. The register allocator does not understand that the kill is
3556 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3557 // subregister from it, using 1 more VGPR than necessary. This was saved when
3558 // this was expanded after register allocation.
3559 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3560                                                   MachineBasicBlock &MBB,
3561                                                   MachineInstr &MI,
3562                                                   unsigned InitResultReg,
3563                                                   unsigned PhiReg,
3564                                                   int Offset,
3565                                                   bool UseGPRIdxMode,
3566                                                   bool IsIndirectSrc) {
3567   MachineFunction *MF = MBB.getParent();
3568   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3569   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3570   MachineRegisterInfo &MRI = MF->getRegInfo();
3571   const DebugLoc &DL = MI.getDebugLoc();
3572   MachineBasicBlock::iterator I(&MI);
3573 
3574   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3575   Register DstReg = MI.getOperand(0).getReg();
3576   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3577   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3578   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3579   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3580 
3581   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3582 
3583   // Save the EXEC mask
3584   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3585     .addReg(Exec);
3586 
3587   MachineBasicBlock *LoopBB;
3588   MachineBasicBlock *RemainderBB;
3589   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3590 
3591   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3592 
3593   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3594                                       InitResultReg, DstReg, PhiReg, TmpExec,
3595                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3596   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3597   MachineFunction::iterator MBBI(LoopBB);
3598   ++MBBI;
3599   MF->insert(MBBI, LandingPad);
3600   LoopBB->removeSuccessor(RemainderBB);
3601   LandingPad->addSuccessor(RemainderBB);
3602   LoopBB->addSuccessor(LandingPad);
3603   MachineBasicBlock::iterator First = LandingPad->begin();
3604   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3605     .addReg(SaveExec);
3606 
3607   return InsPt;
3608 }
3609 
3610 // Returns subreg index, offset
3611 static std::pair<unsigned, int>
3612 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3613                             const TargetRegisterClass *SuperRC,
3614                             unsigned VecReg,
3615                             int Offset) {
3616   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3617 
3618   // Skip out of bounds offsets, or else we would end up using an undefined
3619   // register.
3620   if (Offset >= NumElts || Offset < 0)
3621     return std::make_pair(AMDGPU::sub0, Offset);
3622 
3623   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3624 }
3625 
3626 // Return true if the index is an SGPR and was set.
3627 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3628                                  MachineRegisterInfo &MRI,
3629                                  MachineInstr &MI,
3630                                  int Offset,
3631                                  bool UseGPRIdxMode,
3632                                  bool IsIndirectSrc) {
3633   MachineBasicBlock *MBB = MI.getParent();
3634   const DebugLoc &DL = MI.getDebugLoc();
3635   MachineBasicBlock::iterator I(&MI);
3636 
3637   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3638   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3639 
3640   assert(Idx->getReg() != AMDGPU::NoRegister);
3641 
3642   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3643     return false;
3644 
3645   if (UseGPRIdxMode) {
3646     unsigned IdxMode = IsIndirectSrc ?
3647       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3648     if (Offset == 0) {
3649       MachineInstr *SetOn =
3650           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3651               .add(*Idx)
3652               .addImm(IdxMode);
3653 
3654       SetOn->getOperand(3).setIsUndef();
3655     } else {
3656       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3657       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3658           .add(*Idx)
3659           .addImm(Offset);
3660       MachineInstr *SetOn =
3661         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3662         .addReg(Tmp, RegState::Kill)
3663         .addImm(IdxMode);
3664 
3665       SetOn->getOperand(3).setIsUndef();
3666     }
3667 
3668     return true;
3669   }
3670 
3671   if (Offset == 0) {
3672     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3673       .add(*Idx);
3674   } else {
3675     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3676       .add(*Idx)
3677       .addImm(Offset);
3678   }
3679 
3680   return true;
3681 }
3682 
3683 // Control flow needs to be inserted if indexing with a VGPR.
3684 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3685                                           MachineBasicBlock &MBB,
3686                                           const GCNSubtarget &ST) {
3687   const SIInstrInfo *TII = ST.getInstrInfo();
3688   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3689   MachineFunction *MF = MBB.getParent();
3690   MachineRegisterInfo &MRI = MF->getRegInfo();
3691 
3692   Register Dst = MI.getOperand(0).getReg();
3693   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3694   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3695 
3696   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3697 
3698   unsigned SubReg;
3699   std::tie(SubReg, Offset)
3700     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3701 
3702   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3703 
3704   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3705     MachineBasicBlock::iterator I(&MI);
3706     const DebugLoc &DL = MI.getDebugLoc();
3707 
3708     if (UseGPRIdxMode) {
3709       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3710       // to avoid interfering with other uses, so probably requires a new
3711       // optimization pass.
3712       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3713         .addReg(SrcReg, 0, SubReg)
3714         .addReg(SrcReg, RegState::Implicit)
3715         .addReg(AMDGPU::M0, RegState::Implicit);
3716       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3717     } else {
3718       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3719         .addReg(SrcReg, 0, SubReg)
3720         .addReg(SrcReg, RegState::Implicit);
3721     }
3722 
3723     MI.eraseFromParent();
3724 
3725     return &MBB;
3726   }
3727 
3728   const DebugLoc &DL = MI.getDebugLoc();
3729   MachineBasicBlock::iterator I(&MI);
3730 
3731   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3732   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3733 
3734   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3735 
3736   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3737                               Offset, UseGPRIdxMode, true);
3738   MachineBasicBlock *LoopBB = InsPt->getParent();
3739 
3740   if (UseGPRIdxMode) {
3741     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3742       .addReg(SrcReg, 0, SubReg)
3743       .addReg(SrcReg, RegState::Implicit)
3744       .addReg(AMDGPU::M0, RegState::Implicit);
3745     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3746   } else {
3747     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3748       .addReg(SrcReg, 0, SubReg)
3749       .addReg(SrcReg, RegState::Implicit);
3750   }
3751 
3752   MI.eraseFromParent();
3753 
3754   return LoopBB;
3755 }
3756 
3757 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3758                                           MachineBasicBlock &MBB,
3759                                           const GCNSubtarget &ST) {
3760   const SIInstrInfo *TII = ST.getInstrInfo();
3761   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3762   MachineFunction *MF = MBB.getParent();
3763   MachineRegisterInfo &MRI = MF->getRegInfo();
3764 
3765   Register Dst = MI.getOperand(0).getReg();
3766   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3767   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3768   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3769   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3770   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3771 
3772   // This can be an immediate, but will be folded later.
3773   assert(Val->getReg());
3774 
3775   unsigned SubReg;
3776   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3777                                                          SrcVec->getReg(),
3778                                                          Offset);
3779   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3780 
3781   if (Idx->getReg() == AMDGPU::NoRegister) {
3782     MachineBasicBlock::iterator I(&MI);
3783     const DebugLoc &DL = MI.getDebugLoc();
3784 
3785     assert(Offset == 0);
3786 
3787     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3788         .add(*SrcVec)
3789         .add(*Val)
3790         .addImm(SubReg);
3791 
3792     MI.eraseFromParent();
3793     return &MBB;
3794   }
3795 
3796   const MCInstrDesc &MovRelDesc
3797     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3798 
3799   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3800     MachineBasicBlock::iterator I(&MI);
3801     const DebugLoc &DL = MI.getDebugLoc();
3802     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3803       .addReg(SrcVec->getReg())
3804       .add(*Val)
3805       .addImm(SubReg);
3806     if (UseGPRIdxMode)
3807       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3808 
3809     MI.eraseFromParent();
3810     return &MBB;
3811   }
3812 
3813   if (Val->isReg())
3814     MRI.clearKillFlags(Val->getReg());
3815 
3816   const DebugLoc &DL = MI.getDebugLoc();
3817 
3818   Register PhiReg = MRI.createVirtualRegister(VecRC);
3819 
3820   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3821                               Offset, UseGPRIdxMode, false);
3822   MachineBasicBlock *LoopBB = InsPt->getParent();
3823 
3824   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3825     .addReg(PhiReg)
3826     .add(*Val)
3827     .addImm(AMDGPU::sub0);
3828   if (UseGPRIdxMode)
3829     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3830 
3831   MI.eraseFromParent();
3832   return LoopBB;
3833 }
3834 
3835 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3836   MachineInstr &MI, MachineBasicBlock *BB) const {
3837 
3838   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3839   MachineFunction *MF = BB->getParent();
3840   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3841 
3842   switch (MI.getOpcode()) {
3843   case AMDGPU::S_UADDO_PSEUDO:
3844   case AMDGPU::S_USUBO_PSEUDO: {
3845     const DebugLoc &DL = MI.getDebugLoc();
3846     MachineOperand &Dest0 = MI.getOperand(0);
3847     MachineOperand &Dest1 = MI.getOperand(1);
3848     MachineOperand &Src0 = MI.getOperand(2);
3849     MachineOperand &Src1 = MI.getOperand(3);
3850 
3851     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3852                        ? AMDGPU::S_ADD_I32
3853                        : AMDGPU::S_SUB_I32;
3854     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3855 
3856     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3857         .addImm(1)
3858         .addImm(0);
3859 
3860     MI.eraseFromParent();
3861     return BB;
3862   }
3863   case AMDGPU::S_ADD_U64_PSEUDO:
3864   case AMDGPU::S_SUB_U64_PSEUDO: {
3865     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3866     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3867     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3868     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3869     const DebugLoc &DL = MI.getDebugLoc();
3870 
3871     MachineOperand &Dest = MI.getOperand(0);
3872     MachineOperand &Src0 = MI.getOperand(1);
3873     MachineOperand &Src1 = MI.getOperand(2);
3874 
3875     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3876     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3877 
3878     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3879         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3880     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3881         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3882 
3883     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3884         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3885     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3886         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3887 
3888     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3889 
3890     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3891     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3892     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3893     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3894     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3895         .addReg(DestSub0)
3896         .addImm(AMDGPU::sub0)
3897         .addReg(DestSub1)
3898         .addImm(AMDGPU::sub1);
3899     MI.eraseFromParent();
3900     return BB;
3901   }
3902   case AMDGPU::V_ADD_U64_PSEUDO:
3903   case AMDGPU::V_SUB_U64_PSEUDO: {
3904     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3905     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3906     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3907     const DebugLoc &DL = MI.getDebugLoc();
3908 
3909     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3910 
3911     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3912 
3913     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3914     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3915 
3916     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3917     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3918 
3919     MachineOperand &Dest = MI.getOperand(0);
3920     MachineOperand &Src0 = MI.getOperand(1);
3921     MachineOperand &Src1 = MI.getOperand(2);
3922 
3923     const TargetRegisterClass *Src0RC = Src0.isReg()
3924                                             ? MRI.getRegClass(Src0.getReg())
3925                                             : &AMDGPU::VReg_64RegClass;
3926     const TargetRegisterClass *Src1RC = Src1.isReg()
3927                                             ? MRI.getRegClass(Src1.getReg())
3928                                             : &AMDGPU::VReg_64RegClass;
3929 
3930     const TargetRegisterClass *Src0SubRC =
3931         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3932     const TargetRegisterClass *Src1SubRC =
3933         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3934 
3935     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3936         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3937     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3938         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3939 
3940     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3941         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3942     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3943         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3944 
3945     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3946     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3947                                .addReg(CarryReg, RegState::Define)
3948                                .add(SrcReg0Sub0)
3949                                .add(SrcReg1Sub0)
3950                                .addImm(0); // clamp bit
3951 
3952     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3953     MachineInstr *HiHalf =
3954         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3955             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3956             .add(SrcReg0Sub1)
3957             .add(SrcReg1Sub1)
3958             .addReg(CarryReg, RegState::Kill)
3959             .addImm(0); // clamp bit
3960 
3961     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3962         .addReg(DestSub0)
3963         .addImm(AMDGPU::sub0)
3964         .addReg(DestSub1)
3965         .addImm(AMDGPU::sub1);
3966     TII->legalizeOperands(*LoHalf);
3967     TII->legalizeOperands(*HiHalf);
3968     MI.eraseFromParent();
3969     return BB;
3970   }
3971   case AMDGPU::S_ADD_CO_PSEUDO:
3972   case AMDGPU::S_SUB_CO_PSEUDO: {
3973     // This pseudo has a chance to be selected
3974     // only from uniform add/subcarry node. All the VGPR operands
3975     // therefore assumed to be splat vectors.
3976     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3977     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3978     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3979     MachineBasicBlock::iterator MII = MI;
3980     const DebugLoc &DL = MI.getDebugLoc();
3981     MachineOperand &Dest = MI.getOperand(0);
3982     MachineOperand &CarryDest = MI.getOperand(1);
3983     MachineOperand &Src0 = MI.getOperand(2);
3984     MachineOperand &Src1 = MI.getOperand(3);
3985     MachineOperand &Src2 = MI.getOperand(4);
3986     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3987                        ? AMDGPU::S_ADDC_U32
3988                        : AMDGPU::S_SUBB_U32;
3989     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3990       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3991       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3992           .addReg(Src0.getReg());
3993       Src0.setReg(RegOp0);
3994     }
3995     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3996       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3997       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3998           .addReg(Src1.getReg());
3999       Src1.setReg(RegOp1);
4000     }
4001     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4002     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4003       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4004           .addReg(Src2.getReg());
4005       Src2.setReg(RegOp2);
4006     }
4007 
4008     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
4009       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4010           .addReg(Src2.getReg())
4011           .addImm(0);
4012     } else {
4013       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4014           .addReg(Src2.getReg())
4015           .addImm(0);
4016     }
4017 
4018     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4019 
4020     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4021       .addReg(AMDGPU::SCC);
4022     MI.eraseFromParent();
4023     return BB;
4024   }
4025   case AMDGPU::SI_INIT_M0: {
4026     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4027             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4028         .add(MI.getOperand(0));
4029     MI.eraseFromParent();
4030     return BB;
4031   }
4032   case AMDGPU::SI_INIT_EXEC:
4033     // This should be before all vector instructions.
4034     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
4035             AMDGPU::EXEC)
4036         .addImm(MI.getOperand(0).getImm());
4037     MI.eraseFromParent();
4038     return BB;
4039 
4040   case AMDGPU::SI_INIT_EXEC_LO:
4041     // This should be before all vector instructions.
4042     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
4043             AMDGPU::EXEC_LO)
4044         .addImm(MI.getOperand(0).getImm());
4045     MI.eraseFromParent();
4046     return BB;
4047 
4048   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
4049     // Extract the thread count from an SGPR input and set EXEC accordingly.
4050     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
4051     //
4052     // S_BFE_U32 count, input, {shift, 7}
4053     // S_BFM_B64 exec, count, 0
4054     // S_CMP_EQ_U32 count, 64
4055     // S_CMOV_B64 exec, -1
4056     MachineInstr *FirstMI = &*BB->begin();
4057     MachineRegisterInfo &MRI = MF->getRegInfo();
4058     Register InputReg = MI.getOperand(0).getReg();
4059     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4060     bool Found = false;
4061 
4062     // Move the COPY of the input reg to the beginning, so that we can use it.
4063     for (auto I = BB->begin(); I != &MI; I++) {
4064       if (I->getOpcode() != TargetOpcode::COPY ||
4065           I->getOperand(0).getReg() != InputReg)
4066         continue;
4067 
4068       if (I == FirstMI) {
4069         FirstMI = &*++BB->begin();
4070       } else {
4071         I->removeFromParent();
4072         BB->insert(FirstMI, &*I);
4073       }
4074       Found = true;
4075       break;
4076     }
4077     assert(Found);
4078     (void)Found;
4079 
4080     // This should be before all vector instructions.
4081     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
4082     bool isWave32 = getSubtarget()->isWave32();
4083     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4084     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
4085         .addReg(InputReg)
4086         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
4087     BuildMI(*BB, FirstMI, DebugLoc(),
4088             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
4089             Exec)
4090         .addReg(CountReg)
4091         .addImm(0);
4092     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
4093         .addReg(CountReg, RegState::Kill)
4094         .addImm(getSubtarget()->getWavefrontSize());
4095     BuildMI(*BB, FirstMI, DebugLoc(),
4096             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
4097             Exec)
4098         .addImm(-1);
4099     MI.eraseFromParent();
4100     return BB;
4101   }
4102 
4103   case AMDGPU::GET_GROUPSTATICSIZE: {
4104     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4105            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4106     DebugLoc DL = MI.getDebugLoc();
4107     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4108         .add(MI.getOperand(0))
4109         .addImm(MFI->getLDSSize());
4110     MI.eraseFromParent();
4111     return BB;
4112   }
4113   case AMDGPU::SI_INDIRECT_SRC_V1:
4114   case AMDGPU::SI_INDIRECT_SRC_V2:
4115   case AMDGPU::SI_INDIRECT_SRC_V4:
4116   case AMDGPU::SI_INDIRECT_SRC_V8:
4117   case AMDGPU::SI_INDIRECT_SRC_V16:
4118   case AMDGPU::SI_INDIRECT_SRC_V32:
4119     return emitIndirectSrc(MI, *BB, *getSubtarget());
4120   case AMDGPU::SI_INDIRECT_DST_V1:
4121   case AMDGPU::SI_INDIRECT_DST_V2:
4122   case AMDGPU::SI_INDIRECT_DST_V4:
4123   case AMDGPU::SI_INDIRECT_DST_V8:
4124   case AMDGPU::SI_INDIRECT_DST_V16:
4125   case AMDGPU::SI_INDIRECT_DST_V32:
4126     return emitIndirectDst(MI, *BB, *getSubtarget());
4127   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4128   case AMDGPU::SI_KILL_I1_PSEUDO:
4129     return splitKillBlock(MI, BB);
4130   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4131     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4132     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4133     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4134 
4135     Register Dst = MI.getOperand(0).getReg();
4136     Register Src0 = MI.getOperand(1).getReg();
4137     Register Src1 = MI.getOperand(2).getReg();
4138     const DebugLoc &DL = MI.getDebugLoc();
4139     Register SrcCond = MI.getOperand(3).getReg();
4140 
4141     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4142     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4143     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4144     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4145 
4146     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4147       .addReg(SrcCond);
4148     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4149       .addImm(0)
4150       .addReg(Src0, 0, AMDGPU::sub0)
4151       .addImm(0)
4152       .addReg(Src1, 0, AMDGPU::sub0)
4153       .addReg(SrcCondCopy);
4154     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4155       .addImm(0)
4156       .addReg(Src0, 0, AMDGPU::sub1)
4157       .addImm(0)
4158       .addReg(Src1, 0, AMDGPU::sub1)
4159       .addReg(SrcCondCopy);
4160 
4161     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4162       .addReg(DstLo)
4163       .addImm(AMDGPU::sub0)
4164       .addReg(DstHi)
4165       .addImm(AMDGPU::sub1);
4166     MI.eraseFromParent();
4167     return BB;
4168   }
4169   case AMDGPU::SI_BR_UNDEF: {
4170     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4171     const DebugLoc &DL = MI.getDebugLoc();
4172     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4173                            .add(MI.getOperand(0));
4174     Br->getOperand(1).setIsUndef(true); // read undef SCC
4175     MI.eraseFromParent();
4176     return BB;
4177   }
4178   case AMDGPU::ADJCALLSTACKUP:
4179   case AMDGPU::ADJCALLSTACKDOWN: {
4180     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4181     MachineInstrBuilder MIB(*MF, &MI);
4182 
4183     // Add an implicit use of the frame offset reg to prevent the restore copy
4184     // inserted after the call from being reorderd after stack operations in the
4185     // the caller's frame.
4186     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4187         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
4188         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
4189     return BB;
4190   }
4191   case AMDGPU::SI_CALL_ISEL: {
4192     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4193     const DebugLoc &DL = MI.getDebugLoc();
4194 
4195     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4196 
4197     MachineInstrBuilder MIB;
4198     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4199 
4200     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4201       MIB.add(MI.getOperand(I));
4202 
4203     MIB.cloneMemRefs(MI);
4204     MI.eraseFromParent();
4205     return BB;
4206   }
4207   case AMDGPU::V_ADD_CO_U32_e32:
4208   case AMDGPU::V_SUB_CO_U32_e32:
4209   case AMDGPU::V_SUBREV_CO_U32_e32: {
4210     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4211     const DebugLoc &DL = MI.getDebugLoc();
4212     unsigned Opc = MI.getOpcode();
4213 
4214     bool NeedClampOperand = false;
4215     if (TII->pseudoToMCOpcode(Opc) == -1) {
4216       Opc = AMDGPU::getVOPe64(Opc);
4217       NeedClampOperand = true;
4218     }
4219 
4220     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4221     if (TII->isVOP3(*I)) {
4222       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4223       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4224       I.addReg(TRI->getVCC(), RegState::Define);
4225     }
4226     I.add(MI.getOperand(1))
4227      .add(MI.getOperand(2));
4228     if (NeedClampOperand)
4229       I.addImm(0); // clamp bit for e64 encoding
4230 
4231     TII->legalizeOperands(*I);
4232 
4233     MI.eraseFromParent();
4234     return BB;
4235   }
4236   case AMDGPU::DS_GWS_INIT:
4237   case AMDGPU::DS_GWS_SEMA_V:
4238   case AMDGPU::DS_GWS_SEMA_BR:
4239   case AMDGPU::DS_GWS_SEMA_P:
4240   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4241   case AMDGPU::DS_GWS_BARRIER:
4242     // A s_waitcnt 0 is required to be the instruction immediately following.
4243     if (getSubtarget()->hasGWSAutoReplay()) {
4244       bundleInstWithWaitcnt(MI);
4245       return BB;
4246     }
4247 
4248     return emitGWSMemViolTestLoop(MI, BB);
4249   case AMDGPU::S_SETREG_B32: {
4250     // Try to optimize cases that only set the denormal mode or rounding mode.
4251     //
4252     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4253     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4254     // instead.
4255     //
4256     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4257     // allow you to have a no side effect instruction in the output of a
4258     // sideeffecting pattern.
4259     unsigned ID, Offset, Width;
4260     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4261     if (ID != AMDGPU::Hwreg::ID_MODE)
4262       return BB;
4263 
4264     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4265     const unsigned SetMask = WidthMask << Offset;
4266 
4267     if (getSubtarget()->hasDenormModeInst()) {
4268       unsigned SetDenormOp = 0;
4269       unsigned SetRoundOp = 0;
4270 
4271       // The dedicated instructions can only set the whole denorm or round mode
4272       // at once, not a subset of bits in either.
4273       if (SetMask ==
4274           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4275         // If this fully sets both the round and denorm mode, emit the two
4276         // dedicated instructions for these.
4277         SetRoundOp = AMDGPU::S_ROUND_MODE;
4278         SetDenormOp = AMDGPU::S_DENORM_MODE;
4279       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4280         SetRoundOp = AMDGPU::S_ROUND_MODE;
4281       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4282         SetDenormOp = AMDGPU::S_DENORM_MODE;
4283       }
4284 
4285       if (SetRoundOp || SetDenormOp) {
4286         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4287         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4288         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4289           unsigned ImmVal = Def->getOperand(1).getImm();
4290           if (SetRoundOp) {
4291             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4292                 .addImm(ImmVal & 0xf);
4293 
4294             // If we also have the denorm mode, get just the denorm mode bits.
4295             ImmVal >>= 4;
4296           }
4297 
4298           if (SetDenormOp) {
4299             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4300                 .addImm(ImmVal & 0xf);
4301           }
4302 
4303           MI.eraseFromParent();
4304           return BB;
4305         }
4306       }
4307     }
4308 
4309     // If only FP bits are touched, used the no side effects pseudo.
4310     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4311                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4312       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4313 
4314     return BB;
4315   }
4316   default:
4317     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4318   }
4319 }
4320 
4321 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4322   return isTypeLegal(VT.getScalarType());
4323 }
4324 
4325 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4326   // This currently forces unfolding various combinations of fsub into fma with
4327   // free fneg'd operands. As long as we have fast FMA (controlled by
4328   // isFMAFasterThanFMulAndFAdd), we should perform these.
4329 
4330   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4331   // most of these combines appear to be cycle neutral but save on instruction
4332   // count / code size.
4333   return true;
4334 }
4335 
4336 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4337                                          EVT VT) const {
4338   if (!VT.isVector()) {
4339     return MVT::i1;
4340   }
4341   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4342 }
4343 
4344 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4345   // TODO: Should i16 be used always if legal? For now it would force VALU
4346   // shifts.
4347   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4348 }
4349 
4350 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4351   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4352              ? Ty.changeElementSize(16)
4353              : Ty.changeElementSize(32);
4354 }
4355 
4356 // Answering this is somewhat tricky and depends on the specific device which
4357 // have different rates for fma or all f64 operations.
4358 //
4359 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4360 // regardless of which device (although the number of cycles differs between
4361 // devices), so it is always profitable for f64.
4362 //
4363 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4364 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4365 // which we can always do even without fused FP ops since it returns the same
4366 // result as the separate operations and since it is always full
4367 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4368 // however does not support denormals, so we do report fma as faster if we have
4369 // a fast fma device and require denormals.
4370 //
4371 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4372                                                   EVT VT) const {
4373   VT = VT.getScalarType();
4374 
4375   switch (VT.getSimpleVT().SimpleTy) {
4376   case MVT::f32: {
4377     // If mad is not available this depends only on if f32 fma is full rate.
4378     if (!Subtarget->hasMadMacF32Insts())
4379       return Subtarget->hasFastFMAF32();
4380 
4381     // Otherwise f32 mad is always full rate and returns the same result as
4382     // the separate operations so should be preferred over fma.
4383     // However does not support denomals.
4384     if (hasFP32Denormals(MF))
4385       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4386 
4387     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4388     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4389   }
4390   case MVT::f64:
4391     return true;
4392   case MVT::f16:
4393     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4394   default:
4395     break;
4396   }
4397 
4398   return false;
4399 }
4400 
4401 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4402                                    const SDNode *N) const {
4403   // TODO: Check future ftz flag
4404   // v_mad_f32/v_mac_f32 do not support denormals.
4405   EVT VT = N->getValueType(0);
4406   if (VT == MVT::f32)
4407     return Subtarget->hasMadMacF32Insts() &&
4408            !hasFP32Denormals(DAG.getMachineFunction());
4409   if (VT == MVT::f16) {
4410     return Subtarget->hasMadF16() &&
4411            !hasFP64FP16Denormals(DAG.getMachineFunction());
4412   }
4413 
4414   return false;
4415 }
4416 
4417 //===----------------------------------------------------------------------===//
4418 // Custom DAG Lowering Operations
4419 //===----------------------------------------------------------------------===//
4420 
4421 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4422 // wider vector type is legal.
4423 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4424                                              SelectionDAG &DAG) const {
4425   unsigned Opc = Op.getOpcode();
4426   EVT VT = Op.getValueType();
4427   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4428 
4429   SDValue Lo, Hi;
4430   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4431 
4432   SDLoc SL(Op);
4433   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4434                              Op->getFlags());
4435   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4436                              Op->getFlags());
4437 
4438   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4439 }
4440 
4441 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4442 // wider vector type is legal.
4443 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4444                                               SelectionDAG &DAG) const {
4445   unsigned Opc = Op.getOpcode();
4446   EVT VT = Op.getValueType();
4447   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4448 
4449   SDValue Lo0, Hi0;
4450   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4451   SDValue Lo1, Hi1;
4452   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4453 
4454   SDLoc SL(Op);
4455 
4456   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4457                              Op->getFlags());
4458   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4459                              Op->getFlags());
4460 
4461   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4462 }
4463 
4464 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4465                                               SelectionDAG &DAG) const {
4466   unsigned Opc = Op.getOpcode();
4467   EVT VT = Op.getValueType();
4468   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4469 
4470   SDValue Lo0, Hi0;
4471   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4472   SDValue Lo1, Hi1;
4473   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4474   SDValue Lo2, Hi2;
4475   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4476 
4477   SDLoc SL(Op);
4478 
4479   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4480                              Op->getFlags());
4481   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4482                              Op->getFlags());
4483 
4484   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4485 }
4486 
4487 
4488 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4489   switch (Op.getOpcode()) {
4490   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4491   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4492   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4493   case ISD::LOAD: {
4494     SDValue Result = LowerLOAD(Op, DAG);
4495     assert((!Result.getNode() ||
4496             Result.getNode()->getNumValues() == 2) &&
4497            "Load should return a value and a chain");
4498     return Result;
4499   }
4500 
4501   case ISD::FSIN:
4502   case ISD::FCOS:
4503     return LowerTrig(Op, DAG);
4504   case ISD::SELECT: return LowerSELECT(Op, DAG);
4505   case ISD::FDIV: return LowerFDIV(Op, DAG);
4506   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4507   case ISD::STORE: return LowerSTORE(Op, DAG);
4508   case ISD::GlobalAddress: {
4509     MachineFunction &MF = DAG.getMachineFunction();
4510     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4511     return LowerGlobalAddress(MFI, Op, DAG);
4512   }
4513   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4514   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4515   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4516   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4517   case ISD::INSERT_SUBVECTOR:
4518     return lowerINSERT_SUBVECTOR(Op, DAG);
4519   case ISD::INSERT_VECTOR_ELT:
4520     return lowerINSERT_VECTOR_ELT(Op, DAG);
4521   case ISD::EXTRACT_VECTOR_ELT:
4522     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4523   case ISD::VECTOR_SHUFFLE:
4524     return lowerVECTOR_SHUFFLE(Op, DAG);
4525   case ISD::BUILD_VECTOR:
4526     return lowerBUILD_VECTOR(Op, DAG);
4527   case ISD::FP_ROUND:
4528     return lowerFP_ROUND(Op, DAG);
4529   case ISD::TRAP:
4530     return lowerTRAP(Op, DAG);
4531   case ISD::DEBUGTRAP:
4532     return lowerDEBUGTRAP(Op, DAG);
4533   case ISD::FABS:
4534   case ISD::FNEG:
4535   case ISD::FCANONICALIZE:
4536   case ISD::BSWAP:
4537     return splitUnaryVectorOp(Op, DAG);
4538   case ISD::FMINNUM:
4539   case ISD::FMAXNUM:
4540     return lowerFMINNUM_FMAXNUM(Op, DAG);
4541   case ISD::FMA:
4542     return splitTernaryVectorOp(Op, DAG);
4543   case ISD::SHL:
4544   case ISD::SRA:
4545   case ISD::SRL:
4546   case ISD::ADD:
4547   case ISD::SUB:
4548   case ISD::MUL:
4549   case ISD::SMIN:
4550   case ISD::SMAX:
4551   case ISD::UMIN:
4552   case ISD::UMAX:
4553   case ISD::FADD:
4554   case ISD::FMUL:
4555   case ISD::FMINNUM_IEEE:
4556   case ISD::FMAXNUM_IEEE:
4557   case ISD::UADDSAT:
4558   case ISD::USUBSAT:
4559   case ISD::SADDSAT:
4560   case ISD::SSUBSAT:
4561     return splitBinaryVectorOp(Op, DAG);
4562   case ISD::SMULO:
4563   case ISD::UMULO:
4564     return lowerXMULO(Op, DAG);
4565   case ISD::DYNAMIC_STACKALLOC:
4566     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4567   }
4568   return SDValue();
4569 }
4570 
4571 // Used for D16: Casts the result of an instruction into the right vector,
4572 // packs values if loads return unpacked values.
4573 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4574                                        const SDLoc &DL,
4575                                        SelectionDAG &DAG, bool Unpacked) {
4576   if (!LoadVT.isVector())
4577     return Result;
4578 
4579   // Cast back to the original packed type or to a larger type that is a
4580   // multiple of 32 bit for D16. Widening the return type is a required for
4581   // legalization.
4582   EVT FittingLoadVT = LoadVT;
4583   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4584     FittingLoadVT =
4585         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4586                          LoadVT.getVectorNumElements() + 1);
4587   }
4588 
4589   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4590     // Truncate to v2i16/v4i16.
4591     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4592 
4593     // Workaround legalizer not scalarizing truncate after vector op
4594     // legalization but not creating intermediate vector trunc.
4595     SmallVector<SDValue, 4> Elts;
4596     DAG.ExtractVectorElements(Result, Elts);
4597     for (SDValue &Elt : Elts)
4598       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4599 
4600     // Pad illegal v1i16/v3fi6 to v4i16
4601     if ((LoadVT.getVectorNumElements() % 2) == 1)
4602       Elts.push_back(DAG.getUNDEF(MVT::i16));
4603 
4604     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4605 
4606     // Bitcast to original type (v2f16/v4f16).
4607     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4608   }
4609 
4610   // Cast back to the original packed type.
4611   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4612 }
4613 
4614 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4615                                               MemSDNode *M,
4616                                               SelectionDAG &DAG,
4617                                               ArrayRef<SDValue> Ops,
4618                                               bool IsIntrinsic) const {
4619   SDLoc DL(M);
4620 
4621   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4622   EVT LoadVT = M->getValueType(0);
4623 
4624   EVT EquivLoadVT = LoadVT;
4625   if (LoadVT.isVector()) {
4626     if (Unpacked) {
4627       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4628                                      LoadVT.getVectorNumElements());
4629     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4630       // Widen v3f16 to legal type
4631       EquivLoadVT =
4632           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4633                            LoadVT.getVectorNumElements() + 1);
4634     }
4635   }
4636 
4637   // Change from v4f16/v2f16 to EquivLoadVT.
4638   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4639 
4640   SDValue Load
4641     = DAG.getMemIntrinsicNode(
4642       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4643       VTList, Ops, M->getMemoryVT(),
4644       M->getMemOperand());
4645 
4646   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4647 
4648   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4649 }
4650 
4651 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4652                                              SelectionDAG &DAG,
4653                                              ArrayRef<SDValue> Ops) const {
4654   SDLoc DL(M);
4655   EVT LoadVT = M->getValueType(0);
4656   EVT EltType = LoadVT.getScalarType();
4657   EVT IntVT = LoadVT.changeTypeToInteger();
4658 
4659   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4660 
4661   unsigned Opc =
4662       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4663 
4664   if (IsD16) {
4665     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4666   }
4667 
4668   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4669   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4670     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4671 
4672   if (isTypeLegal(LoadVT)) {
4673     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4674                                M->getMemOperand(), DAG);
4675   }
4676 
4677   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4678   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4679   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4680                                         M->getMemOperand(), DAG);
4681   return DAG.getMergeValues(
4682       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4683       DL);
4684 }
4685 
4686 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4687                                   SDNode *N, SelectionDAG &DAG) {
4688   EVT VT = N->getValueType(0);
4689   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4690   unsigned CondCode = CD->getZExtValue();
4691   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4692     return DAG.getUNDEF(VT);
4693 
4694   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4695 
4696   SDValue LHS = N->getOperand(1);
4697   SDValue RHS = N->getOperand(2);
4698 
4699   SDLoc DL(N);
4700 
4701   EVT CmpVT = LHS.getValueType();
4702   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4703     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4704       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4705     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4706     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4707   }
4708 
4709   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4710 
4711   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4712   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4713 
4714   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4715                               DAG.getCondCode(CCOpcode));
4716   if (VT.bitsEq(CCVT))
4717     return SetCC;
4718   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4719 }
4720 
4721 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4722                                   SDNode *N, SelectionDAG &DAG) {
4723   EVT VT = N->getValueType(0);
4724   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4725 
4726   unsigned CondCode = CD->getZExtValue();
4727   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4728     return DAG.getUNDEF(VT);
4729 
4730   SDValue Src0 = N->getOperand(1);
4731   SDValue Src1 = N->getOperand(2);
4732   EVT CmpVT = Src0.getValueType();
4733   SDLoc SL(N);
4734 
4735   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4736     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4737     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4738   }
4739 
4740   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4741   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4742   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4743   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4744   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4745                               Src1, DAG.getCondCode(CCOpcode));
4746   if (VT.bitsEq(CCVT))
4747     return SetCC;
4748   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4749 }
4750 
4751 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4752                                     SelectionDAG &DAG) {
4753   EVT VT = N->getValueType(0);
4754   SDValue Src = N->getOperand(1);
4755   SDLoc SL(N);
4756 
4757   if (Src.getOpcode() == ISD::SETCC) {
4758     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4759     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4760                        Src.getOperand(1), Src.getOperand(2));
4761   }
4762   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4763     // (ballot 0) -> 0
4764     if (Arg->isNullValue())
4765       return DAG.getConstant(0, SL, VT);
4766 
4767     // (ballot 1) -> EXEC/EXEC_LO
4768     if (Arg->isOne()) {
4769       Register Exec;
4770       if (VT.getScalarSizeInBits() == 32)
4771         Exec = AMDGPU::EXEC_LO;
4772       else if (VT.getScalarSizeInBits() == 64)
4773         Exec = AMDGPU::EXEC;
4774       else
4775         return SDValue();
4776 
4777       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4778     }
4779   }
4780 
4781   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4782   // ISD::SETNE)
4783   return DAG.getNode(
4784       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4785       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4786 }
4787 
4788 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4789                                           SmallVectorImpl<SDValue> &Results,
4790                                           SelectionDAG &DAG) const {
4791   switch (N->getOpcode()) {
4792   case ISD::INSERT_VECTOR_ELT: {
4793     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4794       Results.push_back(Res);
4795     return;
4796   }
4797   case ISD::EXTRACT_VECTOR_ELT: {
4798     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4799       Results.push_back(Res);
4800     return;
4801   }
4802   case ISD::INTRINSIC_WO_CHAIN: {
4803     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4804     switch (IID) {
4805     case Intrinsic::amdgcn_cvt_pkrtz: {
4806       SDValue Src0 = N->getOperand(1);
4807       SDValue Src1 = N->getOperand(2);
4808       SDLoc SL(N);
4809       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4810                                 Src0, Src1);
4811       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4812       return;
4813     }
4814     case Intrinsic::amdgcn_cvt_pknorm_i16:
4815     case Intrinsic::amdgcn_cvt_pknorm_u16:
4816     case Intrinsic::amdgcn_cvt_pk_i16:
4817     case Intrinsic::amdgcn_cvt_pk_u16: {
4818       SDValue Src0 = N->getOperand(1);
4819       SDValue Src1 = N->getOperand(2);
4820       SDLoc SL(N);
4821       unsigned Opcode;
4822 
4823       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4824         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4825       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4826         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4827       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4828         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4829       else
4830         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4831 
4832       EVT VT = N->getValueType(0);
4833       if (isTypeLegal(VT))
4834         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4835       else {
4836         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4837         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4838       }
4839       return;
4840     }
4841     }
4842     break;
4843   }
4844   case ISD::INTRINSIC_W_CHAIN: {
4845     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4846       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4847         // FIXME: Hacky
4848         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4849           Results.push_back(Res.getOperand(I));
4850         }
4851       } else {
4852         Results.push_back(Res);
4853         Results.push_back(Res.getValue(1));
4854       }
4855       return;
4856     }
4857 
4858     break;
4859   }
4860   case ISD::SELECT: {
4861     SDLoc SL(N);
4862     EVT VT = N->getValueType(0);
4863     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4864     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4865     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4866 
4867     EVT SelectVT = NewVT;
4868     if (NewVT.bitsLT(MVT::i32)) {
4869       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4870       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4871       SelectVT = MVT::i32;
4872     }
4873 
4874     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4875                                     N->getOperand(0), LHS, RHS);
4876 
4877     if (NewVT != SelectVT)
4878       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4879     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4880     return;
4881   }
4882   case ISD::FNEG: {
4883     if (N->getValueType(0) != MVT::v2f16)
4884       break;
4885 
4886     SDLoc SL(N);
4887     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4888 
4889     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4890                              BC,
4891                              DAG.getConstant(0x80008000, SL, MVT::i32));
4892     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4893     return;
4894   }
4895   case ISD::FABS: {
4896     if (N->getValueType(0) != MVT::v2f16)
4897       break;
4898 
4899     SDLoc SL(N);
4900     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4901 
4902     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4903                              BC,
4904                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4905     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4906     return;
4907   }
4908   default:
4909     break;
4910   }
4911 }
4912 
4913 /// Helper function for LowerBRCOND
4914 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4915 
4916   SDNode *Parent = Value.getNode();
4917   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4918        I != E; ++I) {
4919 
4920     if (I.getUse().get() != Value)
4921       continue;
4922 
4923     if (I->getOpcode() == Opcode)
4924       return *I;
4925   }
4926   return nullptr;
4927 }
4928 
4929 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4930   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4931     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4932     case Intrinsic::amdgcn_if:
4933       return AMDGPUISD::IF;
4934     case Intrinsic::amdgcn_else:
4935       return AMDGPUISD::ELSE;
4936     case Intrinsic::amdgcn_loop:
4937       return AMDGPUISD::LOOP;
4938     case Intrinsic::amdgcn_end_cf:
4939       llvm_unreachable("should not occur");
4940     default:
4941       return 0;
4942     }
4943   }
4944 
4945   // break, if_break, else_break are all only used as inputs to loop, not
4946   // directly as branch conditions.
4947   return 0;
4948 }
4949 
4950 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4951   const Triple &TT = getTargetMachine().getTargetTriple();
4952   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4953           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4954          AMDGPU::shouldEmitConstantsToTextSection(TT);
4955 }
4956 
4957 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4958   // FIXME: Either avoid relying on address space here or change the default
4959   // address space for functions to avoid the explicit check.
4960   return (GV->getValueType()->isFunctionTy() ||
4961           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4962          !shouldEmitFixup(GV) &&
4963          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4964 }
4965 
4966 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4967   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4968 }
4969 
4970 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4971   if (!GV->hasExternalLinkage())
4972     return true;
4973 
4974   const auto OS = getTargetMachine().getTargetTriple().getOS();
4975   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4976 }
4977 
4978 /// This transforms the control flow intrinsics to get the branch destination as
4979 /// last parameter, also switches branch target with BR if the need arise
4980 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4981                                       SelectionDAG &DAG) const {
4982   SDLoc DL(BRCOND);
4983 
4984   SDNode *Intr = BRCOND.getOperand(1).getNode();
4985   SDValue Target = BRCOND.getOperand(2);
4986   SDNode *BR = nullptr;
4987   SDNode *SetCC = nullptr;
4988 
4989   if (Intr->getOpcode() == ISD::SETCC) {
4990     // As long as we negate the condition everything is fine
4991     SetCC = Intr;
4992     Intr = SetCC->getOperand(0).getNode();
4993 
4994   } else {
4995     // Get the target from BR if we don't negate the condition
4996     BR = findUser(BRCOND, ISD::BR);
4997     assert(BR && "brcond missing unconditional branch user");
4998     Target = BR->getOperand(1);
4999   }
5000 
5001   unsigned CFNode = isCFIntrinsic(Intr);
5002   if (CFNode == 0) {
5003     // This is a uniform branch so we don't need to legalize.
5004     return BRCOND;
5005   }
5006 
5007   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5008                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5009 
5010   assert(!SetCC ||
5011         (SetCC->getConstantOperandVal(1) == 1 &&
5012          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5013                                                              ISD::SETNE));
5014 
5015   // operands of the new intrinsic call
5016   SmallVector<SDValue, 4> Ops;
5017   if (HaveChain)
5018     Ops.push_back(BRCOND.getOperand(0));
5019 
5020   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5021   Ops.push_back(Target);
5022 
5023   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5024 
5025   // build the new intrinsic call
5026   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5027 
5028   if (!HaveChain) {
5029     SDValue Ops[] =  {
5030       SDValue(Result, 0),
5031       BRCOND.getOperand(0)
5032     };
5033 
5034     Result = DAG.getMergeValues(Ops, DL).getNode();
5035   }
5036 
5037   if (BR) {
5038     // Give the branch instruction our target
5039     SDValue Ops[] = {
5040       BR->getOperand(0),
5041       BRCOND.getOperand(2)
5042     };
5043     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5044     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5045   }
5046 
5047   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5048 
5049   // Copy the intrinsic results to registers
5050   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5051     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5052     if (!CopyToReg)
5053       continue;
5054 
5055     Chain = DAG.getCopyToReg(
5056       Chain, DL,
5057       CopyToReg->getOperand(1),
5058       SDValue(Result, i - 1),
5059       SDValue());
5060 
5061     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5062   }
5063 
5064   // Remove the old intrinsic from the chain
5065   DAG.ReplaceAllUsesOfValueWith(
5066     SDValue(Intr, Intr->getNumValues() - 1),
5067     Intr->getOperand(0));
5068 
5069   return Chain;
5070 }
5071 
5072 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5073                                           SelectionDAG &DAG) const {
5074   MVT VT = Op.getSimpleValueType();
5075   SDLoc DL(Op);
5076   // Checking the depth
5077   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5078     return DAG.getConstant(0, DL, VT);
5079 
5080   MachineFunction &MF = DAG.getMachineFunction();
5081   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5082   // Check for kernel and shader functions
5083   if (Info->isEntryFunction())
5084     return DAG.getConstant(0, DL, VT);
5085 
5086   MachineFrameInfo &MFI = MF.getFrameInfo();
5087   // There is a call to @llvm.returnaddress in this function
5088   MFI.setReturnAddressIsTaken(true);
5089 
5090   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5091   // Get the return address reg and mark it as an implicit live-in
5092   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5093 
5094   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5095 }
5096 
5097 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5098                                             SDValue Op,
5099                                             const SDLoc &DL,
5100                                             EVT VT) const {
5101   return Op.getValueType().bitsLE(VT) ?
5102       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5103     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5104                 DAG.getTargetConstant(0, DL, MVT::i32));
5105 }
5106 
5107 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5108   assert(Op.getValueType() == MVT::f16 &&
5109          "Do not know how to custom lower FP_ROUND for non-f16 type");
5110 
5111   SDValue Src = Op.getOperand(0);
5112   EVT SrcVT = Src.getValueType();
5113   if (SrcVT != MVT::f64)
5114     return Op;
5115 
5116   SDLoc DL(Op);
5117 
5118   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5119   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5120   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5121 }
5122 
5123 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5124                                                SelectionDAG &DAG) const {
5125   EVT VT = Op.getValueType();
5126   const MachineFunction &MF = DAG.getMachineFunction();
5127   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5128   bool IsIEEEMode = Info->getMode().IEEE;
5129 
5130   // FIXME: Assert during selection that this is only selected for
5131   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5132   // mode functions, but this happens to be OK since it's only done in cases
5133   // where there is known no sNaN.
5134   if (IsIEEEMode)
5135     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5136 
5137   if (VT == MVT::v4f16)
5138     return splitBinaryVectorOp(Op, DAG);
5139   return Op;
5140 }
5141 
5142 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5143   EVT VT = Op.getValueType();
5144   SDLoc SL(Op);
5145   SDValue LHS = Op.getOperand(0);
5146   SDValue RHS = Op.getOperand(1);
5147   bool isSigned = Op.getOpcode() == ISD::SMULO;
5148 
5149   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5150     const APInt &C = RHSC->getAPIntValue();
5151     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5152     if (C.isPowerOf2()) {
5153       // smulo(x, signed_min) is same as umulo(x, signed_min).
5154       bool UseArithShift = isSigned && !C.isMinSignedValue();
5155       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5156       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5157       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5158           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5159                       SL, VT, Result, ShiftAmt),
5160           LHS, ISD::SETNE);
5161       return DAG.getMergeValues({ Result, Overflow }, SL);
5162     }
5163   }
5164 
5165   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5166   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5167                             SL, VT, LHS, RHS);
5168 
5169   SDValue Sign = isSigned
5170     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5171                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5172     : DAG.getConstant(0, SL, VT);
5173   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5174 
5175   return DAG.getMergeValues({ Result, Overflow }, SL);
5176 }
5177 
5178 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5179   SDLoc SL(Op);
5180   SDValue Chain = Op.getOperand(0);
5181 
5182   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5183       !Subtarget->isTrapHandlerEnabled())
5184     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5185 
5186   MachineFunction &MF = DAG.getMachineFunction();
5187   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5188   Register UserSGPR = Info->getQueuePtrUserSGPR();
5189   assert(UserSGPR != AMDGPU::NoRegister);
5190   SDValue QueuePtr = CreateLiveInRegister(
5191     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5192   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5193   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5194                                    QueuePtr, SDValue());
5195   SDValue Ops[] = {
5196     ToReg,
5197     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5198     SGPR01,
5199     ToReg.getValue(1)
5200   };
5201   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5202 }
5203 
5204 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5205   SDLoc SL(Op);
5206   SDValue Chain = Op.getOperand(0);
5207   MachineFunction &MF = DAG.getMachineFunction();
5208 
5209   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5210       !Subtarget->isTrapHandlerEnabled()) {
5211     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5212                                      "debugtrap handler not supported",
5213                                      Op.getDebugLoc(),
5214                                      DS_Warning);
5215     LLVMContext &Ctx = MF.getFunction().getContext();
5216     Ctx.diagnose(NoTrap);
5217     return Chain;
5218   }
5219 
5220   SDValue Ops[] = {
5221     Chain,
5222     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5223   };
5224   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5225 }
5226 
5227 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5228                                              SelectionDAG &DAG) const {
5229   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5230   if (Subtarget->hasApertureRegs()) {
5231     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5232         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5233         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5234     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5235         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5236         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5237     unsigned Encoding =
5238         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5239         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5240         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5241 
5242     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5243     SDValue ApertureReg = SDValue(
5244         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5245     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5246     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5247   }
5248 
5249   MachineFunction &MF = DAG.getMachineFunction();
5250   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5251   Register UserSGPR = Info->getQueuePtrUserSGPR();
5252   assert(UserSGPR != AMDGPU::NoRegister);
5253 
5254   SDValue QueuePtr = CreateLiveInRegister(
5255     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5256 
5257   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5258   // private_segment_aperture_base_hi.
5259   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5260 
5261   SDValue Ptr =
5262       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5263 
5264   // TODO: Use custom target PseudoSourceValue.
5265   // TODO: We should use the value from the IR intrinsic call, but it might not
5266   // be available and how do we get it?
5267   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5268   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5269                      commonAlignment(Align(64), StructOffset),
5270                      MachineMemOperand::MODereferenceable |
5271                          MachineMemOperand::MOInvariant);
5272 }
5273 
5274 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5275                                              SelectionDAG &DAG) const {
5276   SDLoc SL(Op);
5277   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5278 
5279   SDValue Src = ASC->getOperand(0);
5280   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5281 
5282   const AMDGPUTargetMachine &TM =
5283     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5284 
5285   // flat -> local/private
5286   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5287     unsigned DestAS = ASC->getDestAddressSpace();
5288 
5289     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5290         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5291       unsigned NullVal = TM.getNullPointerValue(DestAS);
5292       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5293       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5294       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5295 
5296       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5297                          NonNull, Ptr, SegmentNullPtr);
5298     }
5299   }
5300 
5301   // local/private -> flat
5302   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5303     unsigned SrcAS = ASC->getSrcAddressSpace();
5304 
5305     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5306         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5307       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5308       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5309 
5310       SDValue NonNull
5311         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5312 
5313       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5314       SDValue CvtPtr
5315         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5316 
5317       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5318                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5319                          FlatNullPtr);
5320     }
5321   }
5322 
5323   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5324       Src.getValueType() == MVT::i64)
5325     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5326 
5327   // global <-> flat are no-ops and never emitted.
5328 
5329   const MachineFunction &MF = DAG.getMachineFunction();
5330   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5331     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5332   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5333 
5334   return DAG.getUNDEF(ASC->getValueType(0));
5335 }
5336 
5337 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5338 // the small vector and inserting them into the big vector. That is better than
5339 // the default expansion of doing it via a stack slot. Even though the use of
5340 // the stack slot would be optimized away afterwards, the stack slot itself
5341 // remains.
5342 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5343                                                 SelectionDAG &DAG) const {
5344   SDValue Vec = Op.getOperand(0);
5345   SDValue Ins = Op.getOperand(1);
5346   SDValue Idx = Op.getOperand(2);
5347   EVT VecVT = Vec.getValueType();
5348   EVT InsVT = Ins.getValueType();
5349   EVT EltVT = VecVT.getVectorElementType();
5350   unsigned InsNumElts = InsVT.getVectorNumElements();
5351   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5352   SDLoc SL(Op);
5353 
5354   for (unsigned I = 0; I != InsNumElts; ++I) {
5355     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5356                               DAG.getConstant(I, SL, MVT::i32));
5357     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5358                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5359   }
5360   return Vec;
5361 }
5362 
5363 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5364                                                  SelectionDAG &DAG) const {
5365   SDValue Vec = Op.getOperand(0);
5366   SDValue InsVal = Op.getOperand(1);
5367   SDValue Idx = Op.getOperand(2);
5368   EVT VecVT = Vec.getValueType();
5369   EVT EltVT = VecVT.getVectorElementType();
5370   unsigned VecSize = VecVT.getSizeInBits();
5371   unsigned EltSize = EltVT.getSizeInBits();
5372 
5373 
5374   assert(VecSize <= 64);
5375 
5376   unsigned NumElts = VecVT.getVectorNumElements();
5377   SDLoc SL(Op);
5378   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5379 
5380   if (NumElts == 4 && EltSize == 16 && KIdx) {
5381     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5382 
5383     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5384                                  DAG.getConstant(0, SL, MVT::i32));
5385     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5386                                  DAG.getConstant(1, SL, MVT::i32));
5387 
5388     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5389     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5390 
5391     unsigned Idx = KIdx->getZExtValue();
5392     bool InsertLo = Idx < 2;
5393     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5394       InsertLo ? LoVec : HiVec,
5395       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5396       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5397 
5398     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5399 
5400     SDValue Concat = InsertLo ?
5401       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5402       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5403 
5404     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5405   }
5406 
5407   if (isa<ConstantSDNode>(Idx))
5408     return SDValue();
5409 
5410   MVT IntVT = MVT::getIntegerVT(VecSize);
5411 
5412   // Avoid stack access for dynamic indexing.
5413   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5414 
5415   // Create a congruent vector with the target value in each element so that
5416   // the required element can be masked and ORed into the target vector.
5417   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5418                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5419 
5420   assert(isPowerOf2_32(EltSize));
5421   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5422 
5423   // Convert vector index to bit-index.
5424   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5425 
5426   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5427   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5428                             DAG.getConstant(0xffff, SL, IntVT),
5429                             ScaledIdx);
5430 
5431   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5432   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5433                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5434 
5435   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5436   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5437 }
5438 
5439 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5440                                                   SelectionDAG &DAG) const {
5441   SDLoc SL(Op);
5442 
5443   EVT ResultVT = Op.getValueType();
5444   SDValue Vec = Op.getOperand(0);
5445   SDValue Idx = Op.getOperand(1);
5446   EVT VecVT = Vec.getValueType();
5447   unsigned VecSize = VecVT.getSizeInBits();
5448   EVT EltVT = VecVT.getVectorElementType();
5449   assert(VecSize <= 64);
5450 
5451   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5452 
5453   // Make sure we do any optimizations that will make it easier to fold
5454   // source modifiers before obscuring it with bit operations.
5455 
5456   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5457   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5458     return Combined;
5459 
5460   unsigned EltSize = EltVT.getSizeInBits();
5461   assert(isPowerOf2_32(EltSize));
5462 
5463   MVT IntVT = MVT::getIntegerVT(VecSize);
5464   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5465 
5466   // Convert vector index to bit-index (* EltSize)
5467   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5468 
5469   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5470   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5471 
5472   if (ResultVT == MVT::f16) {
5473     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5474     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5475   }
5476 
5477   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5478 }
5479 
5480 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5481   assert(Elt % 2 == 0);
5482   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5483 }
5484 
5485 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5486                                               SelectionDAG &DAG) const {
5487   SDLoc SL(Op);
5488   EVT ResultVT = Op.getValueType();
5489   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5490 
5491   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5492   EVT EltVT = PackVT.getVectorElementType();
5493   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5494 
5495   // vector_shuffle <0,1,6,7> lhs, rhs
5496   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5497   //
5498   // vector_shuffle <6,7,2,3> lhs, rhs
5499   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5500   //
5501   // vector_shuffle <6,7,0,1> lhs, rhs
5502   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5503 
5504   // Avoid scalarizing when both halves are reading from consecutive elements.
5505   SmallVector<SDValue, 4> Pieces;
5506   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5507     if (elementPairIsContiguous(SVN->getMask(), I)) {
5508       const int Idx = SVN->getMaskElt(I);
5509       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5510       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5511       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5512                                     PackVT, SVN->getOperand(VecIdx),
5513                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5514       Pieces.push_back(SubVec);
5515     } else {
5516       const int Idx0 = SVN->getMaskElt(I);
5517       const int Idx1 = SVN->getMaskElt(I + 1);
5518       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5519       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5520       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5521       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5522 
5523       SDValue Vec0 = SVN->getOperand(VecIdx0);
5524       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5525                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5526 
5527       SDValue Vec1 = SVN->getOperand(VecIdx1);
5528       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5529                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5530       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5531     }
5532   }
5533 
5534   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5535 }
5536 
5537 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5538                                             SelectionDAG &DAG) const {
5539   SDLoc SL(Op);
5540   EVT VT = Op.getValueType();
5541 
5542   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5543     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5544 
5545     // Turn into pair of packed build_vectors.
5546     // TODO: Special case for constants that can be materialized with s_mov_b64.
5547     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5548                                     { Op.getOperand(0), Op.getOperand(1) });
5549     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5550                                     { Op.getOperand(2), Op.getOperand(3) });
5551 
5552     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5553     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5554 
5555     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5556     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5557   }
5558 
5559   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5560   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5561 
5562   SDValue Lo = Op.getOperand(0);
5563   SDValue Hi = Op.getOperand(1);
5564 
5565   // Avoid adding defined bits with the zero_extend.
5566   if (Hi.isUndef()) {
5567     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5568     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5569     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5570   }
5571 
5572   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5573   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5574 
5575   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5576                               DAG.getConstant(16, SL, MVT::i32));
5577   if (Lo.isUndef())
5578     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5579 
5580   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5581   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5582 
5583   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5584   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5585 }
5586 
5587 bool
5588 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5589   // We can fold offsets for anything that doesn't require a GOT relocation.
5590   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5591           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5592           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5593          !shouldEmitGOTReloc(GA->getGlobal());
5594 }
5595 
5596 static SDValue
5597 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5598                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5599                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5600   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5601   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5602   // lowered to the following code sequence:
5603   //
5604   // For constant address space:
5605   //   s_getpc_b64 s[0:1]
5606   //   s_add_u32 s0, s0, $symbol
5607   //   s_addc_u32 s1, s1, 0
5608   //
5609   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5610   //   a fixup or relocation is emitted to replace $symbol with a literal
5611   //   constant, which is a pc-relative offset from the encoding of the $symbol
5612   //   operand to the global variable.
5613   //
5614   // For global address space:
5615   //   s_getpc_b64 s[0:1]
5616   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5617   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5618   //
5619   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5620   //   fixups or relocations are emitted to replace $symbol@*@lo and
5621   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5622   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5623   //   operand to the global variable.
5624   //
5625   // What we want here is an offset from the value returned by s_getpc
5626   // (which is the address of the s_add_u32 instruction) to the global
5627   // variable, but since the encoding of $symbol starts 4 bytes after the start
5628   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5629   // small. This requires us to add 4 to the global variable offset in order to
5630   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5631   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5632   // instruction.
5633   SDValue PtrLo =
5634       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5635   SDValue PtrHi;
5636   if (GAFlags == SIInstrInfo::MO_NONE) {
5637     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5638   } else {
5639     PtrHi =
5640         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5641   }
5642   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5643 }
5644 
5645 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5646                                              SDValue Op,
5647                                              SelectionDAG &DAG) const {
5648   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5649   SDLoc DL(GSD);
5650   EVT PtrVT = Op.getValueType();
5651 
5652   const GlobalValue *GV = GSD->getGlobal();
5653   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5654        shouldUseLDSConstAddress(GV)) ||
5655       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5656       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5657     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5658         GV->hasExternalLinkage()) {
5659       Type *Ty = GV->getValueType();
5660       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5661       // zero-sized type in other languages to declare the dynamic shared
5662       // memory which size is not known at the compile time. They will be
5663       // allocated by the runtime and placed directly after the static
5664       // allocated ones. They all share the same offset.
5665       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5666         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5667         // Adjust alignment for that dynamic shared memory array.
5668         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5669         return SDValue(
5670             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5671       }
5672     }
5673     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5674   }
5675 
5676   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5677     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5678                                             SIInstrInfo::MO_ABS32_LO);
5679     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5680   }
5681 
5682   if (shouldEmitFixup(GV))
5683     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5684   else if (shouldEmitPCReloc(GV))
5685     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5686                                    SIInstrInfo::MO_REL32);
5687 
5688   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5689                                             SIInstrInfo::MO_GOTPCREL32);
5690 
5691   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5692   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5693   const DataLayout &DataLayout = DAG.getDataLayout();
5694   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5695   MachinePointerInfo PtrInfo
5696     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5697 
5698   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5699                      MachineMemOperand::MODereferenceable |
5700                          MachineMemOperand::MOInvariant);
5701 }
5702 
5703 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5704                                    const SDLoc &DL, SDValue V) const {
5705   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5706   // the destination register.
5707   //
5708   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5709   // so we will end up with redundant moves to m0.
5710   //
5711   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5712 
5713   // A Null SDValue creates a glue result.
5714   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5715                                   V, Chain);
5716   return SDValue(M0, 0);
5717 }
5718 
5719 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5720                                                  SDValue Op,
5721                                                  MVT VT,
5722                                                  unsigned Offset) const {
5723   SDLoc SL(Op);
5724   SDValue Param = lowerKernargMemParameter(
5725       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5726   // The local size values will have the hi 16-bits as zero.
5727   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5728                      DAG.getValueType(VT));
5729 }
5730 
5731 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5732                                         EVT VT) {
5733   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5734                                       "non-hsa intrinsic with hsa target",
5735                                       DL.getDebugLoc());
5736   DAG.getContext()->diagnose(BadIntrin);
5737   return DAG.getUNDEF(VT);
5738 }
5739 
5740 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5741                                          EVT VT) {
5742   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5743                                       "intrinsic not supported on subtarget",
5744                                       DL.getDebugLoc());
5745   DAG.getContext()->diagnose(BadIntrin);
5746   return DAG.getUNDEF(VT);
5747 }
5748 
5749 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5750                                     ArrayRef<SDValue> Elts) {
5751   assert(!Elts.empty());
5752   MVT Type;
5753   unsigned NumElts;
5754 
5755   if (Elts.size() == 1) {
5756     Type = MVT::f32;
5757     NumElts = 1;
5758   } else if (Elts.size() == 2) {
5759     Type = MVT::v2f32;
5760     NumElts = 2;
5761   } else if (Elts.size() == 3) {
5762     Type = MVT::v3f32;
5763     NumElts = 3;
5764   } else if (Elts.size() <= 4) {
5765     Type = MVT::v4f32;
5766     NumElts = 4;
5767   } else if (Elts.size() <= 8) {
5768     Type = MVT::v8f32;
5769     NumElts = 8;
5770   } else {
5771     assert(Elts.size() <= 16);
5772     Type = MVT::v16f32;
5773     NumElts = 16;
5774   }
5775 
5776   SmallVector<SDValue, 16> VecElts(NumElts);
5777   for (unsigned i = 0; i < Elts.size(); ++i) {
5778     SDValue Elt = Elts[i];
5779     if (Elt.getValueType() != MVT::f32)
5780       Elt = DAG.getBitcast(MVT::f32, Elt);
5781     VecElts[i] = Elt;
5782   }
5783   for (unsigned i = Elts.size(); i < NumElts; ++i)
5784     VecElts[i] = DAG.getUNDEF(MVT::f32);
5785 
5786   if (NumElts == 1)
5787     return VecElts[0];
5788   return DAG.getBuildVector(Type, DL, VecElts);
5789 }
5790 
5791 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5792                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5793   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5794 
5795   uint64_t Value = CachePolicyConst->getZExtValue();
5796   SDLoc DL(CachePolicy);
5797   if (GLC) {
5798     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5799     Value &= ~(uint64_t)0x1;
5800   }
5801   if (SLC) {
5802     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5803     Value &= ~(uint64_t)0x2;
5804   }
5805   if (DLC) {
5806     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5807     Value &= ~(uint64_t)0x4;
5808   }
5809 
5810   return Value == 0;
5811 }
5812 
5813 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5814                               SDValue Src, int ExtraElts) {
5815   EVT SrcVT = Src.getValueType();
5816 
5817   SmallVector<SDValue, 8> Elts;
5818 
5819   if (SrcVT.isVector())
5820     DAG.ExtractVectorElements(Src, Elts);
5821   else
5822     Elts.push_back(Src);
5823 
5824   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5825   while (ExtraElts--)
5826     Elts.push_back(Undef);
5827 
5828   return DAG.getBuildVector(CastVT, DL, Elts);
5829 }
5830 
5831 // Re-construct the required return value for a image load intrinsic.
5832 // This is more complicated due to the optional use TexFailCtrl which means the required
5833 // return type is an aggregate
5834 static SDValue constructRetValue(SelectionDAG &DAG,
5835                                  MachineSDNode *Result,
5836                                  ArrayRef<EVT> ResultTypes,
5837                                  bool IsTexFail, bool Unpacked, bool IsD16,
5838                                  int DMaskPop, int NumVDataDwords,
5839                                  const SDLoc &DL, LLVMContext &Context) {
5840   // Determine the required return type. This is the same regardless of IsTexFail flag
5841   EVT ReqRetVT = ResultTypes[0];
5842   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5843   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5844     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5845 
5846   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5847     DMaskPop : (DMaskPop + 1) / 2;
5848 
5849   MVT DataDwordVT = NumDataDwords == 1 ?
5850     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5851 
5852   MVT MaskPopVT = MaskPopDwords == 1 ?
5853     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5854 
5855   SDValue Data(Result, 0);
5856   SDValue TexFail;
5857 
5858   if (IsTexFail) {
5859     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5860     if (MaskPopVT.isVector()) {
5861       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5862                          SDValue(Result, 0), ZeroIdx);
5863     } else {
5864       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5865                          SDValue(Result, 0), ZeroIdx);
5866     }
5867 
5868     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5869                           SDValue(Result, 0),
5870                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5871   }
5872 
5873   if (DataDwordVT.isVector())
5874     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5875                           NumDataDwords - MaskPopDwords);
5876 
5877   if (IsD16)
5878     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5879 
5880   EVT LegalReqRetVT = ReqRetVT;
5881   if (!ReqRetVT.isVector()) {
5882     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5883   } else {
5884     // We need to widen the return vector to a legal type
5885     if ((ReqRetVT.getVectorNumElements() % 2) == 1) {
5886       LegalReqRetVT =
5887           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5888                            ReqRetVT.getVectorNumElements() + 1);
5889     }
5890   }
5891   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5892 
5893   if (TexFail)
5894     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5895 
5896   if (Result->getNumValues() == 1)
5897     return Data;
5898 
5899   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5900 }
5901 
5902 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5903                          SDValue *LWE, bool &IsTexFail) {
5904   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5905 
5906   uint64_t Value = TexFailCtrlConst->getZExtValue();
5907   if (Value) {
5908     IsTexFail = true;
5909   }
5910 
5911   SDLoc DL(TexFailCtrlConst);
5912   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5913   Value &= ~(uint64_t)0x1;
5914   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5915   Value &= ~(uint64_t)0x2;
5916 
5917   return Value == 0;
5918 }
5919 
5920 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5921                                         MVT PackVectorVT,
5922                                         SmallVectorImpl<SDValue> &PackedAddrs,
5923                                         unsigned DimIdx, unsigned EndIdx,
5924                                         unsigned NumGradients) {
5925   SDLoc DL(Op);
5926   for (unsigned I = DimIdx; I < EndIdx; I++) {
5927     SDValue Addr = Op.getOperand(I);
5928 
5929     // Gradients are packed with undef for each coordinate.
5930     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5931     // 1D: undef,dx/dh; undef,dx/dv
5932     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5933     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5934     if (((I + 1) >= EndIdx) ||
5935         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5936                                          I == DimIdx + NumGradients - 1))) {
5937       if (Addr.getValueType() != MVT::i16)
5938         Addr = DAG.getBitcast(MVT::i16, Addr);
5939       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5940     } else {
5941       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5942       I++;
5943     }
5944     Addr = DAG.getBitcast(MVT::f32, Addr);
5945     PackedAddrs.push_back(Addr);
5946   }
5947 }
5948 
5949 SDValue SITargetLowering::lowerImage(SDValue Op,
5950                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5951                                      SelectionDAG &DAG) const {
5952   SDLoc DL(Op);
5953   MachineFunction &MF = DAG.getMachineFunction();
5954   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5955   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5956       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5957   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5958   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5959       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5960   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5961       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5962   unsigned IntrOpcode = Intr->BaseOpcode;
5963   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5964 
5965   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5966   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5967   bool IsD16 = false;
5968   bool IsG16 = false;
5969   bool IsA16 = false;
5970   SDValue VData;
5971   int NumVDataDwords;
5972   bool AdjustRetType = false;
5973 
5974   unsigned AddrIdx; // Index of first address argument
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       AddrIdx = 4;
5993     } else {
5994       DMask = Is64Bit ? 0x3 : 0x1;
5995       NumVDataDwords = Is64Bit ? 2 : 1;
5996       AddrIdx = 3;
5997     }
5998   } else {
5999     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
6000     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
6001     DMask = DMaskConst->getZExtValue();
6002     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6003 
6004     if (BaseOpcode->Store) {
6005       VData = Op.getOperand(2);
6006 
6007       MVT StoreVT = VData.getSimpleValueType();
6008       if (StoreVT.getScalarType() == MVT::f16) {
6009         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6010           return Op; // D16 is unsupported for this instruction
6011 
6012         IsD16 = true;
6013         VData = handleD16VData(VData, DAG);
6014       }
6015 
6016       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6017     } else {
6018       // Work out the num dwords based on the dmask popcount and underlying type
6019       // and whether packing is supported.
6020       MVT LoadVT = ResultTypes[0].getSimpleVT();
6021       if (LoadVT.getScalarType() == MVT::f16) {
6022         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6023           return Op; // D16 is unsupported for this instruction
6024 
6025         IsD16 = true;
6026       }
6027 
6028       // Confirm that the return type is large enough for the dmask specified
6029       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6030           (!LoadVT.isVector() && DMaskLanes > 1))
6031           return Op;
6032 
6033       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
6034         NumVDataDwords = (DMaskLanes + 1) / 2;
6035       else
6036         NumVDataDwords = DMaskLanes;
6037 
6038       AdjustRetType = true;
6039     }
6040 
6041     AddrIdx = DMaskIdx + 1;
6042   }
6043 
6044   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
6045   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
6046   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
6047   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
6048                        NumCoords + NumLCM;
6049   unsigned NumMIVAddrs = NumVAddrs;
6050 
6051   SmallVector<SDValue, 4> VAddrs;
6052 
6053   // Optimize _L to _LZ when _L is zero
6054   if (LZMappingInfo) {
6055     if (auto ConstantLod =
6056          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
6057       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6058         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6059         NumMIVAddrs--;               // remove 'lod'
6060       }
6061     }
6062   }
6063 
6064   // Optimize _mip away, when 'lod' is zero
6065   if (MIPMappingInfo) {
6066     if (auto ConstantLod =
6067          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
6068       if (ConstantLod->isNullValue()) {
6069         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6070         NumMIVAddrs--;               // remove 'lod'
6071       }
6072     }
6073   }
6074 
6075   // Push back extra arguments.
6076   for (unsigned I = 0; I < BaseOpcode->NumExtraArgs; I++)
6077     VAddrs.push_back(Op.getOperand(AddrIdx + I));
6078 
6079   // Check for 16 bit addresses or derivatives and pack if true.
6080   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
6081   unsigned CoordIdx = DimIdx + NumGradients;
6082   unsigned CoordsEnd = AddrIdx + NumMIVAddrs;
6083 
6084   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
6085   MVT VAddrScalarVT = VAddrVT.getScalarType();
6086   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6087   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6088 
6089   VAddrVT = Op.getOperand(CoordIdx).getSimpleValueType();
6090   VAddrScalarVT = VAddrVT.getScalarType();
6091   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6092   if (IsA16 || IsG16) {
6093     if (IsA16) {
6094       if (!ST->hasA16()) {
6095         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6096                              "support 16 bit addresses\n");
6097         return Op;
6098       }
6099       if (!IsG16) {
6100         LLVM_DEBUG(
6101             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6102                       "need 16 bit derivatives but got 32 bit derivatives\n");
6103         return Op;
6104       }
6105     } else if (!ST->hasG16()) {
6106       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6107                            "support 16 bit derivatives\n");
6108       return Op;
6109     }
6110 
6111     if (BaseOpcode->Gradients && !IsA16) {
6112       if (!ST->hasG16()) {
6113         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6114                              "support 16 bit derivatives\n");
6115         return Op;
6116       }
6117       // Activate g16
6118       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6119           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6120       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6121     }
6122 
6123     // Don't compress addresses for G16
6124     const int PackEndIdx = IsA16 ? CoordsEnd : CoordIdx;
6125     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs, DimIdx,
6126                                 PackEndIdx, NumGradients);
6127 
6128     if (!IsA16) {
6129       // Add uncompressed address
6130       for (unsigned I = CoordIdx; I < CoordsEnd; I++)
6131         VAddrs.push_back(Op.getOperand(I));
6132     }
6133   } else {
6134     for (unsigned I = DimIdx; I < CoordsEnd; I++)
6135       VAddrs.push_back(Op.getOperand(I));
6136   }
6137 
6138   // If the register allocator cannot place the address registers contiguously
6139   // without introducing moves, then using the non-sequential address encoding
6140   // is always preferable, since it saves VALU instructions and is usually a
6141   // wash in terms of code size or even better.
6142   //
6143   // However, we currently have no way of hinting to the register allocator that
6144   // MIMG addresses should be placed contiguously when it is possible to do so,
6145   // so force non-NSA for the common 2-address case as a heuristic.
6146   //
6147   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6148   // allocation when possible.
6149   bool UseNSA =
6150       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6151   SDValue VAddr;
6152   if (!UseNSA)
6153     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6154 
6155   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6156   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6157   unsigned CtrlIdx; // Index of texfailctrl argument
6158   SDValue Unorm;
6159   if (!BaseOpcode->Sampler) {
6160     Unorm = True;
6161     CtrlIdx = AddrIdx + NumVAddrs + 1;
6162   } else {
6163     auto UnormConst =
6164         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
6165 
6166     Unorm = UnormConst->getZExtValue() ? True : False;
6167     CtrlIdx = AddrIdx + NumVAddrs + 3;
6168   }
6169 
6170   SDValue TFE;
6171   SDValue LWE;
6172   SDValue TexFail = Op.getOperand(CtrlIdx);
6173   bool IsTexFail = false;
6174   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6175     return Op;
6176 
6177   if (IsTexFail) {
6178     if (!DMaskLanes) {
6179       // Expecting to get an error flag since TFC is on - and dmask is 0
6180       // Force dmask to be at least 1 otherwise the instruction will fail
6181       DMask = 0x1;
6182       DMaskLanes = 1;
6183       NumVDataDwords = 1;
6184     }
6185     NumVDataDwords += 1;
6186     AdjustRetType = true;
6187   }
6188 
6189   // Has something earlier tagged that the return type needs adjusting
6190   // This happens if the instruction is a load or has set TexFailCtrl flags
6191   if (AdjustRetType) {
6192     // NumVDataDwords reflects the true number of dwords required in the return type
6193     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6194       // This is a no-op load. This can be eliminated
6195       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6196       if (isa<MemSDNode>(Op))
6197         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6198       return Undef;
6199     }
6200 
6201     EVT NewVT = NumVDataDwords > 1 ?
6202                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6203                 : MVT::i32;
6204 
6205     ResultTypes[0] = NewVT;
6206     if (ResultTypes.size() == 3) {
6207       // Original result was aggregate type used for TexFailCtrl results
6208       // The actual instruction returns as a vector type which has now been
6209       // created. Remove the aggregate result.
6210       ResultTypes.erase(&ResultTypes[1]);
6211     }
6212   }
6213 
6214   SDValue GLC;
6215   SDValue SLC;
6216   SDValue DLC;
6217   if (BaseOpcode->Atomic) {
6218     GLC = True; // TODO no-return optimization
6219     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
6220                           IsGFX10 ? &DLC : nullptr))
6221       return Op;
6222   } else {
6223     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
6224                           IsGFX10 ? &DLC : nullptr))
6225       return Op;
6226   }
6227 
6228   SmallVector<SDValue, 26> Ops;
6229   if (BaseOpcode->Store || BaseOpcode->Atomic)
6230     Ops.push_back(VData); // vdata
6231   if (UseNSA) {
6232     for (const SDValue &Addr : VAddrs)
6233       Ops.push_back(Addr);
6234   } else {
6235     Ops.push_back(VAddr);
6236   }
6237   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
6238   if (BaseOpcode->Sampler)
6239     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
6240   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6241   if (IsGFX10)
6242     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6243   Ops.push_back(Unorm);
6244   if (IsGFX10)
6245     Ops.push_back(DLC);
6246   Ops.push_back(GLC);
6247   Ops.push_back(SLC);
6248   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6249                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6250   if (IsGFX10)
6251     Ops.push_back(IsA16 ? True : False);
6252   Ops.push_back(TFE);
6253   Ops.push_back(LWE);
6254   if (!IsGFX10)
6255     Ops.push_back(DimInfo->DA ? True : False);
6256   if (BaseOpcode->HasD16)
6257     Ops.push_back(IsD16 ? True : False);
6258   if (isa<MemSDNode>(Op))
6259     Ops.push_back(Op.getOperand(0)); // chain
6260 
6261   int NumVAddrDwords =
6262       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6263   int Opcode = -1;
6264 
6265   if (IsGFX10) {
6266     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6267                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6268                                           : AMDGPU::MIMGEncGfx10Default,
6269                                    NumVDataDwords, NumVAddrDwords);
6270   } else {
6271     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6272       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6273                                      NumVDataDwords, NumVAddrDwords);
6274     if (Opcode == -1)
6275       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6276                                      NumVDataDwords, NumVAddrDwords);
6277   }
6278   assert(Opcode != -1);
6279 
6280   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6281   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6282     MachineMemOperand *MemRef = MemOp->getMemOperand();
6283     DAG.setNodeMemRefs(NewNode, {MemRef});
6284   }
6285 
6286   if (BaseOpcode->AtomicX2) {
6287     SmallVector<SDValue, 1> Elt;
6288     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6289     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6290   } else if (!BaseOpcode->Store) {
6291     return constructRetValue(DAG, NewNode,
6292                              OrigResultTypes, IsTexFail,
6293                              Subtarget->hasUnpackedD16VMem(), IsD16,
6294                              DMaskLanes, NumVDataDwords, DL,
6295                              *DAG.getContext());
6296   }
6297 
6298   return SDValue(NewNode, 0);
6299 }
6300 
6301 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6302                                        SDValue Offset, SDValue CachePolicy,
6303                                        SelectionDAG &DAG) const {
6304   MachineFunction &MF = DAG.getMachineFunction();
6305 
6306   const DataLayout &DataLayout = DAG.getDataLayout();
6307   Align Alignment =
6308       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6309 
6310   MachineMemOperand *MMO = MF.getMachineMemOperand(
6311       MachinePointerInfo(),
6312       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6313           MachineMemOperand::MOInvariant,
6314       VT.getStoreSize(), Alignment);
6315 
6316   if (!Offset->isDivergent()) {
6317     SDValue Ops[] = {
6318         Rsrc,
6319         Offset, // Offset
6320         CachePolicy
6321     };
6322 
6323     // Widen vec3 load to vec4.
6324     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6325       EVT WidenedVT =
6326           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6327       auto WidenedOp = DAG.getMemIntrinsicNode(
6328           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6329           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6330       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6331                                    DAG.getVectorIdxConstant(0, DL));
6332       return Subvector;
6333     }
6334 
6335     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6336                                    DAG.getVTList(VT), Ops, VT, MMO);
6337   }
6338 
6339   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6340   // assume that the buffer is unswizzled.
6341   SmallVector<SDValue, 4> Loads;
6342   unsigned NumLoads = 1;
6343   MVT LoadVT = VT.getSimpleVT();
6344   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6345   assert((LoadVT.getScalarType() == MVT::i32 ||
6346           LoadVT.getScalarType() == MVT::f32));
6347 
6348   if (NumElts == 8 || NumElts == 16) {
6349     NumLoads = NumElts / 4;
6350     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6351   }
6352 
6353   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6354   SDValue Ops[] = {
6355       DAG.getEntryNode(),                               // Chain
6356       Rsrc,                                             // rsrc
6357       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6358       {},                                               // voffset
6359       {},                                               // soffset
6360       {},                                               // offset
6361       CachePolicy,                                      // cachepolicy
6362       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6363   };
6364 
6365   // Use the alignment to ensure that the required offsets will fit into the
6366   // immediate offsets.
6367   setBufferOffsets(Offset, DAG, &Ops[3],
6368                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6369 
6370   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6371   for (unsigned i = 0; i < NumLoads; ++i) {
6372     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6373     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6374                                         LoadVT, MMO, DAG));
6375   }
6376 
6377   if (NumElts == 8 || NumElts == 16)
6378     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6379 
6380   return Loads[0];
6381 }
6382 
6383 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6384                                                   SelectionDAG &DAG) const {
6385   MachineFunction &MF = DAG.getMachineFunction();
6386   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6387 
6388   EVT VT = Op.getValueType();
6389   SDLoc DL(Op);
6390   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6391 
6392   // TODO: Should this propagate fast-math-flags?
6393 
6394   switch (IntrinsicID) {
6395   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6396     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6397       return emitNonHSAIntrinsicError(DAG, DL, VT);
6398     return getPreloadedValue(DAG, *MFI, VT,
6399                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6400   }
6401   case Intrinsic::amdgcn_dispatch_ptr:
6402   case Intrinsic::amdgcn_queue_ptr: {
6403     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6404       DiagnosticInfoUnsupported BadIntrin(
6405           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6406           DL.getDebugLoc());
6407       DAG.getContext()->diagnose(BadIntrin);
6408       return DAG.getUNDEF(VT);
6409     }
6410 
6411     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6412       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6413     return getPreloadedValue(DAG, *MFI, VT, RegID);
6414   }
6415   case Intrinsic::amdgcn_implicitarg_ptr: {
6416     if (MFI->isEntryFunction())
6417       return getImplicitArgPtr(DAG, DL);
6418     return getPreloadedValue(DAG, *MFI, VT,
6419                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6420   }
6421   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6422     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6423       // This only makes sense to call in a kernel, so just lower to null.
6424       return DAG.getConstant(0, DL, VT);
6425     }
6426 
6427     return getPreloadedValue(DAG, *MFI, VT,
6428                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6429   }
6430   case Intrinsic::amdgcn_dispatch_id: {
6431     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6432   }
6433   case Intrinsic::amdgcn_rcp:
6434     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6435   case Intrinsic::amdgcn_rsq:
6436     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6437   case Intrinsic::amdgcn_rsq_legacy:
6438     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6439       return emitRemovedIntrinsicError(DAG, DL, VT);
6440     return SDValue();
6441   case Intrinsic::amdgcn_rcp_legacy:
6442     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6443       return emitRemovedIntrinsicError(DAG, DL, VT);
6444     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6445   case Intrinsic::amdgcn_rsq_clamp: {
6446     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6447       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6448 
6449     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6450     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6451     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6452 
6453     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6454     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6455                               DAG.getConstantFP(Max, DL, VT));
6456     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6457                        DAG.getConstantFP(Min, DL, VT));
6458   }
6459   case Intrinsic::r600_read_ngroups_x:
6460     if (Subtarget->isAmdHsaOS())
6461       return emitNonHSAIntrinsicError(DAG, DL, VT);
6462 
6463     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6464                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6465                                     false);
6466   case Intrinsic::r600_read_ngroups_y:
6467     if (Subtarget->isAmdHsaOS())
6468       return emitNonHSAIntrinsicError(DAG, DL, VT);
6469 
6470     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6471                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6472                                     false);
6473   case Intrinsic::r600_read_ngroups_z:
6474     if (Subtarget->isAmdHsaOS())
6475       return emitNonHSAIntrinsicError(DAG, DL, VT);
6476 
6477     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6478                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6479                                     false);
6480   case Intrinsic::r600_read_global_size_x:
6481     if (Subtarget->isAmdHsaOS())
6482       return emitNonHSAIntrinsicError(DAG, DL, VT);
6483 
6484     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6485                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6486                                     Align(4), false);
6487   case Intrinsic::r600_read_global_size_y:
6488     if (Subtarget->isAmdHsaOS())
6489       return emitNonHSAIntrinsicError(DAG, DL, VT);
6490 
6491     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6492                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6493                                     Align(4), false);
6494   case Intrinsic::r600_read_global_size_z:
6495     if (Subtarget->isAmdHsaOS())
6496       return emitNonHSAIntrinsicError(DAG, DL, VT);
6497 
6498     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6499                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6500                                     Align(4), false);
6501   case Intrinsic::r600_read_local_size_x:
6502     if (Subtarget->isAmdHsaOS())
6503       return emitNonHSAIntrinsicError(DAG, DL, VT);
6504 
6505     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6506                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6507   case Intrinsic::r600_read_local_size_y:
6508     if (Subtarget->isAmdHsaOS())
6509       return emitNonHSAIntrinsicError(DAG, DL, VT);
6510 
6511     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6512                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6513   case Intrinsic::r600_read_local_size_z:
6514     if (Subtarget->isAmdHsaOS())
6515       return emitNonHSAIntrinsicError(DAG, DL, VT);
6516 
6517     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6518                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6519   case Intrinsic::amdgcn_workgroup_id_x:
6520     return getPreloadedValue(DAG, *MFI, VT,
6521                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6522   case Intrinsic::amdgcn_workgroup_id_y:
6523     return getPreloadedValue(DAG, *MFI, VT,
6524                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6525   case Intrinsic::amdgcn_workgroup_id_z:
6526     return getPreloadedValue(DAG, *MFI, VT,
6527                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6528   case Intrinsic::amdgcn_workitem_id_x:
6529     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6530                           SDLoc(DAG.getEntryNode()),
6531                           MFI->getArgInfo().WorkItemIDX);
6532   case Intrinsic::amdgcn_workitem_id_y:
6533     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6534                           SDLoc(DAG.getEntryNode()),
6535                           MFI->getArgInfo().WorkItemIDY);
6536   case Intrinsic::amdgcn_workitem_id_z:
6537     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6538                           SDLoc(DAG.getEntryNode()),
6539                           MFI->getArgInfo().WorkItemIDZ);
6540   case Intrinsic::amdgcn_wavefrontsize:
6541     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6542                            SDLoc(Op), MVT::i32);
6543   case Intrinsic::amdgcn_s_buffer_load: {
6544     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6545     SDValue GLC;
6546     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6547     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6548                           IsGFX10 ? &DLC : nullptr))
6549       return Op;
6550     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6551                         DAG);
6552   }
6553   case Intrinsic::amdgcn_fdiv_fast:
6554     return lowerFDIV_FAST(Op, DAG);
6555   case Intrinsic::amdgcn_sin:
6556     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6557 
6558   case Intrinsic::amdgcn_cos:
6559     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6560 
6561   case Intrinsic::amdgcn_mul_u24:
6562     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6563   case Intrinsic::amdgcn_mul_i24:
6564     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6565 
6566   case Intrinsic::amdgcn_log_clamp: {
6567     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6568       return SDValue();
6569 
6570     DiagnosticInfoUnsupported BadIntrin(
6571       MF.getFunction(), "intrinsic not supported on subtarget",
6572       DL.getDebugLoc());
6573       DAG.getContext()->diagnose(BadIntrin);
6574       return DAG.getUNDEF(VT);
6575   }
6576   case Intrinsic::amdgcn_ldexp:
6577     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6578                        Op.getOperand(1), Op.getOperand(2));
6579 
6580   case Intrinsic::amdgcn_fract:
6581     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6582 
6583   case Intrinsic::amdgcn_class:
6584     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6585                        Op.getOperand(1), Op.getOperand(2));
6586   case Intrinsic::amdgcn_div_fmas:
6587     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6588                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6589                        Op.getOperand(4));
6590 
6591   case Intrinsic::amdgcn_div_fixup:
6592     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6593                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6594 
6595   case Intrinsic::amdgcn_div_scale: {
6596     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6597 
6598     // Translate to the operands expected by the machine instruction. The
6599     // first parameter must be the same as the first instruction.
6600     SDValue Numerator = Op.getOperand(1);
6601     SDValue Denominator = Op.getOperand(2);
6602 
6603     // Note this order is opposite of the machine instruction's operations,
6604     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6605     // intrinsic has the numerator as the first operand to match a normal
6606     // division operation.
6607 
6608     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6609 
6610     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6611                        Denominator, Numerator);
6612   }
6613   case Intrinsic::amdgcn_icmp: {
6614     // There is a Pat that handles this variant, so return it as-is.
6615     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6616         Op.getConstantOperandVal(2) == 0 &&
6617         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6618       return Op;
6619     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6620   }
6621   case Intrinsic::amdgcn_fcmp: {
6622     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6623   }
6624   case Intrinsic::amdgcn_ballot:
6625     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6626   case Intrinsic::amdgcn_fmed3:
6627     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6628                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6629   case Intrinsic::amdgcn_fdot2:
6630     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6631                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6632                        Op.getOperand(4));
6633   case Intrinsic::amdgcn_fmul_legacy:
6634     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6635                        Op.getOperand(1), Op.getOperand(2));
6636   case Intrinsic::amdgcn_sffbh:
6637     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6638   case Intrinsic::amdgcn_sbfe:
6639     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6640                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6641   case Intrinsic::amdgcn_ubfe:
6642     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6643                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6644   case Intrinsic::amdgcn_cvt_pkrtz:
6645   case Intrinsic::amdgcn_cvt_pknorm_i16:
6646   case Intrinsic::amdgcn_cvt_pknorm_u16:
6647   case Intrinsic::amdgcn_cvt_pk_i16:
6648   case Intrinsic::amdgcn_cvt_pk_u16: {
6649     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6650     EVT VT = Op.getValueType();
6651     unsigned Opcode;
6652 
6653     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6654       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6655     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6656       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6657     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6658       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6659     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6660       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6661     else
6662       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6663 
6664     if (isTypeLegal(VT))
6665       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6666 
6667     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6668                                Op.getOperand(1), Op.getOperand(2));
6669     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6670   }
6671   case Intrinsic::amdgcn_fmad_ftz:
6672     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6673                        Op.getOperand(2), Op.getOperand(3));
6674 
6675   case Intrinsic::amdgcn_if_break:
6676     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6677                                       Op->getOperand(1), Op->getOperand(2)), 0);
6678 
6679   case Intrinsic::amdgcn_groupstaticsize: {
6680     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6681     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6682       return Op;
6683 
6684     const Module *M = MF.getFunction().getParent();
6685     const GlobalValue *GV =
6686         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6687     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6688                                             SIInstrInfo::MO_ABS32_LO);
6689     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6690   }
6691   case Intrinsic::amdgcn_is_shared:
6692   case Intrinsic::amdgcn_is_private: {
6693     SDLoc SL(Op);
6694     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6695       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6696     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6697     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6698                                  Op.getOperand(1));
6699 
6700     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6701                                 DAG.getConstant(1, SL, MVT::i32));
6702     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6703   }
6704   case Intrinsic::amdgcn_alignbit:
6705     return DAG.getNode(ISD::FSHR, DL, VT,
6706                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6707   case Intrinsic::amdgcn_reloc_constant: {
6708     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6709     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6710     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6711     auto RelocSymbol = cast<GlobalVariable>(
6712         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6713     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6714                                             SIInstrInfo::MO_ABS32_LO);
6715     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6716   }
6717   default:
6718     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6719             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6720       return lowerImage(Op, ImageDimIntr, DAG);
6721 
6722     return Op;
6723   }
6724 }
6725 
6726 // This function computes an appropriate offset to pass to
6727 // MachineMemOperand::setOffset() based on the offset inputs to
6728 // an intrinsic.  If any of the offsets are non-contstant or
6729 // if VIndex is non-zero then this function returns 0.  Otherwise,
6730 // it returns the sum of VOffset, SOffset, and Offset.
6731 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6732                                       SDValue SOffset,
6733                                       SDValue Offset,
6734                                       SDValue VIndex = SDValue()) {
6735 
6736   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6737       !isa<ConstantSDNode>(Offset))
6738     return 0;
6739 
6740   if (VIndex) {
6741     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6742       return 0;
6743   }
6744 
6745   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6746          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6747          cast<ConstantSDNode>(Offset)->getSExtValue();
6748 }
6749 
6750 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6751                                                      SelectionDAG &DAG,
6752                                                      unsigned NewOpcode) const {
6753   SDLoc DL(Op);
6754 
6755   SDValue VData = Op.getOperand(2);
6756   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6757   SDValue Ops[] = {
6758     Op.getOperand(0), // Chain
6759     VData,            // vdata
6760     Op.getOperand(3), // rsrc
6761     DAG.getConstant(0, DL, MVT::i32), // vindex
6762     Offsets.first,    // voffset
6763     Op.getOperand(5), // soffset
6764     Offsets.second,   // offset
6765     Op.getOperand(6), // cachepolicy
6766     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6767   };
6768 
6769   auto *M = cast<MemSDNode>(Op);
6770   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6771 
6772   EVT MemVT = VData.getValueType();
6773   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6774                                  M->getMemOperand());
6775 }
6776 
6777 SDValue
6778 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6779                                                 unsigned NewOpcode) const {
6780   SDLoc DL(Op);
6781 
6782   SDValue VData = Op.getOperand(2);
6783   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6784   SDValue Ops[] = {
6785     Op.getOperand(0), // Chain
6786     VData,            // vdata
6787     Op.getOperand(3), // rsrc
6788     Op.getOperand(4), // vindex
6789     Offsets.first,    // voffset
6790     Op.getOperand(6), // soffset
6791     Offsets.second,   // offset
6792     Op.getOperand(7), // cachepolicy
6793     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6794   };
6795 
6796   auto *M = cast<MemSDNode>(Op);
6797   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6798                                                       Ops[3]));
6799 
6800   EVT MemVT = VData.getValueType();
6801   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6802                                  M->getMemOperand());
6803 }
6804 
6805 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6806                                                  SelectionDAG &DAG) const {
6807   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6808   SDLoc DL(Op);
6809 
6810   switch (IntrID) {
6811   case Intrinsic::amdgcn_ds_ordered_add:
6812   case Intrinsic::amdgcn_ds_ordered_swap: {
6813     MemSDNode *M = cast<MemSDNode>(Op);
6814     SDValue Chain = M->getOperand(0);
6815     SDValue M0 = M->getOperand(2);
6816     SDValue Value = M->getOperand(3);
6817     unsigned IndexOperand = M->getConstantOperandVal(7);
6818     unsigned WaveRelease = M->getConstantOperandVal(8);
6819     unsigned WaveDone = M->getConstantOperandVal(9);
6820 
6821     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6822     IndexOperand &= ~0x3f;
6823     unsigned CountDw = 0;
6824 
6825     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6826       CountDw = (IndexOperand >> 24) & 0xf;
6827       IndexOperand &= ~(0xf << 24);
6828 
6829       if (CountDw < 1 || CountDw > 4) {
6830         report_fatal_error(
6831             "ds_ordered_count: dword count must be between 1 and 4");
6832       }
6833     }
6834 
6835     if (IndexOperand)
6836       report_fatal_error("ds_ordered_count: bad index operand");
6837 
6838     if (WaveDone && !WaveRelease)
6839       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6840 
6841     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6842     unsigned ShaderType =
6843         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6844     unsigned Offset0 = OrderedCountIndex << 2;
6845     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6846                        (Instruction << 4);
6847 
6848     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6849       Offset1 |= (CountDw - 1) << 6;
6850 
6851     unsigned Offset = Offset0 | (Offset1 << 8);
6852 
6853     SDValue Ops[] = {
6854       Chain,
6855       Value,
6856       DAG.getTargetConstant(Offset, DL, MVT::i16),
6857       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6858     };
6859     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6860                                    M->getVTList(), Ops, M->getMemoryVT(),
6861                                    M->getMemOperand());
6862   }
6863   case Intrinsic::amdgcn_ds_fadd: {
6864     MemSDNode *M = cast<MemSDNode>(Op);
6865     unsigned Opc;
6866     switch (IntrID) {
6867     case Intrinsic::amdgcn_ds_fadd:
6868       Opc = ISD::ATOMIC_LOAD_FADD;
6869       break;
6870     }
6871 
6872     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6873                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6874                          M->getMemOperand());
6875   }
6876   case Intrinsic::amdgcn_atomic_inc:
6877   case Intrinsic::amdgcn_atomic_dec:
6878   case Intrinsic::amdgcn_ds_fmin:
6879   case Intrinsic::amdgcn_ds_fmax: {
6880     MemSDNode *M = cast<MemSDNode>(Op);
6881     unsigned Opc;
6882     switch (IntrID) {
6883     case Intrinsic::amdgcn_atomic_inc:
6884       Opc = AMDGPUISD::ATOMIC_INC;
6885       break;
6886     case Intrinsic::amdgcn_atomic_dec:
6887       Opc = AMDGPUISD::ATOMIC_DEC;
6888       break;
6889     case Intrinsic::amdgcn_ds_fmin:
6890       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6891       break;
6892     case Intrinsic::amdgcn_ds_fmax:
6893       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6894       break;
6895     default:
6896       llvm_unreachable("Unknown intrinsic!");
6897     }
6898     SDValue Ops[] = {
6899       M->getOperand(0), // Chain
6900       M->getOperand(2), // Ptr
6901       M->getOperand(3)  // Value
6902     };
6903 
6904     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6905                                    M->getMemoryVT(), M->getMemOperand());
6906   }
6907   case Intrinsic::amdgcn_buffer_load:
6908   case Intrinsic::amdgcn_buffer_load_format: {
6909     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6910     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6911     unsigned IdxEn = 1;
6912     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6913       IdxEn = Idx->getZExtValue() != 0;
6914     SDValue Ops[] = {
6915       Op.getOperand(0), // Chain
6916       Op.getOperand(2), // rsrc
6917       Op.getOperand(3), // vindex
6918       SDValue(),        // voffset -- will be set by setBufferOffsets
6919       SDValue(),        // soffset -- will be set by setBufferOffsets
6920       SDValue(),        // offset -- will be set by setBufferOffsets
6921       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6922       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6923     };
6924 
6925     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6926     // We don't know the offset if vindex is non-zero, so clear it.
6927     if (IdxEn)
6928       Offset = 0;
6929 
6930     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6931         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6932 
6933     EVT VT = Op.getValueType();
6934     EVT IntVT = VT.changeTypeToInteger();
6935     auto *M = cast<MemSDNode>(Op);
6936     M->getMemOperand()->setOffset(Offset);
6937     EVT LoadVT = Op.getValueType();
6938 
6939     if (LoadVT.getScalarType() == MVT::f16)
6940       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6941                                  M, DAG, Ops);
6942 
6943     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6944     if (LoadVT.getScalarType() == MVT::i8 ||
6945         LoadVT.getScalarType() == MVT::i16)
6946       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6947 
6948     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6949                                M->getMemOperand(), DAG);
6950   }
6951   case Intrinsic::amdgcn_raw_buffer_load:
6952   case Intrinsic::amdgcn_raw_buffer_load_format: {
6953     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6954 
6955     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6956     SDValue Ops[] = {
6957       Op.getOperand(0), // Chain
6958       Op.getOperand(2), // rsrc
6959       DAG.getConstant(0, DL, MVT::i32), // vindex
6960       Offsets.first,    // voffset
6961       Op.getOperand(4), // soffset
6962       Offsets.second,   // offset
6963       Op.getOperand(5), // cachepolicy, swizzled buffer
6964       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6965     };
6966 
6967     auto *M = cast<MemSDNode>(Op);
6968     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6969     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6970   }
6971   case Intrinsic::amdgcn_struct_buffer_load:
6972   case Intrinsic::amdgcn_struct_buffer_load_format: {
6973     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6974 
6975     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6976     SDValue Ops[] = {
6977       Op.getOperand(0), // Chain
6978       Op.getOperand(2), // rsrc
6979       Op.getOperand(3), // vindex
6980       Offsets.first,    // voffset
6981       Op.getOperand(5), // soffset
6982       Offsets.second,   // offset
6983       Op.getOperand(6), // cachepolicy, swizzled buffer
6984       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6985     };
6986 
6987     auto *M = cast<MemSDNode>(Op);
6988     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6989                                                         Ops[2]));
6990     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6991   }
6992   case Intrinsic::amdgcn_tbuffer_load: {
6993     MemSDNode *M = cast<MemSDNode>(Op);
6994     EVT LoadVT = Op.getValueType();
6995 
6996     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6997     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6998     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6999     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7000     unsigned IdxEn = 1;
7001     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
7002       IdxEn = Idx->getZExtValue() != 0;
7003     SDValue Ops[] = {
7004       Op.getOperand(0),  // Chain
7005       Op.getOperand(2),  // rsrc
7006       Op.getOperand(3),  // vindex
7007       Op.getOperand(4),  // voffset
7008       Op.getOperand(5),  // soffset
7009       Op.getOperand(6),  // offset
7010       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7011       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7012       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7013     };
7014 
7015     if (LoadVT.getScalarType() == MVT::f16)
7016       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7017                                  M, DAG, Ops);
7018     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7019                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7020                                DAG);
7021   }
7022   case Intrinsic::amdgcn_raw_tbuffer_load: {
7023     MemSDNode *M = cast<MemSDNode>(Op);
7024     EVT LoadVT = Op.getValueType();
7025     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7026 
7027     SDValue Ops[] = {
7028       Op.getOperand(0),  // Chain
7029       Op.getOperand(2),  // rsrc
7030       DAG.getConstant(0, DL, MVT::i32), // vindex
7031       Offsets.first,     // voffset
7032       Op.getOperand(4),  // soffset
7033       Offsets.second,    // offset
7034       Op.getOperand(5),  // format
7035       Op.getOperand(6),  // cachepolicy, swizzled buffer
7036       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7037     };
7038 
7039     if (LoadVT.getScalarType() == MVT::f16)
7040       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7041                                  M, DAG, Ops);
7042     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7043                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7044                                DAG);
7045   }
7046   case Intrinsic::amdgcn_struct_tbuffer_load: {
7047     MemSDNode *M = cast<MemSDNode>(Op);
7048     EVT LoadVT = Op.getValueType();
7049     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7050 
7051     SDValue Ops[] = {
7052       Op.getOperand(0),  // Chain
7053       Op.getOperand(2),  // rsrc
7054       Op.getOperand(3),  // vindex
7055       Offsets.first,     // voffset
7056       Op.getOperand(5),  // soffset
7057       Offsets.second,    // offset
7058       Op.getOperand(6),  // format
7059       Op.getOperand(7),  // cachepolicy, swizzled buffer
7060       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7061     };
7062 
7063     if (LoadVT.getScalarType() == MVT::f16)
7064       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7065                                  M, DAG, Ops);
7066     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7067                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7068                                DAG);
7069   }
7070   case Intrinsic::amdgcn_buffer_atomic_swap:
7071   case Intrinsic::amdgcn_buffer_atomic_add:
7072   case Intrinsic::amdgcn_buffer_atomic_sub:
7073   case Intrinsic::amdgcn_buffer_atomic_csub:
7074   case Intrinsic::amdgcn_buffer_atomic_smin:
7075   case Intrinsic::amdgcn_buffer_atomic_umin:
7076   case Intrinsic::amdgcn_buffer_atomic_smax:
7077   case Intrinsic::amdgcn_buffer_atomic_umax:
7078   case Intrinsic::amdgcn_buffer_atomic_and:
7079   case Intrinsic::amdgcn_buffer_atomic_or:
7080   case Intrinsic::amdgcn_buffer_atomic_xor:
7081   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7082     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7083     unsigned IdxEn = 1;
7084     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7085       IdxEn = Idx->getZExtValue() != 0;
7086     SDValue Ops[] = {
7087       Op.getOperand(0), // Chain
7088       Op.getOperand(2), // vdata
7089       Op.getOperand(3), // rsrc
7090       Op.getOperand(4), // vindex
7091       SDValue(),        // voffset -- will be set by setBufferOffsets
7092       SDValue(),        // soffset -- will be set by setBufferOffsets
7093       SDValue(),        // offset -- will be set by setBufferOffsets
7094       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7095       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7096     };
7097     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7098     // We don't know the offset if vindex is non-zero, so clear it.
7099     if (IdxEn)
7100       Offset = 0;
7101     EVT VT = Op.getValueType();
7102 
7103     auto *M = cast<MemSDNode>(Op);
7104     M->getMemOperand()->setOffset(Offset);
7105     unsigned Opcode = 0;
7106 
7107     switch (IntrID) {
7108     case Intrinsic::amdgcn_buffer_atomic_swap:
7109       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7110       break;
7111     case Intrinsic::amdgcn_buffer_atomic_add:
7112       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7113       break;
7114     case Intrinsic::amdgcn_buffer_atomic_sub:
7115       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7116       break;
7117     case Intrinsic::amdgcn_buffer_atomic_csub:
7118       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7119       break;
7120     case Intrinsic::amdgcn_buffer_atomic_smin:
7121       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7122       break;
7123     case Intrinsic::amdgcn_buffer_atomic_umin:
7124       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7125       break;
7126     case Intrinsic::amdgcn_buffer_atomic_smax:
7127       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7128       break;
7129     case Intrinsic::amdgcn_buffer_atomic_umax:
7130       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7131       break;
7132     case Intrinsic::amdgcn_buffer_atomic_and:
7133       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7134       break;
7135     case Intrinsic::amdgcn_buffer_atomic_or:
7136       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7137       break;
7138     case Intrinsic::amdgcn_buffer_atomic_xor:
7139       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7140       break;
7141     case Intrinsic::amdgcn_buffer_atomic_fadd:
7142       if (!Op.getValue(0).use_empty()) {
7143         DiagnosticInfoUnsupported
7144           NoFpRet(DAG.getMachineFunction().getFunction(),
7145                   "return versions of fp atomics not supported",
7146                   DL.getDebugLoc(), DS_Error);
7147         DAG.getContext()->diagnose(NoFpRet);
7148         return SDValue();
7149       }
7150       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7151       break;
7152     default:
7153       llvm_unreachable("unhandled atomic opcode");
7154     }
7155 
7156     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7157                                    M->getMemOperand());
7158   }
7159   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7160     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7161   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7162     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7163   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7164     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7165   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7166     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7167   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7168     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7169   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7170     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7171   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7172     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7173   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7174     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7175   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7176     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7177   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7178     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7179   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7180     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7181   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7182     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7183   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7184     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7185   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7186     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7187   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7188     return lowerStructBufferAtomicIntrin(Op, DAG,
7189                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7190   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7191     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7192   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7193     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7194   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7195     return lowerStructBufferAtomicIntrin(Op, DAG,
7196                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7197   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7198     return lowerStructBufferAtomicIntrin(Op, DAG,
7199                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7200   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7201     return lowerStructBufferAtomicIntrin(Op, DAG,
7202                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7203   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7204     return lowerStructBufferAtomicIntrin(Op, DAG,
7205                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7206   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7207     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7208   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7209     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7210   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7211     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7212   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7213     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7214   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7215     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7216 
7217   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7218     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7219     unsigned IdxEn = 1;
7220     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7221       IdxEn = Idx->getZExtValue() != 0;
7222     SDValue Ops[] = {
7223       Op.getOperand(0), // Chain
7224       Op.getOperand(2), // src
7225       Op.getOperand(3), // cmp
7226       Op.getOperand(4), // rsrc
7227       Op.getOperand(5), // vindex
7228       SDValue(),        // voffset -- will be set by setBufferOffsets
7229       SDValue(),        // soffset -- will be set by setBufferOffsets
7230       SDValue(),        // offset -- will be set by setBufferOffsets
7231       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7232       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7233     };
7234     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7235     // We don't know the offset if vindex is non-zero, so clear it.
7236     if (IdxEn)
7237       Offset = 0;
7238     EVT VT = Op.getValueType();
7239     auto *M = cast<MemSDNode>(Op);
7240     M->getMemOperand()->setOffset(Offset);
7241 
7242     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7243                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7244   }
7245   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7246     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7247     SDValue Ops[] = {
7248       Op.getOperand(0), // Chain
7249       Op.getOperand(2), // src
7250       Op.getOperand(3), // cmp
7251       Op.getOperand(4), // rsrc
7252       DAG.getConstant(0, DL, MVT::i32), // vindex
7253       Offsets.first,    // voffset
7254       Op.getOperand(6), // soffset
7255       Offsets.second,   // offset
7256       Op.getOperand(7), // cachepolicy
7257       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7258     };
7259     EVT VT = Op.getValueType();
7260     auto *M = cast<MemSDNode>(Op);
7261     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7262 
7263     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7264                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7265   }
7266   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7267     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7268     SDValue Ops[] = {
7269       Op.getOperand(0), // Chain
7270       Op.getOperand(2), // src
7271       Op.getOperand(3), // cmp
7272       Op.getOperand(4), // rsrc
7273       Op.getOperand(5), // vindex
7274       Offsets.first,    // voffset
7275       Op.getOperand(7), // soffset
7276       Offsets.second,   // offset
7277       Op.getOperand(8), // cachepolicy
7278       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7279     };
7280     EVT VT = Op.getValueType();
7281     auto *M = cast<MemSDNode>(Op);
7282     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7283                                                         Ops[4]));
7284 
7285     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7286                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7287   }
7288   case Intrinsic::amdgcn_global_atomic_fadd: {
7289     if (!Op.getValue(0).use_empty()) {
7290       DiagnosticInfoUnsupported
7291         NoFpRet(DAG.getMachineFunction().getFunction(),
7292                 "return versions of fp atomics not supported",
7293                 DL.getDebugLoc(), DS_Error);
7294       DAG.getContext()->diagnose(NoFpRet);
7295       return SDValue();
7296     }
7297     MemSDNode *M = cast<MemSDNode>(Op);
7298     SDValue Ops[] = {
7299       M->getOperand(0), // Chain
7300       M->getOperand(2), // Ptr
7301       M->getOperand(3)  // Value
7302     };
7303 
7304     EVT VT = Op.getOperand(3).getValueType();
7305     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7306                          DAG.getVTList(VT, MVT::Other), Ops,
7307                          M->getMemOperand());
7308   }
7309   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7310     SDLoc DL(Op);
7311     MemSDNode *M = cast<MemSDNode>(Op);
7312     SDValue NodePtr = M->getOperand(2);
7313     SDValue RayExtent = M->getOperand(3);
7314     SDValue RayOrigin = M->getOperand(4);
7315     SDValue RayDir = M->getOperand(5);
7316     SDValue RayInvDir = M->getOperand(6);
7317     SDValue TDescr = M->getOperand(7);
7318 
7319     assert(NodePtr.getValueType() == MVT::i32 ||
7320            NodePtr.getValueType() == MVT::i64);
7321     assert(RayDir.getValueType() == MVT::v4f16 ||
7322            RayDir.getValueType() == MVT::v4f32);
7323 
7324     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7325     bool Is64 = NodePtr.getValueType() == MVT::i64;
7326     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7327                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7328                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7329                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7330 
7331     SmallVector<SDValue, 16> Ops;
7332 
7333     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7334       SmallVector<SDValue, 3> Lanes;
7335       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7336       if (Lanes[0].getValueSizeInBits() == 32) {
7337         for (unsigned I = 0; I < 3; ++I)
7338           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7339       } else {
7340         if (IsAligned) {
7341           Ops.push_back(
7342             DAG.getBitcast(MVT::i32,
7343                            DAG.getBuildVector(MVT::v2f16, DL,
7344                                               { Lanes[0], Lanes[1] })));
7345           Ops.push_back(Lanes[2]);
7346         } else {
7347           SDValue Elt0 = Ops.pop_back_val();
7348           Ops.push_back(
7349             DAG.getBitcast(MVT::i32,
7350                            DAG.getBuildVector(MVT::v2f16, DL,
7351                                               { Elt0, Lanes[0] })));
7352           Ops.push_back(
7353             DAG.getBitcast(MVT::i32,
7354                            DAG.getBuildVector(MVT::v2f16, DL,
7355                                               { Lanes[1], Lanes[2] })));
7356         }
7357       }
7358     };
7359 
7360     if (Is64)
7361       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7362     else
7363       Ops.push_back(NodePtr);
7364 
7365     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7366     packLanes(RayOrigin, true);
7367     packLanes(RayDir, true);
7368     packLanes(RayInvDir, false);
7369     Ops.push_back(TDescr);
7370     if (IsA16)
7371       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7372     Ops.push_back(M->getChain());
7373 
7374     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7375     MachineMemOperand *MemRef = M->getMemOperand();
7376     DAG.setNodeMemRefs(NewNode, {MemRef});
7377     return SDValue(NewNode, 0);
7378   }
7379   default:
7380     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7381             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7382       return lowerImage(Op, ImageDimIntr, DAG);
7383 
7384     return SDValue();
7385   }
7386 }
7387 
7388 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7389 // dwordx4 if on SI.
7390 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7391                                               SDVTList VTList,
7392                                               ArrayRef<SDValue> Ops, EVT MemVT,
7393                                               MachineMemOperand *MMO,
7394                                               SelectionDAG &DAG) const {
7395   EVT VT = VTList.VTs[0];
7396   EVT WidenedVT = VT;
7397   EVT WidenedMemVT = MemVT;
7398   if (!Subtarget->hasDwordx3LoadStores() &&
7399       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7400     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7401                                  WidenedVT.getVectorElementType(), 4);
7402     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7403                                     WidenedMemVT.getVectorElementType(), 4);
7404     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7405   }
7406 
7407   assert(VTList.NumVTs == 2);
7408   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7409 
7410   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7411                                        WidenedMemVT, MMO);
7412   if (WidenedVT != VT) {
7413     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7414                                DAG.getVectorIdxConstant(0, DL));
7415     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7416   }
7417   return NewOp;
7418 }
7419 
7420 SDValue SITargetLowering::handleD16VData(SDValue VData,
7421                                          SelectionDAG &DAG) const {
7422   EVT StoreVT = VData.getValueType();
7423 
7424   // No change for f16 and legal vector D16 types.
7425   if (!StoreVT.isVector())
7426     return VData;
7427 
7428   SDLoc DL(VData);
7429   unsigned NumElements = StoreVT.getVectorNumElements();
7430 
7431   if (Subtarget->hasUnpackedD16VMem()) {
7432     // We need to unpack the packed data to store.
7433     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7434     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7435 
7436     EVT EquivStoreVT =
7437         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7438     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7439     return DAG.UnrollVectorOp(ZExt.getNode());
7440   } else if (NumElements == 3) {
7441     EVT IntStoreVT =
7442         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7443     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7444 
7445     EVT WidenedStoreVT = EVT::getVectorVT(
7446         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7447     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7448                                          WidenedStoreVT.getStoreSizeInBits());
7449     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7450     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7451   }
7452 
7453   assert(isTypeLegal(StoreVT));
7454   return VData;
7455 }
7456 
7457 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7458                                               SelectionDAG &DAG) const {
7459   SDLoc DL(Op);
7460   SDValue Chain = Op.getOperand(0);
7461   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7462   MachineFunction &MF = DAG.getMachineFunction();
7463 
7464   switch (IntrinsicID) {
7465   case Intrinsic::amdgcn_exp_compr: {
7466     SDValue Src0 = Op.getOperand(4);
7467     SDValue Src1 = Op.getOperand(5);
7468     // Hack around illegal type on SI by directly selecting it.
7469     if (isTypeLegal(Src0.getValueType()))
7470       return SDValue();
7471 
7472     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7473     SDValue Undef = DAG.getUNDEF(MVT::f32);
7474     const SDValue Ops[] = {
7475       Op.getOperand(2), // tgt
7476       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7477       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7478       Undef, // src2
7479       Undef, // src3
7480       Op.getOperand(7), // vm
7481       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7482       Op.getOperand(3), // en
7483       Op.getOperand(0) // Chain
7484     };
7485 
7486     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7487     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7488   }
7489   case Intrinsic::amdgcn_s_barrier: {
7490     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7491       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7492       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7493       if (WGSize <= ST.getWavefrontSize())
7494         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7495                                           Op.getOperand(0)), 0);
7496     }
7497     return SDValue();
7498   };
7499   case Intrinsic::amdgcn_tbuffer_store: {
7500     SDValue VData = Op.getOperand(2);
7501     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7502     if (IsD16)
7503       VData = handleD16VData(VData, DAG);
7504     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7505     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7506     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7507     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7508     unsigned IdxEn = 1;
7509     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7510       IdxEn = Idx->getZExtValue() != 0;
7511     SDValue Ops[] = {
7512       Chain,
7513       VData,             // vdata
7514       Op.getOperand(3),  // rsrc
7515       Op.getOperand(4),  // vindex
7516       Op.getOperand(5),  // voffset
7517       Op.getOperand(6),  // soffset
7518       Op.getOperand(7),  // offset
7519       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7520       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7521       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7522     };
7523     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7524                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7525     MemSDNode *M = cast<MemSDNode>(Op);
7526     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7527                                    M->getMemoryVT(), M->getMemOperand());
7528   }
7529 
7530   case Intrinsic::amdgcn_struct_tbuffer_store: {
7531     SDValue VData = Op.getOperand(2);
7532     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7533     if (IsD16)
7534       VData = handleD16VData(VData, DAG);
7535     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7536     SDValue Ops[] = {
7537       Chain,
7538       VData,             // vdata
7539       Op.getOperand(3),  // rsrc
7540       Op.getOperand(4),  // vindex
7541       Offsets.first,     // voffset
7542       Op.getOperand(6),  // soffset
7543       Offsets.second,    // offset
7544       Op.getOperand(7),  // format
7545       Op.getOperand(8),  // cachepolicy, swizzled buffer
7546       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7547     };
7548     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7549                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7550     MemSDNode *M = cast<MemSDNode>(Op);
7551     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7552                                    M->getMemoryVT(), M->getMemOperand());
7553   }
7554 
7555   case Intrinsic::amdgcn_raw_tbuffer_store: {
7556     SDValue VData = Op.getOperand(2);
7557     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7558     if (IsD16)
7559       VData = handleD16VData(VData, DAG);
7560     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7561     SDValue Ops[] = {
7562       Chain,
7563       VData,             // vdata
7564       Op.getOperand(3),  // rsrc
7565       DAG.getConstant(0, DL, MVT::i32), // vindex
7566       Offsets.first,     // voffset
7567       Op.getOperand(5),  // soffset
7568       Offsets.second,    // offset
7569       Op.getOperand(6),  // format
7570       Op.getOperand(7),  // cachepolicy, swizzled buffer
7571       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7572     };
7573     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7574                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7575     MemSDNode *M = cast<MemSDNode>(Op);
7576     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7577                                    M->getMemoryVT(), M->getMemOperand());
7578   }
7579 
7580   case Intrinsic::amdgcn_buffer_store:
7581   case Intrinsic::amdgcn_buffer_store_format: {
7582     SDValue VData = Op.getOperand(2);
7583     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7584     if (IsD16)
7585       VData = handleD16VData(VData, DAG);
7586     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7587     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7588     unsigned IdxEn = 1;
7589     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7590       IdxEn = Idx->getZExtValue() != 0;
7591     SDValue Ops[] = {
7592       Chain,
7593       VData,
7594       Op.getOperand(3), // rsrc
7595       Op.getOperand(4), // vindex
7596       SDValue(), // voffset -- will be set by setBufferOffsets
7597       SDValue(), // soffset -- will be set by setBufferOffsets
7598       SDValue(), // offset -- will be set by setBufferOffsets
7599       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7600       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7601     };
7602     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7603     // We don't know the offset if vindex is non-zero, so clear it.
7604     if (IdxEn)
7605       Offset = 0;
7606     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7607                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7608     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7609     MemSDNode *M = cast<MemSDNode>(Op);
7610     M->getMemOperand()->setOffset(Offset);
7611 
7612     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7613     EVT VDataType = VData.getValueType().getScalarType();
7614     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7615       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7616 
7617     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7618                                    M->getMemoryVT(), M->getMemOperand());
7619   }
7620 
7621   case Intrinsic::amdgcn_raw_buffer_store:
7622   case Intrinsic::amdgcn_raw_buffer_store_format: {
7623     const bool IsFormat =
7624         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7625 
7626     SDValue VData = Op.getOperand(2);
7627     EVT VDataVT = VData.getValueType();
7628     EVT EltType = VDataVT.getScalarType();
7629     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7630     if (IsD16) {
7631       VData = handleD16VData(VData, DAG);
7632       VDataVT = VData.getValueType();
7633     }
7634 
7635     if (!isTypeLegal(VDataVT)) {
7636       VData =
7637           DAG.getNode(ISD::BITCAST, DL,
7638                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7639     }
7640 
7641     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7642     SDValue Ops[] = {
7643       Chain,
7644       VData,
7645       Op.getOperand(3), // rsrc
7646       DAG.getConstant(0, DL, MVT::i32), // vindex
7647       Offsets.first,    // voffset
7648       Op.getOperand(5), // soffset
7649       Offsets.second,   // offset
7650       Op.getOperand(6), // cachepolicy, swizzled buffer
7651       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7652     };
7653     unsigned Opc =
7654         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7655     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7656     MemSDNode *M = cast<MemSDNode>(Op);
7657     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7658 
7659     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7660     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7661       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7662 
7663     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7664                                    M->getMemoryVT(), M->getMemOperand());
7665   }
7666 
7667   case Intrinsic::amdgcn_struct_buffer_store:
7668   case Intrinsic::amdgcn_struct_buffer_store_format: {
7669     const bool IsFormat =
7670         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7671 
7672     SDValue VData = Op.getOperand(2);
7673     EVT VDataVT = VData.getValueType();
7674     EVT EltType = VDataVT.getScalarType();
7675     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7676 
7677     if (IsD16) {
7678       VData = handleD16VData(VData, DAG);
7679       VDataVT = VData.getValueType();
7680     }
7681 
7682     if (!isTypeLegal(VDataVT)) {
7683       VData =
7684           DAG.getNode(ISD::BITCAST, DL,
7685                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7686     }
7687 
7688     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7689     SDValue Ops[] = {
7690       Chain,
7691       VData,
7692       Op.getOperand(3), // rsrc
7693       Op.getOperand(4), // vindex
7694       Offsets.first,    // voffset
7695       Op.getOperand(6), // soffset
7696       Offsets.second,   // offset
7697       Op.getOperand(7), // cachepolicy, swizzled buffer
7698       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7699     };
7700     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7701                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7702     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7703     MemSDNode *M = cast<MemSDNode>(Op);
7704     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7705                                                         Ops[3]));
7706 
7707     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7708     EVT VDataType = VData.getValueType().getScalarType();
7709     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7710       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7711 
7712     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7713                                    M->getMemoryVT(), M->getMemOperand());
7714   }
7715   case Intrinsic::amdgcn_end_cf:
7716     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7717                                       Op->getOperand(2), Chain), 0);
7718 
7719   default: {
7720     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7721             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7722       return lowerImage(Op, ImageDimIntr, DAG);
7723 
7724     return Op;
7725   }
7726   }
7727 }
7728 
7729 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7730 // offset (the offset that is included in bounds checking and swizzling, to be
7731 // split between the instruction's voffset and immoffset fields) and soffset
7732 // (the offset that is excluded from bounds checking and swizzling, to go in
7733 // the instruction's soffset field).  This function takes the first kind of
7734 // offset and figures out how to split it between voffset and immoffset.
7735 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7736     SDValue Offset, SelectionDAG &DAG) const {
7737   SDLoc DL(Offset);
7738   const unsigned MaxImm = 4095;
7739   SDValue N0 = Offset;
7740   ConstantSDNode *C1 = nullptr;
7741 
7742   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7743     N0 = SDValue();
7744   else if (DAG.isBaseWithConstantOffset(N0)) {
7745     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7746     N0 = N0.getOperand(0);
7747   }
7748 
7749   if (C1) {
7750     unsigned ImmOffset = C1->getZExtValue();
7751     // If the immediate value is too big for the immoffset field, put the value
7752     // and -4096 into the immoffset field so that the value that is copied/added
7753     // for the voffset field is a multiple of 4096, and it stands more chance
7754     // of being CSEd with the copy/add for another similar load/store.
7755     // However, do not do that rounding down to a multiple of 4096 if that is a
7756     // negative number, as it appears to be illegal to have a negative offset
7757     // in the vgpr, even if adding the immediate offset makes it positive.
7758     unsigned Overflow = ImmOffset & ~MaxImm;
7759     ImmOffset -= Overflow;
7760     if ((int32_t)Overflow < 0) {
7761       Overflow += ImmOffset;
7762       ImmOffset = 0;
7763     }
7764     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7765     if (Overflow) {
7766       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7767       if (!N0)
7768         N0 = OverflowVal;
7769       else {
7770         SDValue Ops[] = { N0, OverflowVal };
7771         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7772       }
7773     }
7774   }
7775   if (!N0)
7776     N0 = DAG.getConstant(0, DL, MVT::i32);
7777   if (!C1)
7778     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7779   return {N0, SDValue(C1, 0)};
7780 }
7781 
7782 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7783 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7784 // pointed to by Offsets.
7785 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7786                                             SelectionDAG &DAG, SDValue *Offsets,
7787                                             Align Alignment) const {
7788   SDLoc DL(CombinedOffset);
7789   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7790     uint32_t Imm = C->getZExtValue();
7791     uint32_t SOffset, ImmOffset;
7792     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7793                                  Alignment)) {
7794       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7795       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7796       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7797       return SOffset + ImmOffset;
7798     }
7799   }
7800   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7801     SDValue N0 = CombinedOffset.getOperand(0);
7802     SDValue N1 = CombinedOffset.getOperand(1);
7803     uint32_t SOffset, ImmOffset;
7804     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7805     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7806                                                 Subtarget, Alignment)) {
7807       Offsets[0] = N0;
7808       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7809       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7810       return 0;
7811     }
7812   }
7813   Offsets[0] = CombinedOffset;
7814   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7815   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7816   return 0;
7817 }
7818 
7819 // Handle 8 bit and 16 bit buffer loads
7820 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7821                                                      EVT LoadVT, SDLoc DL,
7822                                                      ArrayRef<SDValue> Ops,
7823                                                      MemSDNode *M) const {
7824   EVT IntVT = LoadVT.changeTypeToInteger();
7825   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7826          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7827 
7828   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7829   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7830                                                Ops, IntVT,
7831                                                M->getMemOperand());
7832   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7833   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7834 
7835   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7836 }
7837 
7838 // Handle 8 bit and 16 bit buffer stores
7839 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7840                                                       EVT VDataType, SDLoc DL,
7841                                                       SDValue Ops[],
7842                                                       MemSDNode *M) const {
7843   if (VDataType == MVT::f16)
7844     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7845 
7846   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7847   Ops[1] = BufferStoreExt;
7848   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7849                                  AMDGPUISD::BUFFER_STORE_SHORT;
7850   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7851   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7852                                      M->getMemOperand());
7853 }
7854 
7855 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7856                                  ISD::LoadExtType ExtType, SDValue Op,
7857                                  const SDLoc &SL, EVT VT) {
7858   if (VT.bitsLT(Op.getValueType()))
7859     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7860 
7861   switch (ExtType) {
7862   case ISD::SEXTLOAD:
7863     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7864   case ISD::ZEXTLOAD:
7865     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7866   case ISD::EXTLOAD:
7867     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7868   case ISD::NON_EXTLOAD:
7869     return Op;
7870   }
7871 
7872   llvm_unreachable("invalid ext type");
7873 }
7874 
7875 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7876   SelectionDAG &DAG = DCI.DAG;
7877   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7878     return SDValue();
7879 
7880   // FIXME: Constant loads should all be marked invariant.
7881   unsigned AS = Ld->getAddressSpace();
7882   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7883       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7884       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7885     return SDValue();
7886 
7887   // Don't do this early, since it may interfere with adjacent load merging for
7888   // illegal types. We can avoid losing alignment information for exotic types
7889   // pre-legalize.
7890   EVT MemVT = Ld->getMemoryVT();
7891   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7892       MemVT.getSizeInBits() >= 32)
7893     return SDValue();
7894 
7895   SDLoc SL(Ld);
7896 
7897   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7898          "unexpected vector extload");
7899 
7900   // TODO: Drop only high part of range.
7901   SDValue Ptr = Ld->getBasePtr();
7902   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7903                                 MVT::i32, SL, Ld->getChain(), Ptr,
7904                                 Ld->getOffset(),
7905                                 Ld->getPointerInfo(), MVT::i32,
7906                                 Ld->getAlignment(),
7907                                 Ld->getMemOperand()->getFlags(),
7908                                 Ld->getAAInfo(),
7909                                 nullptr); // Drop ranges
7910 
7911   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7912   if (MemVT.isFloatingPoint()) {
7913     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7914            "unexpected fp extload");
7915     TruncVT = MemVT.changeTypeToInteger();
7916   }
7917 
7918   SDValue Cvt = NewLoad;
7919   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7920     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7921                       DAG.getValueType(TruncVT));
7922   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7923              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7924     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7925   } else {
7926     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7927   }
7928 
7929   EVT VT = Ld->getValueType(0);
7930   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7931 
7932   DCI.AddToWorklist(Cvt.getNode());
7933 
7934   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7935   // the appropriate extension from the 32-bit load.
7936   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7937   DCI.AddToWorklist(Cvt.getNode());
7938 
7939   // Handle conversion back to floating point if necessary.
7940   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7941 
7942   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7943 }
7944 
7945 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7946   SDLoc DL(Op);
7947   LoadSDNode *Load = cast<LoadSDNode>(Op);
7948   ISD::LoadExtType ExtType = Load->getExtensionType();
7949   EVT MemVT = Load->getMemoryVT();
7950 
7951   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7952     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7953       return SDValue();
7954 
7955     // FIXME: Copied from PPC
7956     // First, load into 32 bits, then truncate to 1 bit.
7957 
7958     SDValue Chain = Load->getChain();
7959     SDValue BasePtr = Load->getBasePtr();
7960     MachineMemOperand *MMO = Load->getMemOperand();
7961 
7962     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7963 
7964     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7965                                    BasePtr, RealMemVT, MMO);
7966 
7967     if (!MemVT.isVector()) {
7968       SDValue Ops[] = {
7969         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7970         NewLD.getValue(1)
7971       };
7972 
7973       return DAG.getMergeValues(Ops, DL);
7974     }
7975 
7976     SmallVector<SDValue, 3> Elts;
7977     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7978       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7979                                 DAG.getConstant(I, DL, MVT::i32));
7980 
7981       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7982     }
7983 
7984     SDValue Ops[] = {
7985       DAG.getBuildVector(MemVT, DL, Elts),
7986       NewLD.getValue(1)
7987     };
7988 
7989     return DAG.getMergeValues(Ops, DL);
7990   }
7991 
7992   if (!MemVT.isVector())
7993     return SDValue();
7994 
7995   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7996          "Custom lowering for non-i32 vectors hasn't been implemented.");
7997 
7998   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7999                                       MemVT, *Load->getMemOperand())) {
8000     SDValue Ops[2];
8001     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8002     return DAG.getMergeValues(Ops, DL);
8003   }
8004 
8005   unsigned Alignment = Load->getAlignment();
8006   unsigned AS = Load->getAddressSpace();
8007   if (Subtarget->hasLDSMisalignedBug() &&
8008       AS == AMDGPUAS::FLAT_ADDRESS &&
8009       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8010     return SplitVectorLoad(Op, DAG);
8011   }
8012 
8013   MachineFunction &MF = DAG.getMachineFunction();
8014   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8015   // If there is a possibilty that flat instruction access scratch memory
8016   // then we need to use the same legalization rules we use for private.
8017   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8018       !Subtarget->hasMultiDwordFlatScratchAddressing())
8019     AS = MFI->hasFlatScratchInit() ?
8020          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8021 
8022   unsigned NumElements = MemVT.getVectorNumElements();
8023 
8024   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8025       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8026     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8027       if (MemVT.isPow2VectorType())
8028         return SDValue();
8029       if (NumElements == 3)
8030         return WidenVectorLoad(Op, DAG);
8031       return SplitVectorLoad(Op, DAG);
8032     }
8033     // Non-uniform loads will be selected to MUBUF instructions, so they
8034     // have the same legalization requirements as global and private
8035     // loads.
8036     //
8037   }
8038 
8039   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8040       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8041       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8042     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8043         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8044         Alignment >= 4 && NumElements < 32) {
8045       if (MemVT.isPow2VectorType())
8046         return SDValue();
8047       if (NumElements == 3)
8048         return WidenVectorLoad(Op, DAG);
8049       return SplitVectorLoad(Op, DAG);
8050     }
8051     // Non-uniform loads will be selected to MUBUF instructions, so they
8052     // have the same legalization requirements as global and private
8053     // loads.
8054     //
8055   }
8056   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8057       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8058       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8059       AS == AMDGPUAS::FLAT_ADDRESS) {
8060     if (NumElements > 4)
8061       return SplitVectorLoad(Op, DAG);
8062     // v3 loads not supported on SI.
8063     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8064       return WidenVectorLoad(Op, DAG);
8065     // v3 and v4 loads are supported for private and global memory.
8066     return SDValue();
8067   }
8068   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8069     // Depending on the setting of the private_element_size field in the
8070     // resource descriptor, we can only make private accesses up to a certain
8071     // size.
8072     switch (Subtarget->getMaxPrivateElementSize()) {
8073     case 4: {
8074       SDValue Ops[2];
8075       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8076       return DAG.getMergeValues(Ops, DL);
8077     }
8078     case 8:
8079       if (NumElements > 2)
8080         return SplitVectorLoad(Op, DAG);
8081       return SDValue();
8082     case 16:
8083       // Same as global/flat
8084       if (NumElements > 4)
8085         return SplitVectorLoad(Op, DAG);
8086       // v3 loads not supported on SI.
8087       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8088         return WidenVectorLoad(Op, DAG);
8089       return SDValue();
8090     default:
8091       llvm_unreachable("unsupported private_element_size");
8092     }
8093   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8094     // Use ds_read_b128 or ds_read_b96 when possible.
8095     if (Subtarget->hasDS96AndDS128() &&
8096         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8097          MemVT.getStoreSize() == 12) &&
8098         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8099                                            Load->getAlign()))
8100       return SDValue();
8101 
8102     if (NumElements > 2)
8103       return SplitVectorLoad(Op, DAG);
8104 
8105     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8106     // address is negative, then the instruction is incorrectly treated as
8107     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8108     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8109     // load later in the SILoadStoreOptimizer.
8110     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8111         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8112         Load->getAlignment() < 8) {
8113       return SplitVectorLoad(Op, DAG);
8114     }
8115   }
8116   return SDValue();
8117 }
8118 
8119 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8120   EVT VT = Op.getValueType();
8121   assert(VT.getSizeInBits() == 64);
8122 
8123   SDLoc DL(Op);
8124   SDValue Cond = Op.getOperand(0);
8125 
8126   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8127   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8128 
8129   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8130   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8131 
8132   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8133   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8134 
8135   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8136 
8137   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8138   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8139 
8140   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8141 
8142   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8143   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8144 }
8145 
8146 // Catch division cases where we can use shortcuts with rcp and rsq
8147 // instructions.
8148 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8149                                               SelectionDAG &DAG) const {
8150   SDLoc SL(Op);
8151   SDValue LHS = Op.getOperand(0);
8152   SDValue RHS = Op.getOperand(1);
8153   EVT VT = Op.getValueType();
8154   const SDNodeFlags Flags = Op->getFlags();
8155 
8156   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
8157                             Flags.hasApproximateFuncs();
8158 
8159   // Without !fpmath accuracy information, we can't do more because we don't
8160   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8161   if (!AllowInaccurateRcp)
8162     return SDValue();
8163 
8164   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8165     if (CLHS->isExactlyValue(1.0)) {
8166       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8167       // the CI documentation has a worst case error of 1 ulp.
8168       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8169       // use it as long as we aren't trying to use denormals.
8170       //
8171       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8172 
8173       // 1.0 / sqrt(x) -> rsq(x)
8174 
8175       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8176       // error seems really high at 2^29 ULP.
8177       if (RHS.getOpcode() == ISD::FSQRT)
8178         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8179 
8180       // 1.0 / x -> rcp(x)
8181       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8182     }
8183 
8184     // Same as for 1.0, but expand the sign out of the constant.
8185     if (CLHS->isExactlyValue(-1.0)) {
8186       // -1.0 / x -> rcp (fneg x)
8187       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8188       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8189     }
8190   }
8191 
8192   // Turn into multiply by the reciprocal.
8193   // x / y -> x * (1.0 / y)
8194   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8195   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8196 }
8197 
8198 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8199                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8200                           SDNodeFlags Flags) {
8201   if (GlueChain->getNumValues() <= 1) {
8202     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8203   }
8204 
8205   assert(GlueChain->getNumValues() == 3);
8206 
8207   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8208   switch (Opcode) {
8209   default: llvm_unreachable("no chain equivalent for opcode");
8210   case ISD::FMUL:
8211     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8212     break;
8213   }
8214 
8215   return DAG.getNode(Opcode, SL, VTList,
8216                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8217                      Flags);
8218 }
8219 
8220 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8221                            EVT VT, SDValue A, SDValue B, SDValue C,
8222                            SDValue GlueChain, SDNodeFlags Flags) {
8223   if (GlueChain->getNumValues() <= 1) {
8224     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8225   }
8226 
8227   assert(GlueChain->getNumValues() == 3);
8228 
8229   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8230   switch (Opcode) {
8231   default: llvm_unreachable("no chain equivalent for opcode");
8232   case ISD::FMA:
8233     Opcode = AMDGPUISD::FMA_W_CHAIN;
8234     break;
8235   }
8236 
8237   return DAG.getNode(Opcode, SL, VTList,
8238                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8239                      Flags);
8240 }
8241 
8242 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8243   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8244     return FastLowered;
8245 
8246   SDLoc SL(Op);
8247   SDValue Src0 = Op.getOperand(0);
8248   SDValue Src1 = Op.getOperand(1);
8249 
8250   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8251   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8252 
8253   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8254   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8255 
8256   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8257   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8258 
8259   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8260 }
8261 
8262 // Faster 2.5 ULP division that does not support denormals.
8263 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8264   SDLoc SL(Op);
8265   SDValue LHS = Op.getOperand(1);
8266   SDValue RHS = Op.getOperand(2);
8267 
8268   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8269 
8270   const APFloat K0Val(BitsToFloat(0x6f800000));
8271   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8272 
8273   const APFloat K1Val(BitsToFloat(0x2f800000));
8274   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8275 
8276   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8277 
8278   EVT SetCCVT =
8279     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8280 
8281   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8282 
8283   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8284 
8285   // TODO: Should this propagate fast-math-flags?
8286   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8287 
8288   // rcp does not support denormals.
8289   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8290 
8291   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8292 
8293   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8294 }
8295 
8296 // Returns immediate value for setting the F32 denorm mode when using the
8297 // S_DENORM_MODE instruction.
8298 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8299                                           const SDLoc &SL, const GCNSubtarget *ST) {
8300   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8301   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8302                                 ? FP_DENORM_FLUSH_NONE
8303                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8304 
8305   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8306   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8307 }
8308 
8309 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8310   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8311     return FastLowered;
8312 
8313   // The selection matcher assumes anything with a chain selecting to a
8314   // mayRaiseFPException machine instruction. Since we're introducing a chain
8315   // here, we need to explicitly report nofpexcept for the regular fdiv
8316   // lowering.
8317   SDNodeFlags Flags = Op->getFlags();
8318   Flags.setNoFPExcept(true);
8319 
8320   SDLoc SL(Op);
8321   SDValue LHS = Op.getOperand(0);
8322   SDValue RHS = Op.getOperand(1);
8323 
8324   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8325 
8326   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8327 
8328   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8329                                           {RHS, RHS, LHS}, Flags);
8330   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8331                                         {LHS, RHS, LHS}, Flags);
8332 
8333   // Denominator is scaled to not be denormal, so using rcp is ok.
8334   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8335                                   DenominatorScaled, Flags);
8336   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8337                                      DenominatorScaled, Flags);
8338 
8339   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8340                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8341                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8342   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8343 
8344   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8345 
8346   if (!HasFP32Denormals) {
8347     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8348     // lowering. The chain dependence is insufficient, and we need glue. We do
8349     // not need the glue variants in a strictfp function.
8350 
8351     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8352 
8353     SDNode *EnableDenorm;
8354     if (Subtarget->hasDenormModeInst()) {
8355       const SDValue EnableDenormValue =
8356           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8357 
8358       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8359                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8360     } else {
8361       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8362                                                         SL, MVT::i32);
8363       EnableDenorm =
8364           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8365                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8366     }
8367 
8368     SDValue Ops[3] = {
8369       NegDivScale0,
8370       SDValue(EnableDenorm, 0),
8371       SDValue(EnableDenorm, 1)
8372     };
8373 
8374     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8375   }
8376 
8377   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8378                              ApproxRcp, One, NegDivScale0, Flags);
8379 
8380   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8381                              ApproxRcp, Fma0, Flags);
8382 
8383   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8384                            Fma1, Fma1, Flags);
8385 
8386   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8387                              NumeratorScaled, Mul, Flags);
8388 
8389   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8390                              Fma2, Fma1, Mul, Fma2, Flags);
8391 
8392   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8393                              NumeratorScaled, Fma3, Flags);
8394 
8395   if (!HasFP32Denormals) {
8396     SDNode *DisableDenorm;
8397     if (Subtarget->hasDenormModeInst()) {
8398       const SDValue DisableDenormValue =
8399           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8400 
8401       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8402                                   Fma4.getValue(1), DisableDenormValue,
8403                                   Fma4.getValue(2)).getNode();
8404     } else {
8405       const SDValue DisableDenormValue =
8406           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8407 
8408       DisableDenorm = DAG.getMachineNode(
8409           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8410           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8411     }
8412 
8413     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8414                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8415     DAG.setRoot(OutputChain);
8416   }
8417 
8418   SDValue Scale = NumeratorScaled.getValue(1);
8419   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8420                              {Fma4, Fma1, Fma3, Scale}, Flags);
8421 
8422   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8423 }
8424 
8425 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8426   if (DAG.getTarget().Options.UnsafeFPMath)
8427     return lowerFastUnsafeFDIV(Op, DAG);
8428 
8429   SDLoc SL(Op);
8430   SDValue X = Op.getOperand(0);
8431   SDValue Y = Op.getOperand(1);
8432 
8433   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8434 
8435   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8436 
8437   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8438 
8439   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8440 
8441   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8442 
8443   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8444 
8445   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8446 
8447   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8448 
8449   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8450 
8451   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8452   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8453 
8454   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8455                              NegDivScale0, Mul, DivScale1);
8456 
8457   SDValue Scale;
8458 
8459   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8460     // Workaround a hardware bug on SI where the condition output from div_scale
8461     // is not usable.
8462 
8463     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8464 
8465     // Figure out if the scale to use for div_fmas.
8466     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8467     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8468     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8469     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8470 
8471     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8472     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8473 
8474     SDValue Scale0Hi
8475       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8476     SDValue Scale1Hi
8477       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8478 
8479     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8480     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8481     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8482   } else {
8483     Scale = DivScale1.getValue(1);
8484   }
8485 
8486   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8487                              Fma4, Fma3, Mul, Scale);
8488 
8489   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8490 }
8491 
8492 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8493   EVT VT = Op.getValueType();
8494 
8495   if (VT == MVT::f32)
8496     return LowerFDIV32(Op, DAG);
8497 
8498   if (VT == MVT::f64)
8499     return LowerFDIV64(Op, DAG);
8500 
8501   if (VT == MVT::f16)
8502     return LowerFDIV16(Op, DAG);
8503 
8504   llvm_unreachable("Unexpected type for fdiv");
8505 }
8506 
8507 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8508   SDLoc DL(Op);
8509   StoreSDNode *Store = cast<StoreSDNode>(Op);
8510   EVT VT = Store->getMemoryVT();
8511 
8512   if (VT == MVT::i1) {
8513     return DAG.getTruncStore(Store->getChain(), DL,
8514        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8515        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8516   }
8517 
8518   assert(VT.isVector() &&
8519          Store->getValue().getValueType().getScalarType() == MVT::i32);
8520 
8521   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8522                                       VT, *Store->getMemOperand())) {
8523     return expandUnalignedStore(Store, DAG);
8524   }
8525 
8526   unsigned AS = Store->getAddressSpace();
8527   if (Subtarget->hasLDSMisalignedBug() &&
8528       AS == AMDGPUAS::FLAT_ADDRESS &&
8529       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8530     return SplitVectorStore(Op, DAG);
8531   }
8532 
8533   MachineFunction &MF = DAG.getMachineFunction();
8534   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8535   // If there is a possibilty that flat instruction access scratch memory
8536   // then we need to use the same legalization rules we use for private.
8537   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8538       !Subtarget->hasMultiDwordFlatScratchAddressing())
8539     AS = MFI->hasFlatScratchInit() ?
8540          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8541 
8542   unsigned NumElements = VT.getVectorNumElements();
8543   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8544       AS == AMDGPUAS::FLAT_ADDRESS) {
8545     if (NumElements > 4)
8546       return SplitVectorStore(Op, DAG);
8547     // v3 stores not supported on SI.
8548     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8549       return SplitVectorStore(Op, DAG);
8550     return SDValue();
8551   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8552     switch (Subtarget->getMaxPrivateElementSize()) {
8553     case 4:
8554       return scalarizeVectorStore(Store, DAG);
8555     case 8:
8556       if (NumElements > 2)
8557         return SplitVectorStore(Op, DAG);
8558       return SDValue();
8559     case 16:
8560       if (NumElements > 4 || NumElements == 3)
8561         return SplitVectorStore(Op, DAG);
8562       return SDValue();
8563     default:
8564       llvm_unreachable("unsupported private_element_size");
8565     }
8566   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8567     // Use ds_write_b128 or ds_write_b96 when possible.
8568     if (Subtarget->hasDS96AndDS128() &&
8569         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8570          (VT.getStoreSize() == 12)) &&
8571         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8572                                            Store->getAlign()))
8573       return SDValue();
8574 
8575     if (NumElements > 2)
8576       return SplitVectorStore(Op, DAG);
8577 
8578     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8579     // address is negative, then the instruction is incorrectly treated as
8580     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8581     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8582     // store later in the SILoadStoreOptimizer.
8583     if (!Subtarget->hasUsableDSOffset() &&
8584         NumElements == 2 && VT.getStoreSize() == 8 &&
8585         Store->getAlignment() < 8) {
8586       return SplitVectorStore(Op, DAG);
8587     }
8588 
8589     return SDValue();
8590   } else {
8591     llvm_unreachable("unhandled address space");
8592   }
8593 }
8594 
8595 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8596   SDLoc DL(Op);
8597   EVT VT = Op.getValueType();
8598   SDValue Arg = Op.getOperand(0);
8599   SDValue TrigVal;
8600 
8601   // Propagate fast-math flags so that the multiply we introduce can be folded
8602   // if Arg is already the result of a multiply by constant.
8603   auto Flags = Op->getFlags();
8604 
8605   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8606 
8607   if (Subtarget->hasTrigReducedRange()) {
8608     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8609     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8610   } else {
8611     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8612   }
8613 
8614   switch (Op.getOpcode()) {
8615   case ISD::FCOS:
8616     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8617   case ISD::FSIN:
8618     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8619   default:
8620     llvm_unreachable("Wrong trig opcode");
8621   }
8622 }
8623 
8624 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8625   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8626   assert(AtomicNode->isCompareAndSwap());
8627   unsigned AS = AtomicNode->getAddressSpace();
8628 
8629   // No custom lowering required for local address space
8630   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8631     return Op;
8632 
8633   // Non-local address space requires custom lowering for atomic compare
8634   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8635   SDLoc DL(Op);
8636   SDValue ChainIn = Op.getOperand(0);
8637   SDValue Addr = Op.getOperand(1);
8638   SDValue Old = Op.getOperand(2);
8639   SDValue New = Op.getOperand(3);
8640   EVT VT = Op.getValueType();
8641   MVT SimpleVT = VT.getSimpleVT();
8642   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8643 
8644   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8645   SDValue Ops[] = { ChainIn, Addr, NewOld };
8646 
8647   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8648                                  Ops, VT, AtomicNode->getMemOperand());
8649 }
8650 
8651 //===----------------------------------------------------------------------===//
8652 // Custom DAG optimizations
8653 //===----------------------------------------------------------------------===//
8654 
8655 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8656                                                      DAGCombinerInfo &DCI) const {
8657   EVT VT = N->getValueType(0);
8658   EVT ScalarVT = VT.getScalarType();
8659   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8660     return SDValue();
8661 
8662   SelectionDAG &DAG = DCI.DAG;
8663   SDLoc DL(N);
8664 
8665   SDValue Src = N->getOperand(0);
8666   EVT SrcVT = Src.getValueType();
8667 
8668   // TODO: We could try to match extracting the higher bytes, which would be
8669   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8670   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8671   // about in practice.
8672   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8673     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8674       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8675       DCI.AddToWorklist(Cvt.getNode());
8676 
8677       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8678       if (ScalarVT != MVT::f32) {
8679         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8680                           DAG.getTargetConstant(0, DL, MVT::i32));
8681       }
8682       return Cvt;
8683     }
8684   }
8685 
8686   return SDValue();
8687 }
8688 
8689 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8690 
8691 // This is a variant of
8692 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8693 //
8694 // The normal DAG combiner will do this, but only if the add has one use since
8695 // that would increase the number of instructions.
8696 //
8697 // This prevents us from seeing a constant offset that can be folded into a
8698 // memory instruction's addressing mode. If we know the resulting add offset of
8699 // a pointer can be folded into an addressing offset, we can replace the pointer
8700 // operand with the add of new constant offset. This eliminates one of the uses,
8701 // and may allow the remaining use to also be simplified.
8702 //
8703 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8704                                                unsigned AddrSpace,
8705                                                EVT MemVT,
8706                                                DAGCombinerInfo &DCI) const {
8707   SDValue N0 = N->getOperand(0);
8708   SDValue N1 = N->getOperand(1);
8709 
8710   // We only do this to handle cases where it's profitable when there are
8711   // multiple uses of the add, so defer to the standard combine.
8712   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8713       N0->hasOneUse())
8714     return SDValue();
8715 
8716   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8717   if (!CN1)
8718     return SDValue();
8719 
8720   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8721   if (!CAdd)
8722     return SDValue();
8723 
8724   // If the resulting offset is too large, we can't fold it into the addressing
8725   // mode offset.
8726   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8727   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8728 
8729   AddrMode AM;
8730   AM.HasBaseReg = true;
8731   AM.BaseOffs = Offset.getSExtValue();
8732   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8733     return SDValue();
8734 
8735   SelectionDAG &DAG = DCI.DAG;
8736   SDLoc SL(N);
8737   EVT VT = N->getValueType(0);
8738 
8739   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8740   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8741 
8742   SDNodeFlags Flags;
8743   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8744                           (N0.getOpcode() == ISD::OR ||
8745                            N0->getFlags().hasNoUnsignedWrap()));
8746 
8747   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8748 }
8749 
8750 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8751 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8752 /// specific intrinsic, but they all place the pointer operand first.
8753 static unsigned getBasePtrIndex(const MemSDNode *N) {
8754   switch (N->getOpcode()) {
8755   case ISD::STORE:
8756   case ISD::INTRINSIC_W_CHAIN:
8757   case ISD::INTRINSIC_VOID:
8758     return 2;
8759   default:
8760     return 1;
8761   }
8762 }
8763 
8764 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8765                                                   DAGCombinerInfo &DCI) const {
8766   SelectionDAG &DAG = DCI.DAG;
8767   SDLoc SL(N);
8768 
8769   unsigned PtrIdx = getBasePtrIndex(N);
8770   SDValue Ptr = N->getOperand(PtrIdx);
8771 
8772   // TODO: We could also do this for multiplies.
8773   if (Ptr.getOpcode() == ISD::SHL) {
8774     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8775                                           N->getMemoryVT(), DCI);
8776     if (NewPtr) {
8777       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8778 
8779       NewOps[PtrIdx] = NewPtr;
8780       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8781     }
8782   }
8783 
8784   return SDValue();
8785 }
8786 
8787 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8788   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8789          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8790          (Opc == ISD::XOR && Val == 0);
8791 }
8792 
8793 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8794 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8795 // integer combine opportunities since most 64-bit operations are decomposed
8796 // this way.  TODO: We won't want this for SALU especially if it is an inline
8797 // immediate.
8798 SDValue SITargetLowering::splitBinaryBitConstantOp(
8799   DAGCombinerInfo &DCI,
8800   const SDLoc &SL,
8801   unsigned Opc, SDValue LHS,
8802   const ConstantSDNode *CRHS) const {
8803   uint64_t Val = CRHS->getZExtValue();
8804   uint32_t ValLo = Lo_32(Val);
8805   uint32_t ValHi = Hi_32(Val);
8806   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8807 
8808     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8809          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8810         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8811     // If we need to materialize a 64-bit immediate, it will be split up later
8812     // anyway. Avoid creating the harder to understand 64-bit immediate
8813     // materialization.
8814     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8815   }
8816 
8817   return SDValue();
8818 }
8819 
8820 // Returns true if argument is a boolean value which is not serialized into
8821 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8822 static bool isBoolSGPR(SDValue V) {
8823   if (V.getValueType() != MVT::i1)
8824     return false;
8825   switch (V.getOpcode()) {
8826   default: break;
8827   case ISD::SETCC:
8828   case ISD::AND:
8829   case ISD::OR:
8830   case ISD::XOR:
8831   case AMDGPUISD::FP_CLASS:
8832     return true;
8833   }
8834   return false;
8835 }
8836 
8837 // If a constant has all zeroes or all ones within each byte return it.
8838 // Otherwise return 0.
8839 static uint32_t getConstantPermuteMask(uint32_t C) {
8840   // 0xff for any zero byte in the mask
8841   uint32_t ZeroByteMask = 0;
8842   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8843   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8844   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8845   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8846   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8847   if ((NonZeroByteMask & C) != NonZeroByteMask)
8848     return 0; // Partial bytes selected.
8849   return C;
8850 }
8851 
8852 // Check if a node selects whole bytes from its operand 0 starting at a byte
8853 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8854 // or -1 if not succeeded.
8855 // Note byte select encoding:
8856 // value 0-3 selects corresponding source byte;
8857 // value 0xc selects zero;
8858 // value 0xff selects 0xff.
8859 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8860   assert(V.getValueSizeInBits() == 32);
8861 
8862   if (V.getNumOperands() != 2)
8863     return ~0;
8864 
8865   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8866   if (!N1)
8867     return ~0;
8868 
8869   uint32_t C = N1->getZExtValue();
8870 
8871   switch (V.getOpcode()) {
8872   default:
8873     break;
8874   case ISD::AND:
8875     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8876       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8877     }
8878     break;
8879 
8880   case ISD::OR:
8881     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8882       return (0x03020100 & ~ConstMask) | ConstMask;
8883     }
8884     break;
8885 
8886   case ISD::SHL:
8887     if (C % 8)
8888       return ~0;
8889 
8890     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8891 
8892   case ISD::SRL:
8893     if (C % 8)
8894       return ~0;
8895 
8896     return uint32_t(0x0c0c0c0c03020100ull >> C);
8897   }
8898 
8899   return ~0;
8900 }
8901 
8902 SDValue SITargetLowering::performAndCombine(SDNode *N,
8903                                             DAGCombinerInfo &DCI) const {
8904   if (DCI.isBeforeLegalize())
8905     return SDValue();
8906 
8907   SelectionDAG &DAG = DCI.DAG;
8908   EVT VT = N->getValueType(0);
8909   SDValue LHS = N->getOperand(0);
8910   SDValue RHS = N->getOperand(1);
8911 
8912 
8913   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8914   if (VT == MVT::i64 && CRHS) {
8915     if (SDValue Split
8916         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8917       return Split;
8918   }
8919 
8920   if (CRHS && VT == MVT::i32) {
8921     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8922     // nb = number of trailing zeroes in mask
8923     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8924     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8925     uint64_t Mask = CRHS->getZExtValue();
8926     unsigned Bits = countPopulation(Mask);
8927     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8928         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8929       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8930         unsigned Shift = CShift->getZExtValue();
8931         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8932         unsigned Offset = NB + Shift;
8933         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8934           SDLoc SL(N);
8935           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8936                                     LHS->getOperand(0),
8937                                     DAG.getConstant(Offset, SL, MVT::i32),
8938                                     DAG.getConstant(Bits, SL, MVT::i32));
8939           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8940           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8941                                     DAG.getValueType(NarrowVT));
8942           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8943                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8944           return Shl;
8945         }
8946       }
8947     }
8948 
8949     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8950     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8951         isa<ConstantSDNode>(LHS.getOperand(2))) {
8952       uint32_t Sel = getConstantPermuteMask(Mask);
8953       if (!Sel)
8954         return SDValue();
8955 
8956       // Select 0xc for all zero bytes
8957       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8958       SDLoc DL(N);
8959       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8960                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8961     }
8962   }
8963 
8964   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8965   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8966   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8967     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8968     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8969 
8970     SDValue X = LHS.getOperand(0);
8971     SDValue Y = RHS.getOperand(0);
8972     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8973       return SDValue();
8974 
8975     if (LCC == ISD::SETO) {
8976       if (X != LHS.getOperand(1))
8977         return SDValue();
8978 
8979       if (RCC == ISD::SETUNE) {
8980         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8981         if (!C1 || !C1->isInfinity() || C1->isNegative())
8982           return SDValue();
8983 
8984         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8985                               SIInstrFlags::N_SUBNORMAL |
8986                               SIInstrFlags::N_ZERO |
8987                               SIInstrFlags::P_ZERO |
8988                               SIInstrFlags::P_SUBNORMAL |
8989                               SIInstrFlags::P_NORMAL;
8990 
8991         static_assert(((~(SIInstrFlags::S_NAN |
8992                           SIInstrFlags::Q_NAN |
8993                           SIInstrFlags::N_INFINITY |
8994                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8995                       "mask not equal");
8996 
8997         SDLoc DL(N);
8998         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8999                            X, DAG.getConstant(Mask, DL, MVT::i32));
9000       }
9001     }
9002   }
9003 
9004   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9005     std::swap(LHS, RHS);
9006 
9007   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9008       RHS.hasOneUse()) {
9009     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9010     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9011     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9012     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9013     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9014         (RHS.getOperand(0) == LHS.getOperand(0) &&
9015          LHS.getOperand(0) == LHS.getOperand(1))) {
9016       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9017       unsigned NewMask = LCC == ISD::SETO ?
9018         Mask->getZExtValue() & ~OrdMask :
9019         Mask->getZExtValue() & OrdMask;
9020 
9021       SDLoc DL(N);
9022       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9023                          DAG.getConstant(NewMask, DL, MVT::i32));
9024     }
9025   }
9026 
9027   if (VT == MVT::i32 &&
9028       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9029     // and x, (sext cc from i1) => select cc, x, 0
9030     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9031       std::swap(LHS, RHS);
9032     if (isBoolSGPR(RHS.getOperand(0)))
9033       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9034                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9035   }
9036 
9037   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9038   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9039   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9040       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9041     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9042     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9043     if (LHSMask != ~0u && RHSMask != ~0u) {
9044       // Canonicalize the expression in an attempt to have fewer unique masks
9045       // and therefore fewer registers used to hold the masks.
9046       if (LHSMask > RHSMask) {
9047         std::swap(LHSMask, RHSMask);
9048         std::swap(LHS, RHS);
9049       }
9050 
9051       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9052       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9053       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9054       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9055 
9056       // Check of we need to combine values from two sources within a byte.
9057       if (!(LHSUsedLanes & RHSUsedLanes) &&
9058           // If we select high and lower word keep it for SDWA.
9059           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9060           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9061         // Each byte in each mask is either selector mask 0-3, or has higher
9062         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9063         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9064         // mask which is not 0xff wins. By anding both masks we have a correct
9065         // result except that 0x0c shall be corrected to give 0x0c only.
9066         uint32_t Mask = LHSMask & RHSMask;
9067         for (unsigned I = 0; I < 32; I += 8) {
9068           uint32_t ByteSel = 0xff << I;
9069           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9070             Mask &= (0x0c << I) & 0xffffffff;
9071         }
9072 
9073         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9074         // or 0x0c.
9075         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9076         SDLoc DL(N);
9077 
9078         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9079                            LHS.getOperand(0), RHS.getOperand(0),
9080                            DAG.getConstant(Sel, DL, MVT::i32));
9081       }
9082     }
9083   }
9084 
9085   return SDValue();
9086 }
9087 
9088 SDValue SITargetLowering::performOrCombine(SDNode *N,
9089                                            DAGCombinerInfo &DCI) const {
9090   SelectionDAG &DAG = DCI.DAG;
9091   SDValue LHS = N->getOperand(0);
9092   SDValue RHS = N->getOperand(1);
9093 
9094   EVT VT = N->getValueType(0);
9095   if (VT == MVT::i1) {
9096     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9097     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9098         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9099       SDValue Src = LHS.getOperand(0);
9100       if (Src != RHS.getOperand(0))
9101         return SDValue();
9102 
9103       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9104       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9105       if (!CLHS || !CRHS)
9106         return SDValue();
9107 
9108       // Only 10 bits are used.
9109       static const uint32_t MaxMask = 0x3ff;
9110 
9111       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9112       SDLoc DL(N);
9113       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9114                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9115     }
9116 
9117     return SDValue();
9118   }
9119 
9120   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9121   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9122       LHS.getOpcode() == AMDGPUISD::PERM &&
9123       isa<ConstantSDNode>(LHS.getOperand(2))) {
9124     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9125     if (!Sel)
9126       return SDValue();
9127 
9128     Sel |= LHS.getConstantOperandVal(2);
9129     SDLoc DL(N);
9130     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9131                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9132   }
9133 
9134   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9135   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9136   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9137       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9138     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9139     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9140     if (LHSMask != ~0u && RHSMask != ~0u) {
9141       // Canonicalize the expression in an attempt to have fewer unique masks
9142       // and therefore fewer registers used to hold the masks.
9143       if (LHSMask > RHSMask) {
9144         std::swap(LHSMask, RHSMask);
9145         std::swap(LHS, RHS);
9146       }
9147 
9148       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9149       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9150       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9151       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9152 
9153       // Check of we need to combine values from two sources within a byte.
9154       if (!(LHSUsedLanes & RHSUsedLanes) &&
9155           // If we select high and lower word keep it for SDWA.
9156           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9157           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9158         // Kill zero bytes selected by other mask. Zero value is 0xc.
9159         LHSMask &= ~RHSUsedLanes;
9160         RHSMask &= ~LHSUsedLanes;
9161         // Add 4 to each active LHS lane
9162         LHSMask |= LHSUsedLanes & 0x04040404;
9163         // Combine masks
9164         uint32_t Sel = LHSMask | RHSMask;
9165         SDLoc DL(N);
9166 
9167         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9168                            LHS.getOperand(0), RHS.getOperand(0),
9169                            DAG.getConstant(Sel, DL, MVT::i32));
9170       }
9171     }
9172   }
9173 
9174   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9175     return SDValue();
9176 
9177   // TODO: This could be a generic combine with a predicate for extracting the
9178   // high half of an integer being free.
9179 
9180   // (or i64:x, (zero_extend i32:y)) ->
9181   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9182   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9183       RHS.getOpcode() != ISD::ZERO_EXTEND)
9184     std::swap(LHS, RHS);
9185 
9186   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9187     SDValue ExtSrc = RHS.getOperand(0);
9188     EVT SrcVT = ExtSrc.getValueType();
9189     if (SrcVT == MVT::i32) {
9190       SDLoc SL(N);
9191       SDValue LowLHS, HiBits;
9192       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9193       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9194 
9195       DCI.AddToWorklist(LowOr.getNode());
9196       DCI.AddToWorklist(HiBits.getNode());
9197 
9198       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9199                                 LowOr, HiBits);
9200       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9201     }
9202   }
9203 
9204   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9205   if (CRHS) {
9206     if (SDValue Split
9207           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9208       return Split;
9209   }
9210 
9211   return SDValue();
9212 }
9213 
9214 SDValue SITargetLowering::performXorCombine(SDNode *N,
9215                                             DAGCombinerInfo &DCI) const {
9216   EVT VT = N->getValueType(0);
9217   if (VT != MVT::i64)
9218     return SDValue();
9219 
9220   SDValue LHS = N->getOperand(0);
9221   SDValue RHS = N->getOperand(1);
9222 
9223   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9224   if (CRHS) {
9225     if (SDValue Split
9226           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9227       return Split;
9228   }
9229 
9230   return SDValue();
9231 }
9232 
9233 // Instructions that will be lowered with a final instruction that zeros the
9234 // high result bits.
9235 // XXX - probably only need to list legal operations.
9236 static bool fp16SrcZerosHighBits(unsigned Opc) {
9237   switch (Opc) {
9238   case ISD::FADD:
9239   case ISD::FSUB:
9240   case ISD::FMUL:
9241   case ISD::FDIV:
9242   case ISD::FREM:
9243   case ISD::FMA:
9244   case ISD::FMAD:
9245   case ISD::FCANONICALIZE:
9246   case ISD::FP_ROUND:
9247   case ISD::UINT_TO_FP:
9248   case ISD::SINT_TO_FP:
9249   case ISD::FABS:
9250     // Fabs is lowered to a bit operation, but it's an and which will clear the
9251     // high bits anyway.
9252   case ISD::FSQRT:
9253   case ISD::FSIN:
9254   case ISD::FCOS:
9255   case ISD::FPOWI:
9256   case ISD::FPOW:
9257   case ISD::FLOG:
9258   case ISD::FLOG2:
9259   case ISD::FLOG10:
9260   case ISD::FEXP:
9261   case ISD::FEXP2:
9262   case ISD::FCEIL:
9263   case ISD::FTRUNC:
9264   case ISD::FRINT:
9265   case ISD::FNEARBYINT:
9266   case ISD::FROUND:
9267   case ISD::FFLOOR:
9268   case ISD::FMINNUM:
9269   case ISD::FMAXNUM:
9270   case AMDGPUISD::FRACT:
9271   case AMDGPUISD::CLAMP:
9272   case AMDGPUISD::COS_HW:
9273   case AMDGPUISD::SIN_HW:
9274   case AMDGPUISD::FMIN3:
9275   case AMDGPUISD::FMAX3:
9276   case AMDGPUISD::FMED3:
9277   case AMDGPUISD::FMAD_FTZ:
9278   case AMDGPUISD::RCP:
9279   case AMDGPUISD::RSQ:
9280   case AMDGPUISD::RCP_IFLAG:
9281   case AMDGPUISD::LDEXP:
9282     return true;
9283   default:
9284     // fcopysign, select and others may be lowered to 32-bit bit operations
9285     // which don't zero the high bits.
9286     return false;
9287   }
9288 }
9289 
9290 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9291                                                    DAGCombinerInfo &DCI) const {
9292   if (!Subtarget->has16BitInsts() ||
9293       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9294     return SDValue();
9295 
9296   EVT VT = N->getValueType(0);
9297   if (VT != MVT::i32)
9298     return SDValue();
9299 
9300   SDValue Src = N->getOperand(0);
9301   if (Src.getValueType() != MVT::i16)
9302     return SDValue();
9303 
9304   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9305   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9306   if (Src.getOpcode() == ISD::BITCAST) {
9307     SDValue BCSrc = Src.getOperand(0);
9308     if (BCSrc.getValueType() == MVT::f16 &&
9309         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9310       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9311   }
9312 
9313   return SDValue();
9314 }
9315 
9316 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9317                                                         DAGCombinerInfo &DCI)
9318                                                         const {
9319   SDValue Src = N->getOperand(0);
9320   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9321 
9322   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9323       VTSign->getVT() == MVT::i8) ||
9324       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9325       VTSign->getVT() == MVT::i16)) &&
9326       Src.hasOneUse()) {
9327     auto *M = cast<MemSDNode>(Src);
9328     SDValue Ops[] = {
9329       Src.getOperand(0), // Chain
9330       Src.getOperand(1), // rsrc
9331       Src.getOperand(2), // vindex
9332       Src.getOperand(3), // voffset
9333       Src.getOperand(4), // soffset
9334       Src.getOperand(5), // offset
9335       Src.getOperand(6),
9336       Src.getOperand(7)
9337     };
9338     // replace with BUFFER_LOAD_BYTE/SHORT
9339     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9340                                          Src.getOperand(0).getValueType());
9341     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9342                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9343     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9344                                                           ResList,
9345                                                           Ops, M->getMemoryVT(),
9346                                                           M->getMemOperand());
9347     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9348                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9349   }
9350   return SDValue();
9351 }
9352 
9353 SDValue SITargetLowering::performClassCombine(SDNode *N,
9354                                               DAGCombinerInfo &DCI) const {
9355   SelectionDAG &DAG = DCI.DAG;
9356   SDValue Mask = N->getOperand(1);
9357 
9358   // fp_class x, 0 -> false
9359   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9360     if (CMask->isNullValue())
9361       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9362   }
9363 
9364   if (N->getOperand(0).isUndef())
9365     return DAG.getUNDEF(MVT::i1);
9366 
9367   return SDValue();
9368 }
9369 
9370 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9371                                             DAGCombinerInfo &DCI) const {
9372   EVT VT = N->getValueType(0);
9373   SDValue N0 = N->getOperand(0);
9374 
9375   if (N0.isUndef())
9376     return N0;
9377 
9378   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9379                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9380     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9381                            N->getFlags());
9382   }
9383 
9384   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9385     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9386                            N0.getOperand(0), N->getFlags());
9387   }
9388 
9389   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9390 }
9391 
9392 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9393                                        unsigned MaxDepth) const {
9394   unsigned Opcode = Op.getOpcode();
9395   if (Opcode == ISD::FCANONICALIZE)
9396     return true;
9397 
9398   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9399     auto F = CFP->getValueAPF();
9400     if (F.isNaN() && F.isSignaling())
9401       return false;
9402     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9403   }
9404 
9405   // If source is a result of another standard FP operation it is already in
9406   // canonical form.
9407   if (MaxDepth == 0)
9408     return false;
9409 
9410   switch (Opcode) {
9411   // These will flush denorms if required.
9412   case ISD::FADD:
9413   case ISD::FSUB:
9414   case ISD::FMUL:
9415   case ISD::FCEIL:
9416   case ISD::FFLOOR:
9417   case ISD::FMA:
9418   case ISD::FMAD:
9419   case ISD::FSQRT:
9420   case ISD::FDIV:
9421   case ISD::FREM:
9422   case ISD::FP_ROUND:
9423   case ISD::FP_EXTEND:
9424   case AMDGPUISD::FMUL_LEGACY:
9425   case AMDGPUISD::FMAD_FTZ:
9426   case AMDGPUISD::RCP:
9427   case AMDGPUISD::RSQ:
9428   case AMDGPUISD::RSQ_CLAMP:
9429   case AMDGPUISD::RCP_LEGACY:
9430   case AMDGPUISD::RCP_IFLAG:
9431   case AMDGPUISD::DIV_SCALE:
9432   case AMDGPUISD::DIV_FMAS:
9433   case AMDGPUISD::DIV_FIXUP:
9434   case AMDGPUISD::FRACT:
9435   case AMDGPUISD::LDEXP:
9436   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9437   case AMDGPUISD::CVT_F32_UBYTE0:
9438   case AMDGPUISD::CVT_F32_UBYTE1:
9439   case AMDGPUISD::CVT_F32_UBYTE2:
9440   case AMDGPUISD::CVT_F32_UBYTE3:
9441     return true;
9442 
9443   // It can/will be lowered or combined as a bit operation.
9444   // Need to check their input recursively to handle.
9445   case ISD::FNEG:
9446   case ISD::FABS:
9447   case ISD::FCOPYSIGN:
9448     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9449 
9450   case ISD::FSIN:
9451   case ISD::FCOS:
9452   case ISD::FSINCOS:
9453     return Op.getValueType().getScalarType() != MVT::f16;
9454 
9455   case ISD::FMINNUM:
9456   case ISD::FMAXNUM:
9457   case ISD::FMINNUM_IEEE:
9458   case ISD::FMAXNUM_IEEE:
9459   case AMDGPUISD::CLAMP:
9460   case AMDGPUISD::FMED3:
9461   case AMDGPUISD::FMAX3:
9462   case AMDGPUISD::FMIN3: {
9463     // FIXME: Shouldn't treat the generic operations different based these.
9464     // However, we aren't really required to flush the result from
9465     // minnum/maxnum..
9466 
9467     // snans will be quieted, so we only need to worry about denormals.
9468     if (Subtarget->supportsMinMaxDenormModes() ||
9469         denormalsEnabledForType(DAG, Op.getValueType()))
9470       return true;
9471 
9472     // Flushing may be required.
9473     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9474     // targets need to check their input recursively.
9475 
9476     // FIXME: Does this apply with clamp? It's implemented with max.
9477     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9478       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9479         return false;
9480     }
9481 
9482     return true;
9483   }
9484   case ISD::SELECT: {
9485     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9486            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9487   }
9488   case ISD::BUILD_VECTOR: {
9489     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9490       SDValue SrcOp = Op.getOperand(i);
9491       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9492         return false;
9493     }
9494 
9495     return true;
9496   }
9497   case ISD::EXTRACT_VECTOR_ELT:
9498   case ISD::EXTRACT_SUBVECTOR: {
9499     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9500   }
9501   case ISD::INSERT_VECTOR_ELT: {
9502     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9503            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9504   }
9505   case ISD::UNDEF:
9506     // Could be anything.
9507     return false;
9508 
9509   case ISD::BITCAST: {
9510     // Hack round the mess we make when legalizing extract_vector_elt
9511     SDValue Src = Op.getOperand(0);
9512     if (Src.getValueType() == MVT::i16 &&
9513         Src.getOpcode() == ISD::TRUNCATE) {
9514       SDValue TruncSrc = Src.getOperand(0);
9515       if (TruncSrc.getValueType() == MVT::i32 &&
9516           TruncSrc.getOpcode() == ISD::BITCAST &&
9517           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9518         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9519       }
9520     }
9521 
9522     return false;
9523   }
9524   case ISD::INTRINSIC_WO_CHAIN: {
9525     unsigned IntrinsicID
9526       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9527     // TODO: Handle more intrinsics
9528     switch (IntrinsicID) {
9529     case Intrinsic::amdgcn_cvt_pkrtz:
9530     case Intrinsic::amdgcn_cubeid:
9531     case Intrinsic::amdgcn_frexp_mant:
9532     case Intrinsic::amdgcn_fdot2:
9533     case Intrinsic::amdgcn_rcp:
9534     case Intrinsic::amdgcn_rsq:
9535     case Intrinsic::amdgcn_rsq_clamp:
9536     case Intrinsic::amdgcn_rcp_legacy:
9537     case Intrinsic::amdgcn_rsq_legacy:
9538     case Intrinsic::amdgcn_trig_preop:
9539       return true;
9540     default:
9541       break;
9542     }
9543 
9544     LLVM_FALLTHROUGH;
9545   }
9546   default:
9547     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9548            DAG.isKnownNeverSNaN(Op);
9549   }
9550 
9551   llvm_unreachable("invalid operation");
9552 }
9553 
9554 // Constant fold canonicalize.
9555 SDValue SITargetLowering::getCanonicalConstantFP(
9556   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9557   // Flush denormals to 0 if not enabled.
9558   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9559     return DAG.getConstantFP(0.0, SL, VT);
9560 
9561   if (C.isNaN()) {
9562     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9563     if (C.isSignaling()) {
9564       // Quiet a signaling NaN.
9565       // FIXME: Is this supposed to preserve payload bits?
9566       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9567     }
9568 
9569     // Make sure it is the canonical NaN bitpattern.
9570     //
9571     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9572     // immediate?
9573     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9574       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9575   }
9576 
9577   // Already canonical.
9578   return DAG.getConstantFP(C, SL, VT);
9579 }
9580 
9581 static bool vectorEltWillFoldAway(SDValue Op) {
9582   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9583 }
9584 
9585 SDValue SITargetLowering::performFCanonicalizeCombine(
9586   SDNode *N,
9587   DAGCombinerInfo &DCI) const {
9588   SelectionDAG &DAG = DCI.DAG;
9589   SDValue N0 = N->getOperand(0);
9590   EVT VT = N->getValueType(0);
9591 
9592   // fcanonicalize undef -> qnan
9593   if (N0.isUndef()) {
9594     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9595     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9596   }
9597 
9598   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9599     EVT VT = N->getValueType(0);
9600     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9601   }
9602 
9603   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9604   //                                                   (fcanonicalize k)
9605   //
9606   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9607 
9608   // TODO: This could be better with wider vectors that will be split to v2f16,
9609   // and to consider uses since there aren't that many packed operations.
9610   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9611       isTypeLegal(MVT::v2f16)) {
9612     SDLoc SL(N);
9613     SDValue NewElts[2];
9614     SDValue Lo = N0.getOperand(0);
9615     SDValue Hi = N0.getOperand(1);
9616     EVT EltVT = Lo.getValueType();
9617 
9618     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9619       for (unsigned I = 0; I != 2; ++I) {
9620         SDValue Op = N0.getOperand(I);
9621         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9622           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9623                                               CFP->getValueAPF());
9624         } else if (Op.isUndef()) {
9625           // Handled below based on what the other operand is.
9626           NewElts[I] = Op;
9627         } else {
9628           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9629         }
9630       }
9631 
9632       // If one half is undef, and one is constant, perfer a splat vector rather
9633       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9634       // cheaper to use and may be free with a packed operation.
9635       if (NewElts[0].isUndef()) {
9636         if (isa<ConstantFPSDNode>(NewElts[1]))
9637           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9638             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9639       }
9640 
9641       if (NewElts[1].isUndef()) {
9642         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9643           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9644       }
9645 
9646       return DAG.getBuildVector(VT, SL, NewElts);
9647     }
9648   }
9649 
9650   unsigned SrcOpc = N0.getOpcode();
9651 
9652   // If it's free to do so, push canonicalizes further up the source, which may
9653   // find a canonical source.
9654   //
9655   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9656   // sNaNs.
9657   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9658     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9659     if (CRHS && N0.hasOneUse()) {
9660       SDLoc SL(N);
9661       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9662                                    N0.getOperand(0));
9663       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9664       DCI.AddToWorklist(Canon0.getNode());
9665 
9666       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9667     }
9668   }
9669 
9670   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9671 }
9672 
9673 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9674   switch (Opc) {
9675   case ISD::FMAXNUM:
9676   case ISD::FMAXNUM_IEEE:
9677     return AMDGPUISD::FMAX3;
9678   case ISD::SMAX:
9679     return AMDGPUISD::SMAX3;
9680   case ISD::UMAX:
9681     return AMDGPUISD::UMAX3;
9682   case ISD::FMINNUM:
9683   case ISD::FMINNUM_IEEE:
9684     return AMDGPUISD::FMIN3;
9685   case ISD::SMIN:
9686     return AMDGPUISD::SMIN3;
9687   case ISD::UMIN:
9688     return AMDGPUISD::UMIN3;
9689   default:
9690     llvm_unreachable("Not a min/max opcode");
9691   }
9692 }
9693 
9694 SDValue SITargetLowering::performIntMed3ImmCombine(
9695   SelectionDAG &DAG, const SDLoc &SL,
9696   SDValue Op0, SDValue Op1, bool Signed) const {
9697   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9698   if (!K1)
9699     return SDValue();
9700 
9701   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9702   if (!K0)
9703     return SDValue();
9704 
9705   if (Signed) {
9706     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9707       return SDValue();
9708   } else {
9709     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9710       return SDValue();
9711   }
9712 
9713   EVT VT = K0->getValueType(0);
9714   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9715   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9716     return DAG.getNode(Med3Opc, SL, VT,
9717                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9718   }
9719 
9720   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9721   MVT NVT = MVT::i32;
9722   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9723 
9724   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9725   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9726   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9727 
9728   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9729   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9730 }
9731 
9732 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9733   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9734     return C;
9735 
9736   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9737     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9738       return C;
9739   }
9740 
9741   return nullptr;
9742 }
9743 
9744 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9745                                                   const SDLoc &SL,
9746                                                   SDValue Op0,
9747                                                   SDValue Op1) const {
9748   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9749   if (!K1)
9750     return SDValue();
9751 
9752   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9753   if (!K0)
9754     return SDValue();
9755 
9756   // Ordered >= (although NaN inputs should have folded away by now).
9757   if (K0->getValueAPF() > K1->getValueAPF())
9758     return SDValue();
9759 
9760   const MachineFunction &MF = DAG.getMachineFunction();
9761   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9762 
9763   // TODO: Check IEEE bit enabled?
9764   EVT VT = Op0.getValueType();
9765   if (Info->getMode().DX10Clamp) {
9766     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9767     // hardware fmed3 behavior converting to a min.
9768     // FIXME: Should this be allowing -0.0?
9769     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9770       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9771   }
9772 
9773   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9774   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9775     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9776     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9777     // then give the other result, which is different from med3 with a NaN
9778     // input.
9779     SDValue Var = Op0.getOperand(0);
9780     if (!DAG.isKnownNeverSNaN(Var))
9781       return SDValue();
9782 
9783     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9784 
9785     if ((!K0->hasOneUse() ||
9786          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9787         (!K1->hasOneUse() ||
9788          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9789       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9790                          Var, SDValue(K0, 0), SDValue(K1, 0));
9791     }
9792   }
9793 
9794   return SDValue();
9795 }
9796 
9797 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9798                                                DAGCombinerInfo &DCI) const {
9799   SelectionDAG &DAG = DCI.DAG;
9800 
9801   EVT VT = N->getValueType(0);
9802   unsigned Opc = N->getOpcode();
9803   SDValue Op0 = N->getOperand(0);
9804   SDValue Op1 = N->getOperand(1);
9805 
9806   // Only do this if the inner op has one use since this will just increases
9807   // register pressure for no benefit.
9808 
9809   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9810       !VT.isVector() &&
9811       (VT == MVT::i32 || VT == MVT::f32 ||
9812        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9813     // max(max(a, b), c) -> max3(a, b, c)
9814     // min(min(a, b), c) -> min3(a, b, c)
9815     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9816       SDLoc DL(N);
9817       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9818                          DL,
9819                          N->getValueType(0),
9820                          Op0.getOperand(0),
9821                          Op0.getOperand(1),
9822                          Op1);
9823     }
9824 
9825     // Try commuted.
9826     // max(a, max(b, c)) -> max3(a, b, c)
9827     // min(a, min(b, c)) -> min3(a, b, c)
9828     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9829       SDLoc DL(N);
9830       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9831                          DL,
9832                          N->getValueType(0),
9833                          Op0,
9834                          Op1.getOperand(0),
9835                          Op1.getOperand(1));
9836     }
9837   }
9838 
9839   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9840   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9841     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9842       return Med3;
9843   }
9844 
9845   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9846     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9847       return Med3;
9848   }
9849 
9850   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9851   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9852        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9853        (Opc == AMDGPUISD::FMIN_LEGACY &&
9854         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9855       (VT == MVT::f32 || VT == MVT::f64 ||
9856        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9857        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9858       Op0.hasOneUse()) {
9859     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9860       return Res;
9861   }
9862 
9863   return SDValue();
9864 }
9865 
9866 static bool isClampZeroToOne(SDValue A, SDValue B) {
9867   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9868     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9869       // FIXME: Should this be allowing -0.0?
9870       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9871              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9872     }
9873   }
9874 
9875   return false;
9876 }
9877 
9878 // FIXME: Should only worry about snans for version with chain.
9879 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9880                                               DAGCombinerInfo &DCI) const {
9881   EVT VT = N->getValueType(0);
9882   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9883   // NaNs. With a NaN input, the order of the operands may change the result.
9884 
9885   SelectionDAG &DAG = DCI.DAG;
9886   SDLoc SL(N);
9887 
9888   SDValue Src0 = N->getOperand(0);
9889   SDValue Src1 = N->getOperand(1);
9890   SDValue Src2 = N->getOperand(2);
9891 
9892   if (isClampZeroToOne(Src0, Src1)) {
9893     // const_a, const_b, x -> clamp is safe in all cases including signaling
9894     // nans.
9895     // FIXME: Should this be allowing -0.0?
9896     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9897   }
9898 
9899   const MachineFunction &MF = DAG.getMachineFunction();
9900   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9901 
9902   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9903   // handling no dx10-clamp?
9904   if (Info->getMode().DX10Clamp) {
9905     // If NaNs is clamped to 0, we are free to reorder the inputs.
9906 
9907     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9908       std::swap(Src0, Src1);
9909 
9910     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9911       std::swap(Src1, Src2);
9912 
9913     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9914       std::swap(Src0, Src1);
9915 
9916     if (isClampZeroToOne(Src1, Src2))
9917       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9918   }
9919 
9920   return SDValue();
9921 }
9922 
9923 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9924                                                  DAGCombinerInfo &DCI) const {
9925   SDValue Src0 = N->getOperand(0);
9926   SDValue Src1 = N->getOperand(1);
9927   if (Src0.isUndef() && Src1.isUndef())
9928     return DCI.DAG.getUNDEF(N->getValueType(0));
9929   return SDValue();
9930 }
9931 
9932 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9933 // expanded into a set of cmp/select instructions.
9934 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9935                                                 unsigned NumElem,
9936                                                 bool IsDivergentIdx) {
9937   if (UseDivergentRegisterIndexing)
9938     return false;
9939 
9940   unsigned VecSize = EltSize * NumElem;
9941 
9942   // Sub-dword vectors of size 2 dword or less have better implementation.
9943   if (VecSize <= 64 && EltSize < 32)
9944     return false;
9945 
9946   // Always expand the rest of sub-dword instructions, otherwise it will be
9947   // lowered via memory.
9948   if (EltSize < 32)
9949     return true;
9950 
9951   // Always do this if var-idx is divergent, otherwise it will become a loop.
9952   if (IsDivergentIdx)
9953     return true;
9954 
9955   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9956   unsigned NumInsts = NumElem /* Number of compares */ +
9957                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9958   return NumInsts <= 16;
9959 }
9960 
9961 static bool shouldExpandVectorDynExt(SDNode *N) {
9962   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9963   if (isa<ConstantSDNode>(Idx))
9964     return false;
9965 
9966   SDValue Vec = N->getOperand(0);
9967   EVT VecVT = Vec.getValueType();
9968   EVT EltVT = VecVT.getVectorElementType();
9969   unsigned EltSize = EltVT.getSizeInBits();
9970   unsigned NumElem = VecVT.getVectorNumElements();
9971 
9972   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9973                                                     Idx->isDivergent());
9974 }
9975 
9976 SDValue SITargetLowering::performExtractVectorEltCombine(
9977   SDNode *N, DAGCombinerInfo &DCI) const {
9978   SDValue Vec = N->getOperand(0);
9979   SelectionDAG &DAG = DCI.DAG;
9980 
9981   EVT VecVT = Vec.getValueType();
9982   EVT EltVT = VecVT.getVectorElementType();
9983 
9984   if ((Vec.getOpcode() == ISD::FNEG ||
9985        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9986     SDLoc SL(N);
9987     EVT EltVT = N->getValueType(0);
9988     SDValue Idx = N->getOperand(1);
9989     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9990                               Vec.getOperand(0), Idx);
9991     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9992   }
9993 
9994   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9995   //    =>
9996   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9997   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9998   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9999   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10000     SDLoc SL(N);
10001     EVT EltVT = N->getValueType(0);
10002     SDValue Idx = N->getOperand(1);
10003     unsigned Opc = Vec.getOpcode();
10004 
10005     switch(Opc) {
10006     default:
10007       break;
10008       // TODO: Support other binary operations.
10009     case ISD::FADD:
10010     case ISD::FSUB:
10011     case ISD::FMUL:
10012     case ISD::ADD:
10013     case ISD::UMIN:
10014     case ISD::UMAX:
10015     case ISD::SMIN:
10016     case ISD::SMAX:
10017     case ISD::FMAXNUM:
10018     case ISD::FMINNUM:
10019     case ISD::FMAXNUM_IEEE:
10020     case ISD::FMINNUM_IEEE: {
10021       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10022                                  Vec.getOperand(0), Idx);
10023       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10024                                  Vec.getOperand(1), Idx);
10025 
10026       DCI.AddToWorklist(Elt0.getNode());
10027       DCI.AddToWorklist(Elt1.getNode());
10028       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10029     }
10030     }
10031   }
10032 
10033   unsigned VecSize = VecVT.getSizeInBits();
10034   unsigned EltSize = EltVT.getSizeInBits();
10035 
10036   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10037   if (::shouldExpandVectorDynExt(N)) {
10038     SDLoc SL(N);
10039     SDValue Idx = N->getOperand(1);
10040     SDValue V;
10041     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10042       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10043       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10044       if (I == 0)
10045         V = Elt;
10046       else
10047         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10048     }
10049     return V;
10050   }
10051 
10052   if (!DCI.isBeforeLegalize())
10053     return SDValue();
10054 
10055   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10056   // elements. This exposes more load reduction opportunities by replacing
10057   // multiple small extract_vector_elements with a single 32-bit extract.
10058   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10059   if (isa<MemSDNode>(Vec) &&
10060       EltSize <= 16 &&
10061       EltVT.isByteSized() &&
10062       VecSize > 32 &&
10063       VecSize % 32 == 0 &&
10064       Idx) {
10065     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10066 
10067     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10068     unsigned EltIdx = BitIndex / 32;
10069     unsigned LeftoverBitIdx = BitIndex % 32;
10070     SDLoc SL(N);
10071 
10072     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10073     DCI.AddToWorklist(Cast.getNode());
10074 
10075     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10076                               DAG.getConstant(EltIdx, SL, MVT::i32));
10077     DCI.AddToWorklist(Elt.getNode());
10078     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10079                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10080     DCI.AddToWorklist(Srl.getNode());
10081 
10082     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10083     DCI.AddToWorklist(Trunc.getNode());
10084     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10085   }
10086 
10087   return SDValue();
10088 }
10089 
10090 SDValue
10091 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10092                                                 DAGCombinerInfo &DCI) const {
10093   SDValue Vec = N->getOperand(0);
10094   SDValue Idx = N->getOperand(2);
10095   EVT VecVT = Vec.getValueType();
10096   EVT EltVT = VecVT.getVectorElementType();
10097 
10098   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10099   // => BUILD_VECTOR n x select (e, const-idx)
10100   if (!::shouldExpandVectorDynExt(N))
10101     return SDValue();
10102 
10103   SelectionDAG &DAG = DCI.DAG;
10104   SDLoc SL(N);
10105   SDValue Ins = N->getOperand(1);
10106   EVT IdxVT = Idx.getValueType();
10107 
10108   SmallVector<SDValue, 16> Ops;
10109   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10110     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10111     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10112     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10113     Ops.push_back(V);
10114   }
10115 
10116   return DAG.getBuildVector(VecVT, SL, Ops);
10117 }
10118 
10119 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10120                                           const SDNode *N0,
10121                                           const SDNode *N1) const {
10122   EVT VT = N0->getValueType(0);
10123 
10124   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10125   // support denormals ever.
10126   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10127        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10128         getSubtarget()->hasMadF16())) &&
10129        isOperationLegal(ISD::FMAD, VT))
10130     return ISD::FMAD;
10131 
10132   const TargetOptions &Options = DAG.getTarget().Options;
10133   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10134        (N0->getFlags().hasAllowContract() &&
10135         N1->getFlags().hasAllowContract())) &&
10136       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10137     return ISD::FMA;
10138   }
10139 
10140   return 0;
10141 }
10142 
10143 // For a reassociatable opcode perform:
10144 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10145 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10146                                                SelectionDAG &DAG) const {
10147   EVT VT = N->getValueType(0);
10148   if (VT != MVT::i32 && VT != MVT::i64)
10149     return SDValue();
10150 
10151   unsigned Opc = N->getOpcode();
10152   SDValue Op0 = N->getOperand(0);
10153   SDValue Op1 = N->getOperand(1);
10154 
10155   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10156     return SDValue();
10157 
10158   if (Op0->isDivergent())
10159     std::swap(Op0, Op1);
10160 
10161   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10162     return SDValue();
10163 
10164   SDValue Op2 = Op1.getOperand(1);
10165   Op1 = Op1.getOperand(0);
10166   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10167     return SDValue();
10168 
10169   if (Op1->isDivergent())
10170     std::swap(Op1, Op2);
10171 
10172   // If either operand is constant this will conflict with
10173   // DAGCombiner::ReassociateOps().
10174   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10175       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10176     return SDValue();
10177 
10178   SDLoc SL(N);
10179   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10180   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10181 }
10182 
10183 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10184                            EVT VT,
10185                            SDValue N0, SDValue N1, SDValue N2,
10186                            bool Signed) {
10187   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10188   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10189   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10190   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10191 }
10192 
10193 SDValue SITargetLowering::performAddCombine(SDNode *N,
10194                                             DAGCombinerInfo &DCI) const {
10195   SelectionDAG &DAG = DCI.DAG;
10196   EVT VT = N->getValueType(0);
10197   SDLoc SL(N);
10198   SDValue LHS = N->getOperand(0);
10199   SDValue RHS = N->getOperand(1);
10200 
10201   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10202       && Subtarget->hasMad64_32() &&
10203       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10204       VT.getScalarSizeInBits() <= 64) {
10205     if (LHS.getOpcode() != ISD::MUL)
10206       std::swap(LHS, RHS);
10207 
10208     SDValue MulLHS = LHS.getOperand(0);
10209     SDValue MulRHS = LHS.getOperand(1);
10210     SDValue AddRHS = RHS;
10211 
10212     // TODO: Maybe restrict if SGPR inputs.
10213     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10214         numBitsUnsigned(MulRHS, DAG) <= 32) {
10215       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10216       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10217       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10218       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10219     }
10220 
10221     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10222       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10223       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10224       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10225       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10226     }
10227 
10228     return SDValue();
10229   }
10230 
10231   if (SDValue V = reassociateScalarOps(N, DAG)) {
10232     return V;
10233   }
10234 
10235   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10236     return SDValue();
10237 
10238   // add x, zext (setcc) => addcarry x, 0, setcc
10239   // add x, sext (setcc) => subcarry x, 0, setcc
10240   unsigned Opc = LHS.getOpcode();
10241   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10242       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10243     std::swap(RHS, LHS);
10244 
10245   Opc = RHS.getOpcode();
10246   switch (Opc) {
10247   default: break;
10248   case ISD::ZERO_EXTEND:
10249   case ISD::SIGN_EXTEND:
10250   case ISD::ANY_EXTEND: {
10251     auto Cond = RHS.getOperand(0);
10252     // If this won't be a real VOPC output, we would still need to insert an
10253     // extra instruction anyway.
10254     if (!isBoolSGPR(Cond))
10255       break;
10256     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10257     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10258     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10259     return DAG.getNode(Opc, SL, VTList, Args);
10260   }
10261   case ISD::ADDCARRY: {
10262     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10263     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10264     if (!C || C->getZExtValue() != 0) break;
10265     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10266     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10267   }
10268   }
10269   return SDValue();
10270 }
10271 
10272 SDValue SITargetLowering::performSubCombine(SDNode *N,
10273                                             DAGCombinerInfo &DCI) const {
10274   SelectionDAG &DAG = DCI.DAG;
10275   EVT VT = N->getValueType(0);
10276 
10277   if (VT != MVT::i32)
10278     return SDValue();
10279 
10280   SDLoc SL(N);
10281   SDValue LHS = N->getOperand(0);
10282   SDValue RHS = N->getOperand(1);
10283 
10284   // sub x, zext (setcc) => subcarry x, 0, setcc
10285   // sub x, sext (setcc) => addcarry x, 0, setcc
10286   unsigned Opc = RHS.getOpcode();
10287   switch (Opc) {
10288   default: break;
10289   case ISD::ZERO_EXTEND:
10290   case ISD::SIGN_EXTEND:
10291   case ISD::ANY_EXTEND: {
10292     auto Cond = RHS.getOperand(0);
10293     // If this won't be a real VOPC output, we would still need to insert an
10294     // extra instruction anyway.
10295     if (!isBoolSGPR(Cond))
10296       break;
10297     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10298     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10299     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10300     return DAG.getNode(Opc, SL, VTList, Args);
10301   }
10302   }
10303 
10304   if (LHS.getOpcode() == ISD::SUBCARRY) {
10305     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10306     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10307     if (!C || !C->isNullValue())
10308       return SDValue();
10309     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10310     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10311   }
10312   return SDValue();
10313 }
10314 
10315 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10316   DAGCombinerInfo &DCI) const {
10317 
10318   if (N->getValueType(0) != MVT::i32)
10319     return SDValue();
10320 
10321   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10322   if (!C || C->getZExtValue() != 0)
10323     return SDValue();
10324 
10325   SelectionDAG &DAG = DCI.DAG;
10326   SDValue LHS = N->getOperand(0);
10327 
10328   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10329   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10330   unsigned LHSOpc = LHS.getOpcode();
10331   unsigned Opc = N->getOpcode();
10332   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10333       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10334     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10335     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10336   }
10337   return SDValue();
10338 }
10339 
10340 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10341                                              DAGCombinerInfo &DCI) const {
10342   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10343     return SDValue();
10344 
10345   SelectionDAG &DAG = DCI.DAG;
10346   EVT VT = N->getValueType(0);
10347 
10348   SDLoc SL(N);
10349   SDValue LHS = N->getOperand(0);
10350   SDValue RHS = N->getOperand(1);
10351 
10352   // These should really be instruction patterns, but writing patterns with
10353   // source modiifiers is a pain.
10354 
10355   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10356   if (LHS.getOpcode() == ISD::FADD) {
10357     SDValue A = LHS.getOperand(0);
10358     if (A == LHS.getOperand(1)) {
10359       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10360       if (FusedOp != 0) {
10361         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10362         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10363       }
10364     }
10365   }
10366 
10367   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10368   if (RHS.getOpcode() == ISD::FADD) {
10369     SDValue A = RHS.getOperand(0);
10370     if (A == RHS.getOperand(1)) {
10371       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10372       if (FusedOp != 0) {
10373         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10374         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10375       }
10376     }
10377   }
10378 
10379   return SDValue();
10380 }
10381 
10382 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10383                                              DAGCombinerInfo &DCI) const {
10384   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10385     return SDValue();
10386 
10387   SelectionDAG &DAG = DCI.DAG;
10388   SDLoc SL(N);
10389   EVT VT = N->getValueType(0);
10390   assert(!VT.isVector());
10391 
10392   // Try to get the fneg to fold into the source modifier. This undoes generic
10393   // DAG combines and folds them into the mad.
10394   //
10395   // Only do this if we are not trying to support denormals. v_mad_f32 does
10396   // not support denormals ever.
10397   SDValue LHS = N->getOperand(0);
10398   SDValue RHS = N->getOperand(1);
10399   if (LHS.getOpcode() == ISD::FADD) {
10400     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10401     SDValue A = LHS.getOperand(0);
10402     if (A == LHS.getOperand(1)) {
10403       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10404       if (FusedOp != 0){
10405         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10406         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10407 
10408         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10409       }
10410     }
10411   }
10412 
10413   if (RHS.getOpcode() == ISD::FADD) {
10414     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10415 
10416     SDValue A = RHS.getOperand(0);
10417     if (A == RHS.getOperand(1)) {
10418       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10419       if (FusedOp != 0){
10420         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10421         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10422       }
10423     }
10424   }
10425 
10426   return SDValue();
10427 }
10428 
10429 SDValue SITargetLowering::performFMACombine(SDNode *N,
10430                                             DAGCombinerInfo &DCI) const {
10431   SelectionDAG &DAG = DCI.DAG;
10432   EVT VT = N->getValueType(0);
10433   SDLoc SL(N);
10434 
10435   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10436     return SDValue();
10437 
10438   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10439   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10440   SDValue Op1 = N->getOperand(0);
10441   SDValue Op2 = N->getOperand(1);
10442   SDValue FMA = N->getOperand(2);
10443 
10444   if (FMA.getOpcode() != ISD::FMA ||
10445       Op1.getOpcode() != ISD::FP_EXTEND ||
10446       Op2.getOpcode() != ISD::FP_EXTEND)
10447     return SDValue();
10448 
10449   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10450   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10451   // is sufficient to allow generaing fdot2.
10452   const TargetOptions &Options = DAG.getTarget().Options;
10453   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10454       (N->getFlags().hasAllowContract() &&
10455        FMA->getFlags().hasAllowContract())) {
10456     Op1 = Op1.getOperand(0);
10457     Op2 = Op2.getOperand(0);
10458     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10459         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10460       return SDValue();
10461 
10462     SDValue Vec1 = Op1.getOperand(0);
10463     SDValue Idx1 = Op1.getOperand(1);
10464     SDValue Vec2 = Op2.getOperand(0);
10465 
10466     SDValue FMAOp1 = FMA.getOperand(0);
10467     SDValue FMAOp2 = FMA.getOperand(1);
10468     SDValue FMAAcc = FMA.getOperand(2);
10469 
10470     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10471         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10472       return SDValue();
10473 
10474     FMAOp1 = FMAOp1.getOperand(0);
10475     FMAOp2 = FMAOp2.getOperand(0);
10476     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10477         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10478       return SDValue();
10479 
10480     SDValue Vec3 = FMAOp1.getOperand(0);
10481     SDValue Vec4 = FMAOp2.getOperand(0);
10482     SDValue Idx2 = FMAOp1.getOperand(1);
10483 
10484     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10485         // Idx1 and Idx2 cannot be the same.
10486         Idx1 == Idx2)
10487       return SDValue();
10488 
10489     if (Vec1 == Vec2 || Vec3 == Vec4)
10490       return SDValue();
10491 
10492     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10493       return SDValue();
10494 
10495     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10496         (Vec1 == Vec4 && Vec2 == Vec3)) {
10497       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10498                          DAG.getTargetConstant(0, SL, MVT::i1));
10499     }
10500   }
10501   return SDValue();
10502 }
10503 
10504 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10505                                               DAGCombinerInfo &DCI) const {
10506   SelectionDAG &DAG = DCI.DAG;
10507   SDLoc SL(N);
10508 
10509   SDValue LHS = N->getOperand(0);
10510   SDValue RHS = N->getOperand(1);
10511   EVT VT = LHS.getValueType();
10512   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10513 
10514   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10515   if (!CRHS) {
10516     CRHS = dyn_cast<ConstantSDNode>(LHS);
10517     if (CRHS) {
10518       std::swap(LHS, RHS);
10519       CC = getSetCCSwappedOperands(CC);
10520     }
10521   }
10522 
10523   if (CRHS) {
10524     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10525         isBoolSGPR(LHS.getOperand(0))) {
10526       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10527       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10528       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10529       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10530       if ((CRHS->isAllOnesValue() &&
10531            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10532           (CRHS->isNullValue() &&
10533            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10534         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10535                            DAG.getConstant(-1, SL, MVT::i1));
10536       if ((CRHS->isAllOnesValue() &&
10537            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10538           (CRHS->isNullValue() &&
10539            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10540         return LHS.getOperand(0);
10541     }
10542 
10543     uint64_t CRHSVal = CRHS->getZExtValue();
10544     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10545         LHS.getOpcode() == ISD::SELECT &&
10546         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10547         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10548         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10549         isBoolSGPR(LHS.getOperand(0))) {
10550       // Given CT != FT:
10551       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10552       // setcc (select cc, CT, CF), CF, ne => cc
10553       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10554       // setcc (select cc, CT, CF), CT, eq => cc
10555       uint64_t CT = LHS.getConstantOperandVal(1);
10556       uint64_t CF = LHS.getConstantOperandVal(2);
10557 
10558       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10559           (CT == CRHSVal && CC == ISD::SETNE))
10560         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10561                            DAG.getConstant(-1, SL, MVT::i1));
10562       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10563           (CT == CRHSVal && CC == ISD::SETEQ))
10564         return LHS.getOperand(0);
10565     }
10566   }
10567 
10568   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10569                                            VT != MVT::f16))
10570     return SDValue();
10571 
10572   // Match isinf/isfinite pattern
10573   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10574   // (fcmp one (fabs x), inf) -> (fp_class x,
10575   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10576   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10577     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10578     if (!CRHS)
10579       return SDValue();
10580 
10581     const APFloat &APF = CRHS->getValueAPF();
10582     if (APF.isInfinity() && !APF.isNegative()) {
10583       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10584                                  SIInstrFlags::N_INFINITY;
10585       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10586                                     SIInstrFlags::P_ZERO |
10587                                     SIInstrFlags::N_NORMAL |
10588                                     SIInstrFlags::P_NORMAL |
10589                                     SIInstrFlags::N_SUBNORMAL |
10590                                     SIInstrFlags::P_SUBNORMAL;
10591       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10592       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10593                          DAG.getConstant(Mask, SL, MVT::i32));
10594     }
10595   }
10596 
10597   return SDValue();
10598 }
10599 
10600 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10601                                                      DAGCombinerInfo &DCI) const {
10602   SelectionDAG &DAG = DCI.DAG;
10603   SDLoc SL(N);
10604   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10605 
10606   SDValue Src = N->getOperand(0);
10607   SDValue Shift = N->getOperand(0);
10608 
10609   // TODO: Extend type shouldn't matter (assuming legal types).
10610   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10611     Shift = Shift.getOperand(0);
10612 
10613   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10614     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10615     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10616     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10617     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10618     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10619     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10620       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10621                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10622 
10623       unsigned ShiftOffset = 8 * Offset;
10624       if (Shift.getOpcode() == ISD::SHL)
10625         ShiftOffset -= C->getZExtValue();
10626       else
10627         ShiftOffset += C->getZExtValue();
10628 
10629       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10630         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10631                            MVT::f32, Shift);
10632       }
10633     }
10634   }
10635 
10636   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10637   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10638   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10639     // We simplified Src. If this node is not dead, visit it again so it is
10640     // folded properly.
10641     if (N->getOpcode() != ISD::DELETED_NODE)
10642       DCI.AddToWorklist(N);
10643     return SDValue(N, 0);
10644   }
10645 
10646   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10647   if (SDValue DemandedSrc =
10648           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10649     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10650 
10651   return SDValue();
10652 }
10653 
10654 SDValue SITargetLowering::performClampCombine(SDNode *N,
10655                                               DAGCombinerInfo &DCI) const {
10656   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10657   if (!CSrc)
10658     return SDValue();
10659 
10660   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10661   const APFloat &F = CSrc->getValueAPF();
10662   APFloat Zero = APFloat::getZero(F.getSemantics());
10663   if (F < Zero ||
10664       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10665     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10666   }
10667 
10668   APFloat One(F.getSemantics(), "1.0");
10669   if (F > One)
10670     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10671 
10672   return SDValue(CSrc, 0);
10673 }
10674 
10675 
10676 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10677                                             DAGCombinerInfo &DCI) const {
10678   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10679     return SDValue();
10680   switch (N->getOpcode()) {
10681   case ISD::ADD:
10682     return performAddCombine(N, DCI);
10683   case ISD::SUB:
10684     return performSubCombine(N, DCI);
10685   case ISD::ADDCARRY:
10686   case ISD::SUBCARRY:
10687     return performAddCarrySubCarryCombine(N, DCI);
10688   case ISD::FADD:
10689     return performFAddCombine(N, DCI);
10690   case ISD::FSUB:
10691     return performFSubCombine(N, DCI);
10692   case ISD::SETCC:
10693     return performSetCCCombine(N, DCI);
10694   case ISD::FMAXNUM:
10695   case ISD::FMINNUM:
10696   case ISD::FMAXNUM_IEEE:
10697   case ISD::FMINNUM_IEEE:
10698   case ISD::SMAX:
10699   case ISD::SMIN:
10700   case ISD::UMAX:
10701   case ISD::UMIN:
10702   case AMDGPUISD::FMIN_LEGACY:
10703   case AMDGPUISD::FMAX_LEGACY:
10704     return performMinMaxCombine(N, DCI);
10705   case ISD::FMA:
10706     return performFMACombine(N, DCI);
10707   case ISD::AND:
10708     return performAndCombine(N, DCI);
10709   case ISD::OR:
10710     return performOrCombine(N, DCI);
10711   case ISD::XOR:
10712     return performXorCombine(N, DCI);
10713   case ISD::ZERO_EXTEND:
10714     return performZeroExtendCombine(N, DCI);
10715   case ISD::SIGN_EXTEND_INREG:
10716     return performSignExtendInRegCombine(N , DCI);
10717   case AMDGPUISD::FP_CLASS:
10718     return performClassCombine(N, DCI);
10719   case ISD::FCANONICALIZE:
10720     return performFCanonicalizeCombine(N, DCI);
10721   case AMDGPUISD::RCP:
10722     return performRcpCombine(N, DCI);
10723   case AMDGPUISD::FRACT:
10724   case AMDGPUISD::RSQ:
10725   case AMDGPUISD::RCP_LEGACY:
10726   case AMDGPUISD::RCP_IFLAG:
10727   case AMDGPUISD::RSQ_CLAMP:
10728   case AMDGPUISD::LDEXP: {
10729     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10730     SDValue Src = N->getOperand(0);
10731     if (Src.isUndef())
10732       return Src;
10733     break;
10734   }
10735   case ISD::SINT_TO_FP:
10736   case ISD::UINT_TO_FP:
10737     return performUCharToFloatCombine(N, DCI);
10738   case AMDGPUISD::CVT_F32_UBYTE0:
10739   case AMDGPUISD::CVT_F32_UBYTE1:
10740   case AMDGPUISD::CVT_F32_UBYTE2:
10741   case AMDGPUISD::CVT_F32_UBYTE3:
10742     return performCvtF32UByteNCombine(N, DCI);
10743   case AMDGPUISD::FMED3:
10744     return performFMed3Combine(N, DCI);
10745   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10746     return performCvtPkRTZCombine(N, DCI);
10747   case AMDGPUISD::CLAMP:
10748     return performClampCombine(N, DCI);
10749   case ISD::SCALAR_TO_VECTOR: {
10750     SelectionDAG &DAG = DCI.DAG;
10751     EVT VT = N->getValueType(0);
10752 
10753     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10754     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10755       SDLoc SL(N);
10756       SDValue Src = N->getOperand(0);
10757       EVT EltVT = Src.getValueType();
10758       if (EltVT == MVT::f16)
10759         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10760 
10761       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10762       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10763     }
10764 
10765     break;
10766   }
10767   case ISD::EXTRACT_VECTOR_ELT:
10768     return performExtractVectorEltCombine(N, DCI);
10769   case ISD::INSERT_VECTOR_ELT:
10770     return performInsertVectorEltCombine(N, DCI);
10771   case ISD::LOAD: {
10772     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10773       return Widended;
10774     LLVM_FALLTHROUGH;
10775   }
10776   default: {
10777     if (!DCI.isBeforeLegalize()) {
10778       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10779         return performMemSDNodeCombine(MemNode, DCI);
10780     }
10781 
10782     break;
10783   }
10784   }
10785 
10786   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10787 }
10788 
10789 /// Helper function for adjustWritemask
10790 static unsigned SubIdx2Lane(unsigned Idx) {
10791   switch (Idx) {
10792   default: return 0;
10793   case AMDGPU::sub0: return 0;
10794   case AMDGPU::sub1: return 1;
10795   case AMDGPU::sub2: return 2;
10796   case AMDGPU::sub3: return 3;
10797   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10798   }
10799 }
10800 
10801 /// Adjust the writemask of MIMG instructions
10802 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10803                                           SelectionDAG &DAG) const {
10804   unsigned Opcode = Node->getMachineOpcode();
10805 
10806   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10807   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10808   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10809     return Node; // not implemented for D16
10810 
10811   SDNode *Users[5] = { nullptr };
10812   unsigned Lane = 0;
10813   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10814   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10815   unsigned NewDmask = 0;
10816   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10817   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10818   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10819                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10820   unsigned TFCLane = 0;
10821   bool HasChain = Node->getNumValues() > 1;
10822 
10823   if (OldDmask == 0) {
10824     // These are folded out, but on the chance it happens don't assert.
10825     return Node;
10826   }
10827 
10828   unsigned OldBitsSet = countPopulation(OldDmask);
10829   // Work out which is the TFE/LWE lane if that is enabled.
10830   if (UsesTFC) {
10831     TFCLane = OldBitsSet;
10832   }
10833 
10834   // Try to figure out the used register components
10835   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10836        I != E; ++I) {
10837 
10838     // Don't look at users of the chain.
10839     if (I.getUse().getResNo() != 0)
10840       continue;
10841 
10842     // Abort if we can't understand the usage
10843     if (!I->isMachineOpcode() ||
10844         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10845       return Node;
10846 
10847     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10848     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10849     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10850     // set, etc.
10851     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10852 
10853     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10854     if (UsesTFC && Lane == TFCLane) {
10855       Users[Lane] = *I;
10856     } else {
10857       // Set which texture component corresponds to the lane.
10858       unsigned Comp;
10859       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10860         Comp = countTrailingZeros(Dmask);
10861         Dmask &= ~(1 << Comp);
10862       }
10863 
10864       // Abort if we have more than one user per component.
10865       if (Users[Lane])
10866         return Node;
10867 
10868       Users[Lane] = *I;
10869       NewDmask |= 1 << Comp;
10870     }
10871   }
10872 
10873   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10874   bool NoChannels = !NewDmask;
10875   if (NoChannels) {
10876     if (!UsesTFC) {
10877       // No uses of the result and not using TFC. Then do nothing.
10878       return Node;
10879     }
10880     // If the original dmask has one channel - then nothing to do
10881     if (OldBitsSet == 1)
10882       return Node;
10883     // Use an arbitrary dmask - required for the instruction to work
10884     NewDmask = 1;
10885   }
10886   // Abort if there's no change
10887   if (NewDmask == OldDmask)
10888     return Node;
10889 
10890   unsigned BitsSet = countPopulation(NewDmask);
10891 
10892   // Check for TFE or LWE - increase the number of channels by one to account
10893   // for the extra return value
10894   // This will need adjustment for D16 if this is also included in
10895   // adjustWriteMask (this function) but at present D16 are excluded.
10896   unsigned NewChannels = BitsSet + UsesTFC;
10897 
10898   int NewOpcode =
10899       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10900   assert(NewOpcode != -1 &&
10901          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10902          "failed to find equivalent MIMG op");
10903 
10904   // Adjust the writemask in the node
10905   SmallVector<SDValue, 12> Ops;
10906   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10907   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10908   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10909 
10910   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10911 
10912   MVT ResultVT = NewChannels == 1 ?
10913     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10914                            NewChannels == 5 ? 8 : NewChannels);
10915   SDVTList NewVTList = HasChain ?
10916     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10917 
10918 
10919   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10920                                               NewVTList, Ops);
10921 
10922   if (HasChain) {
10923     // Update chain.
10924     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10925     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10926   }
10927 
10928   if (NewChannels == 1) {
10929     assert(Node->hasNUsesOfValue(1, 0));
10930     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10931                                       SDLoc(Node), Users[Lane]->getValueType(0),
10932                                       SDValue(NewNode, 0));
10933     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10934     return nullptr;
10935   }
10936 
10937   // Update the users of the node with the new indices
10938   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10939     SDNode *User = Users[i];
10940     if (!User) {
10941       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10942       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10943       if (i || !NoChannels)
10944         continue;
10945     } else {
10946       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10947       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10948     }
10949 
10950     switch (Idx) {
10951     default: break;
10952     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10953     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10954     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10955     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10956     }
10957   }
10958 
10959   DAG.RemoveDeadNode(Node);
10960   return nullptr;
10961 }
10962 
10963 static bool isFrameIndexOp(SDValue Op) {
10964   if (Op.getOpcode() == ISD::AssertZext)
10965     Op = Op.getOperand(0);
10966 
10967   return isa<FrameIndexSDNode>(Op);
10968 }
10969 
10970 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10971 /// with frame index operands.
10972 /// LLVM assumes that inputs are to these instructions are registers.
10973 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10974                                                         SelectionDAG &DAG) const {
10975   if (Node->getOpcode() == ISD::CopyToReg) {
10976     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10977     SDValue SrcVal = Node->getOperand(2);
10978 
10979     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10980     // to try understanding copies to physical registers.
10981     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
10982       SDLoc SL(Node);
10983       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10984       SDValue VReg = DAG.getRegister(
10985         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10986 
10987       SDNode *Glued = Node->getGluedNode();
10988       SDValue ToVReg
10989         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10990                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10991       SDValue ToResultReg
10992         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10993                            VReg, ToVReg.getValue(1));
10994       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10995       DAG.RemoveDeadNode(Node);
10996       return ToResultReg.getNode();
10997     }
10998   }
10999 
11000   SmallVector<SDValue, 8> Ops;
11001   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11002     if (!isFrameIndexOp(Node->getOperand(i))) {
11003       Ops.push_back(Node->getOperand(i));
11004       continue;
11005     }
11006 
11007     SDLoc DL(Node);
11008     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11009                                      Node->getOperand(i).getValueType(),
11010                                      Node->getOperand(i)), 0));
11011   }
11012 
11013   return DAG.UpdateNodeOperands(Node, Ops);
11014 }
11015 
11016 /// Fold the instructions after selecting them.
11017 /// Returns null if users were already updated.
11018 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11019                                           SelectionDAG &DAG) const {
11020   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11021   unsigned Opcode = Node->getMachineOpcode();
11022 
11023   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11024       !TII->isGather4(Opcode) &&
11025       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11026     return adjustWritemask(Node, DAG);
11027   }
11028 
11029   if (Opcode == AMDGPU::INSERT_SUBREG ||
11030       Opcode == AMDGPU::REG_SEQUENCE) {
11031     legalizeTargetIndependentNode(Node, DAG);
11032     return Node;
11033   }
11034 
11035   switch (Opcode) {
11036   case AMDGPU::V_DIV_SCALE_F32:
11037   case AMDGPU::V_DIV_SCALE_F64: {
11038     // Satisfy the operand register constraint when one of the inputs is
11039     // undefined. Ordinarily each undef value will have its own implicit_def of
11040     // a vreg, so force these to use a single register.
11041     SDValue Src0 = Node->getOperand(0);
11042     SDValue Src1 = Node->getOperand(1);
11043     SDValue Src2 = Node->getOperand(2);
11044 
11045     if ((Src0.isMachineOpcode() &&
11046          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11047         (Src0 == Src1 || Src0 == Src2))
11048       break;
11049 
11050     MVT VT = Src0.getValueType().getSimpleVT();
11051     const TargetRegisterClass *RC =
11052         getRegClassFor(VT, Src0.getNode()->isDivergent());
11053 
11054     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11055     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11056 
11057     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11058                                       UndefReg, Src0, SDValue());
11059 
11060     // src0 must be the same register as src1 or src2, even if the value is
11061     // undefined, so make sure we don't violate this constraint.
11062     if (Src0.isMachineOpcode() &&
11063         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11064       if (Src1.isMachineOpcode() &&
11065           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11066         Src0 = Src1;
11067       else if (Src2.isMachineOpcode() &&
11068                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11069         Src0 = Src2;
11070       else {
11071         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11072         Src0 = UndefReg;
11073         Src1 = UndefReg;
11074       }
11075     } else
11076       break;
11077 
11078     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
11079     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
11080       Ops.push_back(Node->getOperand(I));
11081 
11082     Ops.push_back(ImpDef.getValue(1));
11083     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11084   }
11085   default:
11086     break;
11087   }
11088 
11089   return Node;
11090 }
11091 
11092 /// Assign the register class depending on the number of
11093 /// bits set in the writemask
11094 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11095                                                      SDNode *Node) const {
11096   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11097 
11098   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11099 
11100   if (TII->isVOP3(MI.getOpcode())) {
11101     // Make sure constant bus requirements are respected.
11102     TII->legalizeOperandsVOP3(MRI, MI);
11103 
11104     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11105     // This saves a chain-copy of registers and better ballance register
11106     // use between vgpr and agpr as agpr tuples tend to be big.
11107     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11108       unsigned Opc = MI.getOpcode();
11109       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11110       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11111                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11112         if (I == -1)
11113           break;
11114         MachineOperand &Op = MI.getOperand(I);
11115         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11116              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11117             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11118           continue;
11119         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11120         if (!Src || !Src->isCopy() ||
11121             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11122           continue;
11123         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11124         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11125         // All uses of agpr64 and agpr32 can also accept vgpr except for
11126         // v_accvgpr_read, but we do not produce agpr reads during selection,
11127         // so no use checks are needed.
11128         MRI.setRegClass(Op.getReg(), NewRC);
11129       }
11130     }
11131 
11132     return;
11133   }
11134 
11135   // Replace unused atomics with the no return version.
11136   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11137   if (NoRetAtomicOp != -1) {
11138     if (!Node->hasAnyUseOfValue(0)) {
11139       MI.setDesc(TII->get(NoRetAtomicOp));
11140       MI.RemoveOperand(0);
11141       return;
11142     }
11143 
11144     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11145     // instruction, because the return type of these instructions is a vec2 of
11146     // the memory type, so it can be tied to the input operand.
11147     // This means these instructions always have a use, so we need to add a
11148     // special case to check if the atomic has only one extract_subreg use,
11149     // which itself has no uses.
11150     if ((Node->hasNUsesOfValue(1, 0) &&
11151          Node->use_begin()->isMachineOpcode() &&
11152          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11153          !Node->use_begin()->hasAnyUseOfValue(0))) {
11154       Register Def = MI.getOperand(0).getReg();
11155 
11156       // Change this into a noret atomic.
11157       MI.setDesc(TII->get(NoRetAtomicOp));
11158       MI.RemoveOperand(0);
11159 
11160       // If we only remove the def operand from the atomic instruction, the
11161       // extract_subreg will be left with a use of a vreg without a def.
11162       // So we need to insert an implicit_def to avoid machine verifier
11163       // errors.
11164       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11165               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11166     }
11167     return;
11168   }
11169 }
11170 
11171 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11172                               uint64_t Val) {
11173   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11174   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11175 }
11176 
11177 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11178                                                 const SDLoc &DL,
11179                                                 SDValue Ptr) const {
11180   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11181 
11182   // Build the half of the subregister with the constants before building the
11183   // full 128-bit register. If we are building multiple resource descriptors,
11184   // this will allow CSEing of the 2-component register.
11185   const SDValue Ops0[] = {
11186     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11187     buildSMovImm32(DAG, DL, 0),
11188     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11189     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11190     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11191   };
11192 
11193   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11194                                                 MVT::v2i32, Ops0), 0);
11195 
11196   // Combine the constants and the pointer.
11197   const SDValue Ops1[] = {
11198     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11199     Ptr,
11200     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11201     SubRegHi,
11202     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11203   };
11204 
11205   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11206 }
11207 
11208 /// Return a resource descriptor with the 'Add TID' bit enabled
11209 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11210 ///        of the resource descriptor) to create an offset, which is added to
11211 ///        the resource pointer.
11212 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11213                                            SDValue Ptr, uint32_t RsrcDword1,
11214                                            uint64_t RsrcDword2And3) const {
11215   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11216   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11217   if (RsrcDword1) {
11218     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11219                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11220                     0);
11221   }
11222 
11223   SDValue DataLo = buildSMovImm32(DAG, DL,
11224                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11225   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11226 
11227   const SDValue Ops[] = {
11228     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11229     PtrLo,
11230     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11231     PtrHi,
11232     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11233     DataLo,
11234     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11235     DataHi,
11236     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11237   };
11238 
11239   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11240 }
11241 
11242 //===----------------------------------------------------------------------===//
11243 //                         SI Inline Assembly Support
11244 //===----------------------------------------------------------------------===//
11245 
11246 std::pair<unsigned, const TargetRegisterClass *>
11247 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11248                                                StringRef Constraint,
11249                                                MVT VT) const {
11250   const TargetRegisterClass *RC = nullptr;
11251   if (Constraint.size() == 1) {
11252     const unsigned BitWidth = VT.getSizeInBits();
11253     switch (Constraint[0]) {
11254     default:
11255       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11256     case 's':
11257     case 'r':
11258       switch (BitWidth) {
11259       case 16:
11260         RC = &AMDGPU::SReg_32RegClass;
11261         break;
11262       case 64:
11263         RC = &AMDGPU::SGPR_64RegClass;
11264         break;
11265       default:
11266         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11267         if (!RC)
11268           return std::make_pair(0U, nullptr);
11269         break;
11270       }
11271       break;
11272     case 'v':
11273       switch (BitWidth) {
11274       case 16:
11275         RC = &AMDGPU::VGPR_32RegClass;
11276         break;
11277       default:
11278         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11279         if (!RC)
11280           return std::make_pair(0U, nullptr);
11281         break;
11282       }
11283       break;
11284     case 'a':
11285       if (!Subtarget->hasMAIInsts())
11286         break;
11287       switch (BitWidth) {
11288       case 16:
11289         RC = &AMDGPU::AGPR_32RegClass;
11290         break;
11291       default:
11292         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11293         if (!RC)
11294           return std::make_pair(0U, nullptr);
11295         break;
11296       }
11297       break;
11298     }
11299     // We actually support i128, i16 and f16 as inline parameters
11300     // even if they are not reported as legal
11301     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11302                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11303       return std::make_pair(0U, RC);
11304   }
11305 
11306   if (Constraint.size() > 1) {
11307     if (Constraint[1] == 'v') {
11308       RC = &AMDGPU::VGPR_32RegClass;
11309     } else if (Constraint[1] == 's') {
11310       RC = &AMDGPU::SGPR_32RegClass;
11311     } else if (Constraint[1] == 'a') {
11312       RC = &AMDGPU::AGPR_32RegClass;
11313     }
11314 
11315     if (RC) {
11316       uint32_t Idx;
11317       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11318       if (!Failed && Idx < RC->getNumRegs())
11319         return std::make_pair(RC->getRegister(Idx), RC);
11320     }
11321   }
11322 
11323   // FIXME: Returns VS_32 for physical SGPR constraints
11324   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11325 }
11326 
11327 static bool isImmConstraint(StringRef Constraint) {
11328   if (Constraint.size() == 1) {
11329     switch (Constraint[0]) {
11330     default: break;
11331     case 'I':
11332     case 'J':
11333     case 'A':
11334     case 'B':
11335     case 'C':
11336       return true;
11337     }
11338   } else if (Constraint == "DA" ||
11339              Constraint == "DB") {
11340     return true;
11341   }
11342   return false;
11343 }
11344 
11345 SITargetLowering::ConstraintType
11346 SITargetLowering::getConstraintType(StringRef Constraint) const {
11347   if (Constraint.size() == 1) {
11348     switch (Constraint[0]) {
11349     default: break;
11350     case 's':
11351     case 'v':
11352     case 'a':
11353       return C_RegisterClass;
11354     }
11355   }
11356   if (isImmConstraint(Constraint)) {
11357     return C_Other;
11358   }
11359   return TargetLowering::getConstraintType(Constraint);
11360 }
11361 
11362 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11363   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11364     Val = Val & maskTrailingOnes<uint64_t>(Size);
11365   }
11366   return Val;
11367 }
11368 
11369 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11370                                                     std::string &Constraint,
11371                                                     std::vector<SDValue> &Ops,
11372                                                     SelectionDAG &DAG) const {
11373   if (isImmConstraint(Constraint)) {
11374     uint64_t Val;
11375     if (getAsmOperandConstVal(Op, Val) &&
11376         checkAsmConstraintVal(Op, Constraint, Val)) {
11377       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11378       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11379     }
11380   } else {
11381     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11382   }
11383 }
11384 
11385 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11386   unsigned Size = Op.getScalarValueSizeInBits();
11387   if (Size > 64)
11388     return false;
11389 
11390   if (Size == 16 && !Subtarget->has16BitInsts())
11391     return false;
11392 
11393   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11394     Val = C->getSExtValue();
11395     return true;
11396   }
11397   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11398     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11399     return true;
11400   }
11401   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11402     if (Size != 16 || Op.getNumOperands() != 2)
11403       return false;
11404     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11405       return false;
11406     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11407       Val = C->getSExtValue();
11408       return true;
11409     }
11410     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11411       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11412       return true;
11413     }
11414   }
11415 
11416   return false;
11417 }
11418 
11419 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11420                                              const std::string &Constraint,
11421                                              uint64_t Val) const {
11422   if (Constraint.size() == 1) {
11423     switch (Constraint[0]) {
11424     case 'I':
11425       return AMDGPU::isInlinableIntLiteral(Val);
11426     case 'J':
11427       return isInt<16>(Val);
11428     case 'A':
11429       return checkAsmConstraintValA(Op, Val);
11430     case 'B':
11431       return isInt<32>(Val);
11432     case 'C':
11433       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11434              AMDGPU::isInlinableIntLiteral(Val);
11435     default:
11436       break;
11437     }
11438   } else if (Constraint.size() == 2) {
11439     if (Constraint == "DA") {
11440       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11441       int64_t LoBits = static_cast<int32_t>(Val);
11442       return checkAsmConstraintValA(Op, HiBits, 32) &&
11443              checkAsmConstraintValA(Op, LoBits, 32);
11444     }
11445     if (Constraint == "DB") {
11446       return true;
11447     }
11448   }
11449   llvm_unreachable("Invalid asm constraint");
11450 }
11451 
11452 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11453                                               uint64_t Val,
11454                                               unsigned MaxSize) const {
11455   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11456   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11457   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11458       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11459       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11460     return true;
11461   }
11462   return false;
11463 }
11464 
11465 // Figure out which registers should be reserved for stack access. Only after
11466 // the function is legalized do we know all of the non-spill stack objects or if
11467 // calls are present.
11468 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11469   MachineRegisterInfo &MRI = MF.getRegInfo();
11470   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11471   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11472   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11473 
11474   if (Info->isEntryFunction()) {
11475     // Callable functions have fixed registers used for stack access.
11476     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11477   }
11478 
11479   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11480                              Info->getStackPtrOffsetReg()));
11481   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11482     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11483 
11484   // We need to worry about replacing the default register with itself in case
11485   // of MIR testcases missing the MFI.
11486   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11487     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11488 
11489   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11490     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11491 
11492   Info->limitOccupancy(MF);
11493 
11494   if (ST.isWave32() && !MF.empty()) {
11495     // Add VCC_HI def because many instructions marked as imp-use VCC where
11496     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11497     // having a use of undef.
11498 
11499     const SIInstrInfo *TII = ST.getInstrInfo();
11500     DebugLoc DL;
11501 
11502     MachineBasicBlock &MBB = MF.front();
11503     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11504     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11505 
11506     for (auto &MBB : MF) {
11507       for (auto &MI : MBB) {
11508         TII->fixImplicitOperands(MI);
11509       }
11510     }
11511   }
11512 
11513   TargetLoweringBase::finalizeLowering(MF);
11514 
11515   // Allocate a VGPR for future SGPR Spill if
11516   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11517   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11518   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11519       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11520     Info->reserveVGPRforSGPRSpills(MF);
11521 }
11522 
11523 void SITargetLowering::computeKnownBitsForFrameIndex(
11524   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11525   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11526 
11527   // Set the high bits to zero based on the maximum allowed scratch size per
11528   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11529   // calculation won't overflow, so assume the sign bit is never set.
11530   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11531 }
11532 
11533 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11534                                    KnownBits &Known, unsigned Dim) {
11535   unsigned MaxValue =
11536       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11537   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11538 }
11539 
11540 void SITargetLowering::computeKnownBitsForTargetInstr(
11541     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11542     const MachineRegisterInfo &MRI, unsigned Depth) const {
11543   const MachineInstr *MI = MRI.getVRegDef(R);
11544   switch (MI->getOpcode()) {
11545   case AMDGPU::G_INTRINSIC: {
11546     switch (MI->getIntrinsicID()) {
11547     case Intrinsic::amdgcn_workitem_id_x:
11548       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11549       break;
11550     case Intrinsic::amdgcn_workitem_id_y:
11551       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11552       break;
11553     case Intrinsic::amdgcn_workitem_id_z:
11554       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11555       break;
11556     case Intrinsic::amdgcn_mbcnt_lo:
11557     case Intrinsic::amdgcn_mbcnt_hi: {
11558       // These return at most the wavefront size - 1.
11559       unsigned Size = MRI.getType(R).getSizeInBits();
11560       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11561       break;
11562     }
11563     case Intrinsic::amdgcn_groupstaticsize: {
11564       // We can report everything over the maximum size as 0. We can't report
11565       // based on the actual size because we don't know if it's accurate or not
11566       // at any given point.
11567       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11568       break;
11569     }
11570     default:
11571       break;
11572     }
11573   }
11574   }
11575 }
11576 
11577 Align SITargetLowering::computeKnownAlignForTargetInstr(
11578   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11579   unsigned Depth) const {
11580   const MachineInstr *MI = MRI.getVRegDef(R);
11581   switch (MI->getOpcode()) {
11582   case AMDGPU::G_INTRINSIC:
11583   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11584     // FIXME: Can this move to generic code? What about the case where the call
11585     // site specifies a lower alignment?
11586     Intrinsic::ID IID = MI->getIntrinsicID();
11587     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11588     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11589     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11590       return *RetAlign;
11591     return Align(1);
11592   }
11593   default:
11594     return Align(1);
11595   }
11596 }
11597 
11598 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11599   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11600   const Align CacheLineAlign = Align(64);
11601 
11602   // Pre-GFX10 target did not benefit from loop alignment
11603   if (!ML || DisableLoopAlignment ||
11604       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11605       getSubtarget()->hasInstFwdPrefetchBug())
11606     return PrefAlign;
11607 
11608   // On GFX10 I$ is 4 x 64 bytes cache lines.
11609   // By default prefetcher keeps one cache line behind and reads two ahead.
11610   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11611   // behind and one ahead.
11612   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11613   // If loop fits 64 bytes it always spans no more than two cache lines and
11614   // does not need an alignment.
11615   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11616   // Else if loop is less or equal 192 bytes we need two lines behind.
11617 
11618   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11619   const MachineBasicBlock *Header = ML->getHeader();
11620   if (Header->getAlignment() != PrefAlign)
11621     return Header->getAlignment(); // Already processed.
11622 
11623   unsigned LoopSize = 0;
11624   for (const MachineBasicBlock *MBB : ML->blocks()) {
11625     // If inner loop block is aligned assume in average half of the alignment
11626     // size to be added as nops.
11627     if (MBB != Header)
11628       LoopSize += MBB->getAlignment().value() / 2;
11629 
11630     for (const MachineInstr &MI : *MBB) {
11631       LoopSize += TII->getInstSizeInBytes(MI);
11632       if (LoopSize > 192)
11633         return PrefAlign;
11634     }
11635   }
11636 
11637   if (LoopSize <= 64)
11638     return PrefAlign;
11639 
11640   if (LoopSize <= 128)
11641     return CacheLineAlign;
11642 
11643   // If any of parent loops is surrounded by prefetch instructions do not
11644   // insert new for inner loop, which would reset parent's settings.
11645   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11646     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11647       auto I = Exit->getFirstNonDebugInstr();
11648       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11649         return CacheLineAlign;
11650     }
11651   }
11652 
11653   MachineBasicBlock *Pre = ML->getLoopPreheader();
11654   MachineBasicBlock *Exit = ML->getExitBlock();
11655 
11656   if (Pre && Exit) {
11657     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11658             TII->get(AMDGPU::S_INST_PREFETCH))
11659       .addImm(1); // prefetch 2 lines behind PC
11660 
11661     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11662             TII->get(AMDGPU::S_INST_PREFETCH))
11663       .addImm(2); // prefetch 1 line behind PC
11664   }
11665 
11666   return CacheLineAlign;
11667 }
11668 
11669 LLVM_ATTRIBUTE_UNUSED
11670 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11671   assert(N->getOpcode() == ISD::CopyFromReg);
11672   do {
11673     // Follow the chain until we find an INLINEASM node.
11674     N = N->getOperand(0).getNode();
11675     if (N->getOpcode() == ISD::INLINEASM ||
11676         N->getOpcode() == ISD::INLINEASM_BR)
11677       return true;
11678   } while (N->getOpcode() == ISD::CopyFromReg);
11679   return false;
11680 }
11681 
11682 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11683   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11684 {
11685   switch (N->getOpcode()) {
11686     case ISD::CopyFromReg:
11687     {
11688       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11689       const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11690       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11691       Register Reg = R->getReg();
11692 
11693       // FIXME: Why does this need to consider isLiveIn?
11694       if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11695         return !TRI->isSGPRReg(MRI, Reg);
11696 
11697       if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11698         return KDA->isDivergent(V);
11699 
11700       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11701       return !TRI->isSGPRReg(MRI, Reg);
11702     }
11703     break;
11704     case ISD::LOAD: {
11705       const LoadSDNode *L = cast<LoadSDNode>(N);
11706       unsigned AS = L->getAddressSpace();
11707       // A flat load may access private memory.
11708       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11709     } break;
11710     case ISD::CALLSEQ_END:
11711     return true;
11712     break;
11713     case ISD::INTRINSIC_WO_CHAIN:
11714     {
11715 
11716     }
11717       return AMDGPU::isIntrinsicSourceOfDivergence(
11718       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11719     case ISD::INTRINSIC_W_CHAIN:
11720       return AMDGPU::isIntrinsicSourceOfDivergence(
11721       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11722   }
11723   return false;
11724 }
11725 
11726 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11727                                                EVT VT) const {
11728   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11729   case MVT::f32:
11730     return hasFP32Denormals(DAG.getMachineFunction());
11731   case MVT::f64:
11732   case MVT::f16:
11733     return hasFP64FP16Denormals(DAG.getMachineFunction());
11734   default:
11735     return false;
11736   }
11737 }
11738 
11739 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11740                                                     const SelectionDAG &DAG,
11741                                                     bool SNaN,
11742                                                     unsigned Depth) const {
11743   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11744     const MachineFunction &MF = DAG.getMachineFunction();
11745     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11746 
11747     if (Info->getMode().DX10Clamp)
11748       return true; // Clamped to 0.
11749     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11750   }
11751 
11752   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11753                                                             SNaN, Depth);
11754 }
11755 
11756 TargetLowering::AtomicExpansionKind
11757 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11758   switch (RMW->getOperation()) {
11759   case AtomicRMWInst::FAdd: {
11760     Type *Ty = RMW->getType();
11761 
11762     // We don't have a way to support 16-bit atomics now, so just leave them
11763     // as-is.
11764     if (Ty->isHalfTy())
11765       return AtomicExpansionKind::None;
11766 
11767     if (!Ty->isFloatTy())
11768       return AtomicExpansionKind::CmpXChg;
11769 
11770     // TODO: Do have these for flat. Older targets also had them for buffers.
11771     unsigned AS = RMW->getPointerAddressSpace();
11772 
11773     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11774       return RMW->use_empty() ? AtomicExpansionKind::None :
11775                                 AtomicExpansionKind::CmpXChg;
11776     }
11777 
11778     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11779       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11780   }
11781   default:
11782     break;
11783   }
11784 
11785   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11786 }
11787 
11788 const TargetRegisterClass *
11789 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11790   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11791   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11792   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11793     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11794                                                : &AMDGPU::SReg_32RegClass;
11795   if (!TRI->isSGPRClass(RC) && !isDivergent)
11796     return TRI->getEquivalentSGPRClass(RC);
11797   else if (TRI->isSGPRClass(RC) && isDivergent)
11798     return TRI->getEquivalentVGPRClass(RC);
11799 
11800   return RC;
11801 }
11802 
11803 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11804 // uniform values (as produced by the mask results of control flow intrinsics)
11805 // used outside of divergent blocks. The phi users need to also be treated as
11806 // always uniform.
11807 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11808                       unsigned WaveSize) {
11809   // FIXME: We asssume we never cast the mask results of a control flow
11810   // intrinsic.
11811   // Early exit if the type won't be consistent as a compile time hack.
11812   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11813   if (!IT || IT->getBitWidth() != WaveSize)
11814     return false;
11815 
11816   if (!isa<Instruction>(V))
11817     return false;
11818   if (!Visited.insert(V).second)
11819     return false;
11820   bool Result = false;
11821   for (auto U : V->users()) {
11822     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11823       if (V == U->getOperand(1)) {
11824         switch (Intrinsic->getIntrinsicID()) {
11825         default:
11826           Result = false;
11827           break;
11828         case Intrinsic::amdgcn_if_break:
11829         case Intrinsic::amdgcn_if:
11830         case Intrinsic::amdgcn_else:
11831           Result = true;
11832           break;
11833         }
11834       }
11835       if (V == U->getOperand(0)) {
11836         switch (Intrinsic->getIntrinsicID()) {
11837         default:
11838           Result = false;
11839           break;
11840         case Intrinsic::amdgcn_end_cf:
11841         case Intrinsic::amdgcn_loop:
11842           Result = true;
11843           break;
11844         }
11845       }
11846     } else {
11847       Result = hasCFUser(U, Visited, WaveSize);
11848     }
11849     if (Result)
11850       break;
11851   }
11852   return Result;
11853 }
11854 
11855 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11856                                                const Value *V) const {
11857   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11858     if (CI->isInlineAsm()) {
11859       // FIXME: This cannot give a correct answer. This should only trigger in
11860       // the case where inline asm returns mixed SGPR and VGPR results, used
11861       // outside the defining block. We don't have a specific result to
11862       // consider, so this assumes if any value is SGPR, the overall register
11863       // also needs to be SGPR.
11864       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11865       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11866           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11867       for (auto &TC : TargetConstraints) {
11868         if (TC.Type == InlineAsm::isOutput) {
11869           ComputeConstraintToUse(TC, SDValue());
11870           unsigned AssignedReg;
11871           const TargetRegisterClass *RC;
11872           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11873               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11874           if (RC) {
11875             MachineRegisterInfo &MRI = MF.getRegInfo();
11876             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11877               return true;
11878             else if (SIRI->isSGPRClass(RC))
11879               return true;
11880           }
11881         }
11882       }
11883     }
11884   }
11885   SmallPtrSet<const Value *, 16> Visited;
11886   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11887 }
11888 
11889 std::pair<int, MVT>
11890 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11891                                           Type *Ty) const {
11892   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11893   auto Size = DL.getTypeSizeInBits(Ty);
11894   // Maximum load or store can handle 8 dwords for scalar and 4 for
11895   // vector ALU. Let's assume anything above 8 dwords is expensive
11896   // even if legal.
11897   if (Size <= 256)
11898     return Cost;
11899 
11900   Cost.first = (Size + 255) / 256;
11901   return Cost;
11902 }
11903