1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUSubtarget.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
19 #include "SIDefines.h"
20 #include "SIInstrInfo.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "SIRegisterInfo.h"
23 #include "Utils/AMDGPUBaseInfo.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/DAGCombine.h"
37 #include "llvm/CodeGen/FunctionLoweringInfo.h"
38 #include "llvm/CodeGen/GlobalISel/GISelKnownBits.h"
39 #include "llvm/CodeGen/ISDOpcodes.h"
40 #include "llvm/CodeGen/MachineBasicBlock.h"
41 #include "llvm/CodeGen/MachineFrameInfo.h"
42 #include "llvm/CodeGen/MachineFunction.h"
43 #include "llvm/CodeGen/MachineInstr.h"
44 #include "llvm/CodeGen/MachineInstrBuilder.h"
45 #include "llvm/CodeGen/MachineLoopInfo.h"
46 #include "llvm/CodeGen/MachineMemOperand.h"
47 #include "llvm/CodeGen/MachineModuleInfo.h"
48 #include "llvm/CodeGen/MachineOperand.h"
49 #include "llvm/CodeGen/MachineRegisterInfo.h"
50 #include "llvm/CodeGen/SelectionDAG.h"
51 #include "llvm/CodeGen/SelectionDAGNodes.h"
52 #include "llvm/CodeGen/TargetCallingConv.h"
53 #include "llvm/CodeGen/TargetRegisterInfo.h"
54 #include "llvm/CodeGen/ValueTypes.h"
55 #include "llvm/IR/Constants.h"
56 #include "llvm/IR/DataLayout.h"
57 #include "llvm/IR/DebugLoc.h"
58 #include "llvm/IR/DerivedTypes.h"
59 #include "llvm/IR/DiagnosticInfo.h"
60 #include "llvm/IR/Function.h"
61 #include "llvm/IR/GlobalValue.h"
62 #include "llvm/IR/InstrTypes.h"
63 #include "llvm/IR/Instruction.h"
64 #include "llvm/IR/Instructions.h"
65 #include "llvm/IR/IntrinsicInst.h"
66 #include "llvm/IR/Type.h"
67 #include "llvm/Support/Casting.h"
68 #include "llvm/Support/CodeGen.h"
69 #include "llvm/Support/CommandLine.h"
70 #include "llvm/Support/Compiler.h"
71 #include "llvm/Support/ErrorHandling.h"
72 #include "llvm/Support/KnownBits.h"
73 #include "llvm/Support/MachineValueType.h"
74 #include "llvm/Support/MathExtras.h"
75 #include "llvm/Target/TargetOptions.h"
76 #include <cassert>
77 #include <cmath>
78 #include <cstdint>
79 #include <iterator>
80 #include <tuple>
81 #include <utility>
82 #include <vector>
83 
84 using namespace llvm;
85 
86 #define DEBUG_TYPE "si-lower"
87 
88 STATISTIC(NumTailCalls, "Number of tail calls");
89 
90 static cl::opt<bool> DisableLoopAlignment(
91   "amdgpu-disable-loop-alignment",
92   cl::desc("Do not align and prefetch loops"),
93   cl::init(false));
94 
95 static cl::opt<bool> VGPRReserveforSGPRSpill(
96     "amdgpu-reserve-vgpr-for-sgpr-spill",
97     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
98 
99 static cl::opt<bool> UseDivergentRegisterIndexing(
100   "amdgpu-use-divergent-register-indexing",
101   cl::Hidden,
102   cl::desc("Use indirect register addressing for divergent indexes"),
103   cl::init(false));
104 
105 static bool hasFP32Denormals(const MachineFunction &MF) {
106   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
107   return Info->getMode().allFP32Denormals();
108 }
109 
110 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
111   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
112   return Info->getMode().allFP64FP16Denormals();
113 }
114 
115 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
116   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
117   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
118     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
119       return AMDGPU::SGPR0 + Reg;
120     }
121   }
122   llvm_unreachable("Cannot allocate sgpr");
123 }
124 
125 SITargetLowering::SITargetLowering(const TargetMachine &TM,
126                                    const GCNSubtarget &STI)
127     : AMDGPUTargetLowering(TM, STI),
128       Subtarget(&STI) {
129   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
130   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
131 
132   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
133   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
134 
135   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
136   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
137   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
138 
139   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
140   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
141 
142   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
143   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
144 
145   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
146   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
147 
148   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
149   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
150 
151   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
152   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
153 
154   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
155   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
156 
157   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
158   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
159 
160   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
161   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
162 
163   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
164   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
165 
166   if (Subtarget->has16BitInsts()) {
167     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
168     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
169 
170     // Unless there are also VOP3P operations, not operations are really legal.
171     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
172     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
173     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
174     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
175   }
176 
177   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
178   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
179 
180   computeRegisterProperties(Subtarget->getRegisterInfo());
181 
182   // The boolean content concept here is too inflexible. Compares only ever
183   // really produce a 1-bit result. Any copy/extend from these will turn into a
184   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
185   // it's what most targets use.
186   setBooleanContents(ZeroOrOneBooleanContent);
187   setBooleanVectorContents(ZeroOrOneBooleanContent);
188 
189   // We need to custom lower vector stores from local memory
190   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
195   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
196   setOperationAction(ISD::LOAD, MVT::i1, Custom);
197   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
198 
199   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
202   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
203   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
204   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
205   setOperationAction(ISD::STORE, MVT::i1, Custom);
206   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
207 
208   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
209   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
210   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
211   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
212   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
213   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
214   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
215   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
216   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
217   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
218   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
219   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
220   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
221   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
222   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
223   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
224 
225   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
226   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
227   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
228   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
229   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
230 
231   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
232   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
233 
234   setOperationAction(ISD::SELECT, MVT::i1, Promote);
235   setOperationAction(ISD::SELECT, MVT::i64, Custom);
236   setOperationAction(ISD::SELECT, MVT::f64, Promote);
237   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
238 
239   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
241   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
242   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
243   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
244 
245   setOperationAction(ISD::SETCC, MVT::i1, Promote);
246   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
247   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
248   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
249 
250   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
251   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
252   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
253   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
254   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
255   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
256   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
257   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
258 
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
265   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
266   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
267 
268   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
269   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
270   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
271   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
272   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
273   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
274 
275   setOperationAction(ISD::UADDO, MVT::i32, Legal);
276   setOperationAction(ISD::USUBO, MVT::i32, Legal);
277 
278   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
279   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
280 
281   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
282   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
283   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
284 
285 #if 0
286   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
287   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
288 #endif
289 
290   // We only support LOAD/STORE and vector manipulation ops for vectors
291   // with > 4 elements.
292   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
293                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
294                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
295                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
296     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
297       switch (Op) {
298       case ISD::LOAD:
299       case ISD::STORE:
300       case ISD::BUILD_VECTOR:
301       case ISD::BITCAST:
302       case ISD::EXTRACT_VECTOR_ELT:
303       case ISD::INSERT_VECTOR_ELT:
304       case ISD::INSERT_SUBVECTOR:
305       case ISD::EXTRACT_SUBVECTOR:
306       case ISD::SCALAR_TO_VECTOR:
307         break;
308       case ISD::CONCAT_VECTORS:
309         setOperationAction(Op, VT, Custom);
310         break;
311       default:
312         setOperationAction(Op, VT, Expand);
313         break;
314       }
315     }
316   }
317 
318   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
319 
320   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
321   // is expanded to avoid having two separate loops in case the index is a VGPR.
322 
323   // Most operations are naturally 32-bit vector operations. We only support
324   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
325   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
326     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
327     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
328 
329     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
330     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
331 
332     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
333     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
334 
335     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
336     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
337   }
338 
339   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
340     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
341     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
342 
343     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
344     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
345 
346     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
347     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
348 
349     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
350     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
351   }
352 
353   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
354     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
355     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
356 
357     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
358     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
359 
360     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
361     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
362 
363     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
364     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
365   }
366 
367   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
368     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
369     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
370 
371     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
372     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
373 
374     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
375     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
376 
377     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
378     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
379   }
380 
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
382   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
383   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
384   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
385 
386   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
387   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
388 
389   // Avoid stack access for these.
390   // TODO: Generalize to more vector types.
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
393   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
394   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
395 
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
399   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
400   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
401 
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
403   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
404   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
405 
406   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
407   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
408   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
409   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
410 
411   // Deal with vec3 vector operations when widened to vec4.
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
414   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
415   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
416 
417   // Deal with vec5 vector operations when widened to vec8.
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
419   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
420   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
421   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
422 
423   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
424   // and output demarshalling
425   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
426   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
427 
428   // We can't return success/failure, only the old value,
429   // let LLVM add the comparison
430   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
431   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
432 
433   if (Subtarget->hasFlatAddressSpace()) {
434     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
435     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
436   }
437 
438   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
439 
440   // FIXME: This should be narrowed to i32, but that only happens if i64 is
441   // illegal.
442   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
443   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
444   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
445 
446   // On SI this is s_memtime and s_memrealtime on VI.
447   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
448   setOperationAction(ISD::TRAP, MVT::Other, Custom);
449   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
450 
451   if (Subtarget->has16BitInsts()) {
452     setOperationAction(ISD::FPOW, MVT::f16, Promote);
453     setOperationAction(ISD::FPOWI, MVT::f16, Promote);
454     setOperationAction(ISD::FLOG, MVT::f16, Custom);
455     setOperationAction(ISD::FEXP, MVT::f16, Custom);
456     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
457   }
458 
459   if (Subtarget->hasMadMacF32Insts())
460     setOperationAction(ISD::FMAD, MVT::f32, Legal);
461 
462   if (!Subtarget->hasBFI()) {
463     // fcopysign can be done in a single instruction with BFI.
464     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
465     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
466   }
467 
468   if (!Subtarget->hasBCNT(32))
469     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
470 
471   if (!Subtarget->hasBCNT(64))
472     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
473 
474   if (Subtarget->hasFFBH())
475     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
476 
477   if (Subtarget->hasFFBL())
478     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
479 
480   // We only really have 32-bit BFE instructions (and 16-bit on VI).
481   //
482   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
483   // effort to match them now. We want this to be false for i64 cases when the
484   // extraction isn't restricted to the upper or lower half. Ideally we would
485   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
486   // span the midpoint are probably relatively rare, so don't worry about them
487   // for now.
488   if (Subtarget->hasBFE())
489     setHasExtractBitsInsn(true);
490 
491   // Clamp modifier on add/sub
492   if (Subtarget->hasIntClamp()) {
493     setOperationAction(ISD::UADDSAT, MVT::i32, Legal);
494     setOperationAction(ISD::USUBSAT, MVT::i32, Legal);
495   }
496 
497   if (Subtarget->hasAddNoCarry()) {
498     setOperationAction(ISD::SADDSAT, MVT::i16, Legal);
499     setOperationAction(ISD::SSUBSAT, MVT::i16, Legal);
500     setOperationAction(ISD::SADDSAT, MVT::i32, Legal);
501     setOperationAction(ISD::SSUBSAT, MVT::i32, Legal);
502   }
503 
504   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
505   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
506   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
507   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
508 
509 
510   // These are really only legal for ieee_mode functions. We should be avoiding
511   // them for functions that don't have ieee_mode enabled, so just say they are
512   // legal.
513   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
514   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
515   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
516   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
517 
518 
519   if (Subtarget->haveRoundOpsF64()) {
520     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
521     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
522     setOperationAction(ISD::FRINT, MVT::f64, Legal);
523   } else {
524     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
525     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
526     setOperationAction(ISD::FRINT, MVT::f64, Custom);
527     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
528   }
529 
530   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
531 
532   setOperationAction(ISD::FSIN, MVT::f32, Custom);
533   setOperationAction(ISD::FCOS, MVT::f32, Custom);
534   setOperationAction(ISD::FDIV, MVT::f32, Custom);
535   setOperationAction(ISD::FDIV, MVT::f64, Custom);
536 
537   if (Subtarget->has16BitInsts()) {
538     setOperationAction(ISD::Constant, MVT::i16, Legal);
539 
540     setOperationAction(ISD::SMIN, MVT::i16, Legal);
541     setOperationAction(ISD::SMAX, MVT::i16, Legal);
542 
543     setOperationAction(ISD::UMIN, MVT::i16, Legal);
544     setOperationAction(ISD::UMAX, MVT::i16, Legal);
545 
546     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
547     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
548 
549     setOperationAction(ISD::ROTR, MVT::i16, Expand);
550     setOperationAction(ISD::ROTL, MVT::i16, Expand);
551 
552     setOperationAction(ISD::SDIV, MVT::i16, Promote);
553     setOperationAction(ISD::UDIV, MVT::i16, Promote);
554     setOperationAction(ISD::SREM, MVT::i16, Promote);
555     setOperationAction(ISD::UREM, MVT::i16, Promote);
556     setOperationAction(ISD::UADDSAT, MVT::i16, Legal);
557     setOperationAction(ISD::USUBSAT, MVT::i16, Legal);
558 
559     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
560 
561     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
562     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
563     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
564     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
565     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
566 
567     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
568 
569     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
570 
571     setOperationAction(ISD::LOAD, MVT::i16, Custom);
572 
573     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
574 
575     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
576     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
577     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
578     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
579 
580     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
581     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
582 
583     // F16 - Constant Actions.
584     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
585 
586     // F16 - Load/Store Actions.
587     setOperationAction(ISD::LOAD, MVT::f16, Promote);
588     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
589     setOperationAction(ISD::STORE, MVT::f16, Promote);
590     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
591 
592     // F16 - VOP1 Actions.
593     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
594     setOperationAction(ISD::FCOS, MVT::f16, Custom);
595     setOperationAction(ISD::FSIN, MVT::f16, Custom);
596 
597     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
598     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
599 
600     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
601     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
602     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
603     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
604     setOperationAction(ISD::FROUND, MVT::f16, Custom);
605 
606     // F16 - VOP2 Actions.
607     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
608     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
609 
610     setOperationAction(ISD::FDIV, MVT::f16, Custom);
611 
612     // F16 - VOP3 Actions.
613     setOperationAction(ISD::FMA, MVT::f16, Legal);
614     if (STI.hasMadF16())
615       setOperationAction(ISD::FMAD, MVT::f16, Legal);
616 
617     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
618       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
619         switch (Op) {
620         case ISD::LOAD:
621         case ISD::STORE:
622         case ISD::BUILD_VECTOR:
623         case ISD::BITCAST:
624         case ISD::EXTRACT_VECTOR_ELT:
625         case ISD::INSERT_VECTOR_ELT:
626         case ISD::INSERT_SUBVECTOR:
627         case ISD::EXTRACT_SUBVECTOR:
628         case ISD::SCALAR_TO_VECTOR:
629           break;
630         case ISD::CONCAT_VECTORS:
631           setOperationAction(Op, VT, Custom);
632           break;
633         default:
634           setOperationAction(Op, VT, Expand);
635           break;
636         }
637       }
638     }
639 
640     // v_perm_b32 can handle either of these.
641     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
642     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
643     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
644 
645     // XXX - Do these do anything? Vector constants turn into build_vector.
646     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
647     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
648 
649     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
650     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
651 
652     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
653     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
654     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
655     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
656 
657     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
658     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
659     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
660     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
661 
662     setOperationAction(ISD::AND, MVT::v2i16, Promote);
663     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
664     setOperationAction(ISD::OR, MVT::v2i16, Promote);
665     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
666     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
667     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
668 
669     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
670     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
671     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
672     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
673 
674     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
675     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
676     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
677     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
678 
679     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
680     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
681     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
682     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
683 
684     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
685     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
686     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
687 
688     if (!Subtarget->hasVOP3PInsts()) {
689       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
690       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
691     }
692 
693     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
694     // This isn't really legal, but this avoids the legalizer unrolling it (and
695     // allows matching fneg (fabs x) patterns)
696     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
697 
698     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
699     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
700     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
701     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
702 
703     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
704     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
705 
706     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
707     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
708   }
709 
710   if (Subtarget->hasVOP3PInsts()) {
711     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
712     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
713     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
714     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
715     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
716     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
717     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
718     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
719     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
720     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
721 
722     setOperationAction(ISD::UADDSAT, MVT::v2i16, Legal);
723     setOperationAction(ISD::USUBSAT, MVT::v2i16, Legal);
724     setOperationAction(ISD::SADDSAT, MVT::v2i16, Legal);
725     setOperationAction(ISD::SSUBSAT, MVT::v2i16, Legal);
726 
727     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
728     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
729     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
730 
731     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
732     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
733 
734     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
735 
736     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
737     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
738 
739     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
740     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
741 
742     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
743     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
744     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
745     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
746     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
747     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
748 
749     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
750     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
751     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
752     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
753 
754     setOperationAction(ISD::UADDSAT, MVT::v4i16, Custom);
755     setOperationAction(ISD::SADDSAT, MVT::v4i16, Custom);
756     setOperationAction(ISD::USUBSAT, MVT::v4i16, Custom);
757     setOperationAction(ISD::SSUBSAT, MVT::v4i16, Custom);
758 
759     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
760     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
761     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
762 
763     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
764     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
765 
766     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
767     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
768     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
769 
770     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
771     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
772     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
773   }
774 
775   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
776   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
777 
778   if (Subtarget->has16BitInsts()) {
779     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
780     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
781     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
782     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
783   } else {
784     // Legalization hack.
785     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
786     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
787 
788     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
789     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
790   }
791 
792   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
793     setOperationAction(ISD::SELECT, VT, Custom);
794   }
795 
796   setOperationAction(ISD::SMULO, MVT::i64, Custom);
797   setOperationAction(ISD::UMULO, MVT::i64, Custom);
798 
799   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
800   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
801   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
802   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
803   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
804   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
805   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
806 
807   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
808   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
809   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3f16, Custom);
810   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v3i16, Custom);
811   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
812   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
813   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
814   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
815   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
816   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
817   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
818 
819   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
820   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
821   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
822   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3i16, Custom);
823   setOperationAction(ISD::INTRINSIC_VOID, MVT::v3f16, Custom);
824   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
825   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
826   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
827   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
828   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
829 
830   setTargetDAGCombine(ISD::ADD);
831   setTargetDAGCombine(ISD::ADDCARRY);
832   setTargetDAGCombine(ISD::SUB);
833   setTargetDAGCombine(ISD::SUBCARRY);
834   setTargetDAGCombine(ISD::FADD);
835   setTargetDAGCombine(ISD::FSUB);
836   setTargetDAGCombine(ISD::FMINNUM);
837   setTargetDAGCombine(ISD::FMAXNUM);
838   setTargetDAGCombine(ISD::FMINNUM_IEEE);
839   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
840   setTargetDAGCombine(ISD::FMA);
841   setTargetDAGCombine(ISD::SMIN);
842   setTargetDAGCombine(ISD::SMAX);
843   setTargetDAGCombine(ISD::UMIN);
844   setTargetDAGCombine(ISD::UMAX);
845   setTargetDAGCombine(ISD::SETCC);
846   setTargetDAGCombine(ISD::AND);
847   setTargetDAGCombine(ISD::OR);
848   setTargetDAGCombine(ISD::XOR);
849   setTargetDAGCombine(ISD::SINT_TO_FP);
850   setTargetDAGCombine(ISD::UINT_TO_FP);
851   setTargetDAGCombine(ISD::FCANONICALIZE);
852   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
853   setTargetDAGCombine(ISD::ZERO_EXTEND);
854   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
855   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
856   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
857 
858   // All memory operations. Some folding on the pointer operand is done to help
859   // matching the constant offsets in the addressing modes.
860   setTargetDAGCombine(ISD::LOAD);
861   setTargetDAGCombine(ISD::STORE);
862   setTargetDAGCombine(ISD::ATOMIC_LOAD);
863   setTargetDAGCombine(ISD::ATOMIC_STORE);
864   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
865   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
866   setTargetDAGCombine(ISD::ATOMIC_SWAP);
867   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
868   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
869   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
870   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
871   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
872   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
873   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
874   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
875   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
876   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
877   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
878   setTargetDAGCombine(ISD::INTRINSIC_VOID);
879   setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
880 
881   // FIXME: In other contexts we pretend this is a per-function property.
882   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
883 
884   setSchedulingPreference(Sched::RegPressure);
885 }
886 
887 const GCNSubtarget *SITargetLowering::getSubtarget() const {
888   return Subtarget;
889 }
890 
891 //===----------------------------------------------------------------------===//
892 // TargetLowering queries
893 //===----------------------------------------------------------------------===//
894 
895 // v_mad_mix* support a conversion from f16 to f32.
896 //
897 // There is only one special case when denormals are enabled we don't currently,
898 // where this is OK to use.
899 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
900                                        EVT DestVT, EVT SrcVT) const {
901   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
902           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
903     DestVT.getScalarType() == MVT::f32 &&
904     SrcVT.getScalarType() == MVT::f16 &&
905     // TODO: This probably only requires no input flushing?
906     !hasFP32Denormals(DAG.getMachineFunction());
907 }
908 
909 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
910   // SI has some legal vector types, but no legal vector operations. Say no
911   // shuffles are legal in order to prefer scalarizing some vector operations.
912   return false;
913 }
914 
915 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
916                                                     CallingConv::ID CC,
917                                                     EVT VT) const {
918   if (CC == CallingConv::AMDGPU_KERNEL)
919     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
920 
921   if (VT.isVector()) {
922     EVT ScalarVT = VT.getScalarType();
923     unsigned Size = ScalarVT.getSizeInBits();
924     if (Size == 16) {
925       if (Subtarget->has16BitInsts())
926         return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
927       return VT.isInteger() ? MVT::i32 : MVT::f32;
928     }
929 
930     if (Size < 16)
931       return Subtarget->has16BitInsts() ? MVT::i16 : MVT::i32;
932     return Size == 32 ? ScalarVT.getSimpleVT() : MVT::i32;
933   }
934 
935   if (VT.getSizeInBits() > 32)
936     return MVT::i32;
937 
938   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
939 }
940 
941 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
942                                                          CallingConv::ID CC,
943                                                          EVT VT) const {
944   if (CC == CallingConv::AMDGPU_KERNEL)
945     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
946 
947   if (VT.isVector()) {
948     unsigned NumElts = VT.getVectorNumElements();
949     EVT ScalarVT = VT.getScalarType();
950     unsigned Size = ScalarVT.getSizeInBits();
951 
952     // FIXME: Should probably promote 8-bit vectors to i16.
953     if (Size == 16 && Subtarget->has16BitInsts())
954       return (NumElts + 1) / 2;
955 
956     if (Size <= 32)
957       return NumElts;
958 
959     if (Size > 32)
960       return NumElts * ((Size + 31) / 32);
961   } else if (VT.getSizeInBits() > 32)
962     return (VT.getSizeInBits() + 31) / 32;
963 
964   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
965 }
966 
967 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
968   LLVMContext &Context, CallingConv::ID CC,
969   EVT VT, EVT &IntermediateVT,
970   unsigned &NumIntermediates, MVT &RegisterVT) const {
971   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
972     unsigned NumElts = VT.getVectorNumElements();
973     EVT ScalarVT = VT.getScalarType();
974     unsigned Size = ScalarVT.getSizeInBits();
975     // FIXME: We should fix the ABI to be the same on targets without 16-bit
976     // support, but unless we can properly handle 3-vectors, it will be still be
977     // inconsistent.
978     if (Size == 16 && Subtarget->has16BitInsts()) {
979       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
980       IntermediateVT = RegisterVT;
981       NumIntermediates = (NumElts + 1) / 2;
982       return NumIntermediates;
983     }
984 
985     if (Size == 32) {
986       RegisterVT = ScalarVT.getSimpleVT();
987       IntermediateVT = RegisterVT;
988       NumIntermediates = NumElts;
989       return NumIntermediates;
990     }
991 
992     if (Size < 16 && Subtarget->has16BitInsts()) {
993       // FIXME: Should probably form v2i16 pieces
994       RegisterVT = MVT::i16;
995       IntermediateVT = ScalarVT;
996       NumIntermediates = NumElts;
997       return NumIntermediates;
998     }
999 
1000 
1001     if (Size != 16 && Size <= 32) {
1002       RegisterVT = MVT::i32;
1003       IntermediateVT = ScalarVT;
1004       NumIntermediates = NumElts;
1005       return NumIntermediates;
1006     }
1007 
1008     if (Size > 32) {
1009       RegisterVT = MVT::i32;
1010       IntermediateVT = RegisterVT;
1011       NumIntermediates = NumElts * ((Size + 31) / 32);
1012       return NumIntermediates;
1013     }
1014   }
1015 
1016   return TargetLowering::getVectorTypeBreakdownForCallingConv(
1017     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
1018 }
1019 
1020 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
1021   assert(DMaskLanes != 0);
1022 
1023   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
1024     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
1025     return EVT::getVectorVT(Ty->getContext(),
1026                             EVT::getEVT(VT->getElementType()),
1027                             NumElts);
1028   }
1029 
1030   return EVT::getEVT(Ty);
1031 }
1032 
1033 // Peek through TFE struct returns to only use the data size.
1034 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
1035   auto *ST = dyn_cast<StructType>(Ty);
1036   if (!ST)
1037     return memVTFromImageData(Ty, DMaskLanes);
1038 
1039   // Some intrinsics return an aggregate type - special case to work out the
1040   // correct memVT.
1041   //
1042   // Only limited forms of aggregate type currently expected.
1043   if (ST->getNumContainedTypes() != 2 ||
1044       !ST->getContainedType(1)->isIntegerTy(32))
1045     return EVT();
1046   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
1047 }
1048 
1049 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
1050                                           const CallInst &CI,
1051                                           MachineFunction &MF,
1052                                           unsigned IntrID) const {
1053   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1054           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1055     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1056                                                   (Intrinsic::ID)IntrID);
1057     if (Attr.hasFnAttribute(Attribute::ReadNone))
1058       return false;
1059 
1060     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1061 
1062     if (RsrcIntr->IsImage) {
1063       Info.ptrVal = MFI->getImagePSV(
1064         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1065         CI.getArgOperand(RsrcIntr->RsrcArg));
1066       Info.align.reset();
1067     } else {
1068       Info.ptrVal = MFI->getBufferPSV(
1069         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1070         CI.getArgOperand(RsrcIntr->RsrcArg));
1071     }
1072 
1073     Info.flags = MachineMemOperand::MODereferenceable;
1074     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1075       unsigned DMaskLanes = 4;
1076 
1077       if (RsrcIntr->IsImage) {
1078         const AMDGPU::ImageDimIntrinsicInfo *Intr
1079           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1080         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1081           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1082 
1083         if (!BaseOpcode->Gather4) {
1084           // If this isn't a gather, we may have excess loaded elements in the
1085           // IR type. Check the dmask for the real number of elements loaded.
1086           unsigned DMask
1087             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1088           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1089         }
1090 
1091         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1092       } else
1093         Info.memVT = EVT::getEVT(CI.getType());
1094 
1095       // FIXME: What does alignment mean for an image?
1096       Info.opc = ISD::INTRINSIC_W_CHAIN;
1097       Info.flags |= MachineMemOperand::MOLoad;
1098     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1099       Info.opc = ISD::INTRINSIC_VOID;
1100 
1101       Type *DataTy = CI.getArgOperand(0)->getType();
1102       if (RsrcIntr->IsImage) {
1103         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1104         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1105         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1106       } else
1107         Info.memVT = EVT::getEVT(DataTy);
1108 
1109       Info.flags |= MachineMemOperand::MOStore;
1110     } else {
1111       // Atomic
1112       Info.opc = CI.getType()->isVoidTy() ? ISD::INTRINSIC_VOID :
1113                                             ISD::INTRINSIC_W_CHAIN;
1114       Info.memVT = MVT::getVT(CI.getArgOperand(0)->getType());
1115       Info.flags = MachineMemOperand::MOLoad |
1116                    MachineMemOperand::MOStore |
1117                    MachineMemOperand::MODereferenceable;
1118 
1119       // XXX - Should this be volatile without known ordering?
1120       Info.flags |= MachineMemOperand::MOVolatile;
1121     }
1122     return true;
1123   }
1124 
1125   switch (IntrID) {
1126   case Intrinsic::amdgcn_atomic_inc:
1127   case Intrinsic::amdgcn_atomic_dec:
1128   case Intrinsic::amdgcn_ds_ordered_add:
1129   case Intrinsic::amdgcn_ds_ordered_swap:
1130   case Intrinsic::amdgcn_ds_fadd:
1131   case Intrinsic::amdgcn_ds_fmin:
1132   case Intrinsic::amdgcn_ds_fmax: {
1133     Info.opc = ISD::INTRINSIC_W_CHAIN;
1134     Info.memVT = MVT::getVT(CI.getType());
1135     Info.ptrVal = CI.getOperand(0);
1136     Info.align.reset();
1137     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1138 
1139     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1140     if (!Vol->isZero())
1141       Info.flags |= MachineMemOperand::MOVolatile;
1142 
1143     return true;
1144   }
1145   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1146     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1147 
1148     Info.opc = ISD::INTRINSIC_W_CHAIN;
1149     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1150     Info.ptrVal = MFI->getBufferPSV(
1151       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1152       CI.getArgOperand(1));
1153     Info.align.reset();
1154     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1155 
1156     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1157     if (!Vol || !Vol->isZero())
1158       Info.flags |= MachineMemOperand::MOVolatile;
1159 
1160     return true;
1161   }
1162   case Intrinsic::amdgcn_ds_append:
1163   case Intrinsic::amdgcn_ds_consume: {
1164     Info.opc = ISD::INTRINSIC_W_CHAIN;
1165     Info.memVT = MVT::getVT(CI.getType());
1166     Info.ptrVal = CI.getOperand(0);
1167     Info.align.reset();
1168     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1169 
1170     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1171     if (!Vol->isZero())
1172       Info.flags |= MachineMemOperand::MOVolatile;
1173 
1174     return true;
1175   }
1176   case Intrinsic::amdgcn_global_atomic_csub: {
1177     Info.opc = ISD::INTRINSIC_W_CHAIN;
1178     Info.memVT = MVT::getVT(CI.getType());
1179     Info.ptrVal = CI.getOperand(0);
1180     Info.align.reset();
1181     Info.flags = MachineMemOperand::MOLoad |
1182                  MachineMemOperand::MOStore |
1183                  MachineMemOperand::MOVolatile;
1184     return true;
1185   }
1186   case Intrinsic::amdgcn_global_atomic_fadd: {
1187     Info.opc = ISD::INTRINSIC_W_CHAIN;
1188     Info.memVT = MVT::getVT(CI.getType());
1189     Info.ptrVal = CI.getOperand(0);
1190     Info.align.reset();
1191     Info.flags = MachineMemOperand::MOLoad |
1192                  MachineMemOperand::MOStore |
1193                  MachineMemOperand::MODereferenceable |
1194                  MachineMemOperand::MOVolatile;
1195     return true;
1196   }
1197   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
1198     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1199     Info.opc = ISD::INTRINSIC_W_CHAIN;
1200     Info.memVT = MVT::getVT(CI.getType()); // XXX: what is correct VT?
1201     Info.ptrVal = MFI->getImagePSV(
1202         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(), CI.getArgOperand(5));
1203     Info.align.reset();
1204     Info.flags = MachineMemOperand::MOLoad |
1205                  MachineMemOperand::MODereferenceable;
1206     return true;
1207   }
1208   case Intrinsic::amdgcn_ds_gws_init:
1209   case Intrinsic::amdgcn_ds_gws_barrier:
1210   case Intrinsic::amdgcn_ds_gws_sema_v:
1211   case Intrinsic::amdgcn_ds_gws_sema_br:
1212   case Intrinsic::amdgcn_ds_gws_sema_p:
1213   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1214     Info.opc = ISD::INTRINSIC_VOID;
1215 
1216     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1217     Info.ptrVal =
1218         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1219 
1220     // This is an abstract access, but we need to specify a type and size.
1221     Info.memVT = MVT::i32;
1222     Info.size = 4;
1223     Info.align = Align(4);
1224 
1225     Info.flags = MachineMemOperand::MOStore;
1226     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1227       Info.flags = MachineMemOperand::MOLoad;
1228     return true;
1229   }
1230   default:
1231     return false;
1232   }
1233 }
1234 
1235 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1236                                             SmallVectorImpl<Value*> &Ops,
1237                                             Type *&AccessTy) const {
1238   switch (II->getIntrinsicID()) {
1239   case Intrinsic::amdgcn_atomic_inc:
1240   case Intrinsic::amdgcn_atomic_dec:
1241   case Intrinsic::amdgcn_ds_ordered_add:
1242   case Intrinsic::amdgcn_ds_ordered_swap:
1243   case Intrinsic::amdgcn_ds_append:
1244   case Intrinsic::amdgcn_ds_consume:
1245   case Intrinsic::amdgcn_ds_fadd:
1246   case Intrinsic::amdgcn_ds_fmin:
1247   case Intrinsic::amdgcn_ds_fmax:
1248   case Intrinsic::amdgcn_global_atomic_fadd:
1249   case Intrinsic::amdgcn_global_atomic_csub: {
1250     Value *Ptr = II->getArgOperand(0);
1251     AccessTy = II->getType();
1252     Ops.push_back(Ptr);
1253     return true;
1254   }
1255   default:
1256     return false;
1257   }
1258 }
1259 
1260 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1261   if (!Subtarget->hasFlatInstOffsets()) {
1262     // Flat instructions do not have offsets, and only have the register
1263     // address.
1264     return AM.BaseOffs == 0 && AM.Scale == 0;
1265   }
1266 
1267   return AM.Scale == 0 &&
1268          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1269                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1270                                   /*Signed=*/false));
1271 }
1272 
1273 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1274   if (Subtarget->hasFlatGlobalInsts())
1275     return AM.Scale == 0 &&
1276            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1277                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1278                                     /*Signed=*/true));
1279 
1280   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1281       // Assume the we will use FLAT for all global memory accesses
1282       // on VI.
1283       // FIXME: This assumption is currently wrong.  On VI we still use
1284       // MUBUF instructions for the r + i addressing mode.  As currently
1285       // implemented, the MUBUF instructions only work on buffer < 4GB.
1286       // It may be possible to support > 4GB buffers with MUBUF instructions,
1287       // by setting the stride value in the resource descriptor which would
1288       // increase the size limit to (stride * 4GB).  However, this is risky,
1289       // because it has never been validated.
1290     return isLegalFlatAddressingMode(AM);
1291   }
1292 
1293   return isLegalMUBUFAddressingMode(AM);
1294 }
1295 
1296 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1297   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1298   // additionally can do r + r + i with addr64. 32-bit has more addressing
1299   // mode options. Depending on the resource constant, it can also do
1300   // (i64 r0) + (i32 r1) * (i14 i).
1301   //
1302   // Private arrays end up using a scratch buffer most of the time, so also
1303   // assume those use MUBUF instructions. Scratch loads / stores are currently
1304   // implemented as mubuf instructions with offen bit set, so slightly
1305   // different than the normal addr64.
1306   if (!SIInstrInfo::isLegalMUBUFImmOffset(AM.BaseOffs))
1307     return false;
1308 
1309   // FIXME: Since we can split immediate into soffset and immediate offset,
1310   // would it make sense to allow any immediate?
1311 
1312   switch (AM.Scale) {
1313   case 0: // r + i or just i, depending on HasBaseReg.
1314     return true;
1315   case 1:
1316     return true; // We have r + r or r + i.
1317   case 2:
1318     if (AM.HasBaseReg) {
1319       // Reject 2 * r + r.
1320       return false;
1321     }
1322 
1323     // Allow 2 * r as r + r
1324     // Or  2 * r + i is allowed as r + r + i.
1325     return true;
1326   default: // Don't allow n * r
1327     return false;
1328   }
1329 }
1330 
1331 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1332                                              const AddrMode &AM, Type *Ty,
1333                                              unsigned AS, Instruction *I) const {
1334   // No global is ever allowed as a base.
1335   if (AM.BaseGV)
1336     return false;
1337 
1338   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1339     return isLegalGlobalAddressingMode(AM);
1340 
1341   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1342       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1343       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1344     // If the offset isn't a multiple of 4, it probably isn't going to be
1345     // correctly aligned.
1346     // FIXME: Can we get the real alignment here?
1347     if (AM.BaseOffs % 4 != 0)
1348       return isLegalMUBUFAddressingMode(AM);
1349 
1350     // There are no SMRD extloads, so if we have to do a small type access we
1351     // will use a MUBUF load.
1352     // FIXME?: We also need to do this if unaligned, but we don't know the
1353     // alignment here.
1354     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1355       return isLegalGlobalAddressingMode(AM);
1356 
1357     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1358       // SMRD instructions have an 8-bit, dword offset on SI.
1359       if (!isUInt<8>(AM.BaseOffs / 4))
1360         return false;
1361     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1362       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1363       // in 8-bits, it can use a smaller encoding.
1364       if (!isUInt<32>(AM.BaseOffs / 4))
1365         return false;
1366     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1367       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1368       if (!isUInt<20>(AM.BaseOffs))
1369         return false;
1370     } else
1371       llvm_unreachable("unhandled generation");
1372 
1373     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1374       return true;
1375 
1376     if (AM.Scale == 1 && AM.HasBaseReg)
1377       return true;
1378 
1379     return false;
1380 
1381   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1382     return isLegalMUBUFAddressingMode(AM);
1383   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1384              AS == AMDGPUAS::REGION_ADDRESS) {
1385     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1386     // field.
1387     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1388     // an 8-bit dword offset but we don't know the alignment here.
1389     if (!isUInt<16>(AM.BaseOffs))
1390       return false;
1391 
1392     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1393       return true;
1394 
1395     if (AM.Scale == 1 && AM.HasBaseReg)
1396       return true;
1397 
1398     return false;
1399   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1400              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1401     // For an unknown address space, this usually means that this is for some
1402     // reason being used for pure arithmetic, and not based on some addressing
1403     // computation. We don't have instructions that compute pointers with any
1404     // addressing modes, so treat them as having no offset like flat
1405     // instructions.
1406     return isLegalFlatAddressingMode(AM);
1407   }
1408 
1409   // Assume a user alias of global for unknown address spaces.
1410   return isLegalGlobalAddressingMode(AM);
1411 }
1412 
1413 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1414                                         const SelectionDAG &DAG) const {
1415   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1416     return (MemVT.getSizeInBits() <= 4 * 32);
1417   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1418     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1419     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1420   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1421     return (MemVT.getSizeInBits() <= 2 * 32);
1422   }
1423   return true;
1424 }
1425 
1426 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1427     unsigned Size, unsigned AddrSpace, Align Alignment,
1428     MachineMemOperand::Flags Flags, bool *IsFast) const {
1429   if (IsFast)
1430     *IsFast = false;
1431 
1432   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1433       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1434     // Check if alignment requirements for ds_read/write instructions are
1435     // disabled.
1436     if (Subtarget->hasUnalignedDSAccess() &&
1437         Subtarget->hasUnalignedAccessMode() &&
1438         !Subtarget->hasLDSMisalignedBug()) {
1439       if (IsFast)
1440         *IsFast = Alignment != Align(2);
1441       return true;
1442     }
1443 
1444     if (Size == 64) {
1445       // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1446       // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1447       // with adjacent offsets.
1448       bool AlignedBy4 = Alignment >= Align(4);
1449       if (IsFast)
1450         *IsFast = AlignedBy4;
1451 
1452       return AlignedBy4;
1453     }
1454     if (Size == 96) {
1455       // ds_read/write_b96 require 16-byte alignment on gfx8 and older.
1456       bool Aligned = Alignment >= Align(16);
1457       if (IsFast)
1458         *IsFast = Aligned;
1459 
1460       return Aligned;
1461     }
1462     if (Size == 128) {
1463       // ds_read/write_b128 require 16-byte alignment on gfx8 and older, but we
1464       // can do a 8 byte aligned, 16 byte access in a single operation using
1465       // ds_read2/write2_b64.
1466       bool Aligned = Alignment >= Align(8);
1467       if (IsFast)
1468         *IsFast = Aligned;
1469 
1470       return Aligned;
1471     }
1472   }
1473 
1474   // FIXME: We have to be conservative here and assume that flat operations
1475   // will access scratch.  If we had access to the IR function, then we
1476   // could determine if any private memory was used in the function.
1477   if (!Subtarget->hasUnalignedScratchAccess() &&
1478       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1479        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1480     bool AlignedBy4 = Alignment >= Align(4);
1481     if (IsFast)
1482       *IsFast = AlignedBy4;
1483 
1484     return AlignedBy4;
1485   }
1486 
1487   if (Subtarget->hasUnalignedBufferAccess() &&
1488       !(AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1489         AddrSpace == AMDGPUAS::REGION_ADDRESS)) {
1490     // If we have an uniform constant load, it still requires using a slow
1491     // buffer instruction if unaligned.
1492     if (IsFast) {
1493       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1494       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1495       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1496                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1497         Alignment >= Align(4) : Alignment != Align(2);
1498     }
1499 
1500     return true;
1501   }
1502 
1503   // Smaller than dword value must be aligned.
1504   if (Size < 32)
1505     return false;
1506 
1507   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1508   // byte-address are ignored, thus forcing Dword alignment.
1509   // This applies to private, global, and constant memory.
1510   if (IsFast)
1511     *IsFast = true;
1512 
1513   return Size >= 32 && Alignment >= Align(4);
1514 }
1515 
1516 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1517     EVT VT, unsigned AddrSpace, unsigned Alignment,
1518     MachineMemOperand::Flags Flags, bool *IsFast) const {
1519   if (IsFast)
1520     *IsFast = false;
1521 
1522   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1523   // which isn't a simple VT.
1524   // Until MVT is extended to handle this, simply check for the size and
1525   // rely on the condition below: allow accesses if the size is a multiple of 4.
1526   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1527                            VT.getStoreSize() > 16)) {
1528     return false;
1529   }
1530 
1531   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1532                                             Align(Alignment), Flags, IsFast);
1533 }
1534 
1535 EVT SITargetLowering::getOptimalMemOpType(
1536     const MemOp &Op, const AttributeList &FuncAttributes) const {
1537   // FIXME: Should account for address space here.
1538 
1539   // The default fallback uses the private pointer size as a guess for a type to
1540   // use. Make sure we switch these to 64-bit accesses.
1541 
1542   if (Op.size() >= 16 &&
1543       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1544     return MVT::v4i32;
1545 
1546   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1547     return MVT::v2i32;
1548 
1549   // Use the default.
1550   return MVT::Other;
1551 }
1552 
1553 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1554   const MemSDNode *MemNode = cast<MemSDNode>(N);
1555   const Value *Ptr = MemNode->getMemOperand()->getValue();
1556   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1557   return I && I->getMetadata("amdgpu.noclobber");
1558 }
1559 
1560 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1561                                            unsigned DestAS) const {
1562   // Flat -> private/local is a simple truncate.
1563   // Flat -> global is no-op
1564   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1565     return true;
1566 
1567   const GCNTargetMachine &TM =
1568       static_cast<const GCNTargetMachine &>(getTargetMachine());
1569   return TM.isNoopAddrSpaceCast(SrcAS, DestAS);
1570 }
1571 
1572 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1573   const MemSDNode *MemNode = cast<MemSDNode>(N);
1574 
1575   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1576 }
1577 
1578 TargetLoweringBase::LegalizeTypeAction
1579 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1580   int NumElts = VT.getVectorNumElements();
1581   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1582     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1583   return TargetLoweringBase::getPreferredVectorAction(VT);
1584 }
1585 
1586 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1587                                                          Type *Ty) const {
1588   // FIXME: Could be smarter if called for vector constants.
1589   return true;
1590 }
1591 
1592 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1593   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1594     switch (Op) {
1595     case ISD::LOAD:
1596     case ISD::STORE:
1597 
1598     // These operations are done with 32-bit instructions anyway.
1599     case ISD::AND:
1600     case ISD::OR:
1601     case ISD::XOR:
1602     case ISD::SELECT:
1603       // TODO: Extensions?
1604       return true;
1605     default:
1606       return false;
1607     }
1608   }
1609 
1610   // SimplifySetCC uses this function to determine whether or not it should
1611   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1612   if (VT == MVT::i1 && Op == ISD::SETCC)
1613     return false;
1614 
1615   return TargetLowering::isTypeDesirableForOp(Op, VT);
1616 }
1617 
1618 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1619                                                    const SDLoc &SL,
1620                                                    SDValue Chain,
1621                                                    uint64_t Offset) const {
1622   const DataLayout &DL = DAG.getDataLayout();
1623   MachineFunction &MF = DAG.getMachineFunction();
1624   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1625 
1626   const ArgDescriptor *InputPtrReg;
1627   const TargetRegisterClass *RC;
1628   LLT ArgTy;
1629 
1630   std::tie(InputPtrReg, RC, ArgTy) =
1631       Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1632 
1633   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1634   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1635   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1636     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1637 
1638   return DAG.getObjectPtrOffset(SL, BasePtr, TypeSize::Fixed(Offset));
1639 }
1640 
1641 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1642                                             const SDLoc &SL) const {
1643   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1644                                                FIRST_IMPLICIT);
1645   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1646 }
1647 
1648 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1649                                          const SDLoc &SL, SDValue Val,
1650                                          bool Signed,
1651                                          const ISD::InputArg *Arg) const {
1652   // First, if it is a widened vector, narrow it.
1653   if (VT.isVector() &&
1654       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1655     EVT NarrowedVT =
1656         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1657                          VT.getVectorNumElements());
1658     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1659                       DAG.getConstant(0, SL, MVT::i32));
1660   }
1661 
1662   // Then convert the vector elements or scalar value.
1663   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1664       VT.bitsLT(MemVT)) {
1665     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1666     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1667   }
1668 
1669   if (MemVT.isFloatingPoint())
1670     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1671   else if (Signed)
1672     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1673   else
1674     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1675 
1676   return Val;
1677 }
1678 
1679 SDValue SITargetLowering::lowerKernargMemParameter(
1680     SelectionDAG &DAG, EVT VT, EVT MemVT, const SDLoc &SL, SDValue Chain,
1681     uint64_t Offset, Align Alignment, bool Signed,
1682     const ISD::InputArg *Arg) const {
1683   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1684 
1685   // Try to avoid using an extload by loading earlier than the argument address,
1686   // and extracting the relevant bits. The load should hopefully be merged with
1687   // the previous argument.
1688   if (MemVT.getStoreSize() < 4 && Alignment < 4) {
1689     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1690     int64_t AlignDownOffset = alignDown(Offset, 4);
1691     int64_t OffsetDiff = Offset - AlignDownOffset;
1692 
1693     EVT IntVT = MemVT.changeTypeToInteger();
1694 
1695     // TODO: If we passed in the base kernel offset we could have a better
1696     // alignment than 4, but we don't really need it.
1697     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1698     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, Align(4),
1699                                MachineMemOperand::MODereferenceable |
1700                                    MachineMemOperand::MOInvariant);
1701 
1702     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1703     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1704 
1705     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1706     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1707     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1708 
1709 
1710     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1711   }
1712 
1713   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1714   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Alignment,
1715                              MachineMemOperand::MODereferenceable |
1716                                  MachineMemOperand::MOInvariant);
1717 
1718   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1719   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1720 }
1721 
1722 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1723                                               const SDLoc &SL, SDValue Chain,
1724                                               const ISD::InputArg &Arg) const {
1725   MachineFunction &MF = DAG.getMachineFunction();
1726   MachineFrameInfo &MFI = MF.getFrameInfo();
1727 
1728   if (Arg.Flags.isByVal()) {
1729     unsigned Size = Arg.Flags.getByValSize();
1730     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1731     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1732   }
1733 
1734   unsigned ArgOffset = VA.getLocMemOffset();
1735   unsigned ArgSize = VA.getValVT().getStoreSize();
1736 
1737   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1738 
1739   // Create load nodes to retrieve arguments from the stack.
1740   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1741   SDValue ArgValue;
1742 
1743   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1744   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1745   MVT MemVT = VA.getValVT();
1746 
1747   switch (VA.getLocInfo()) {
1748   default:
1749     break;
1750   case CCValAssign::BCvt:
1751     MemVT = VA.getLocVT();
1752     break;
1753   case CCValAssign::SExt:
1754     ExtType = ISD::SEXTLOAD;
1755     break;
1756   case CCValAssign::ZExt:
1757     ExtType = ISD::ZEXTLOAD;
1758     break;
1759   case CCValAssign::AExt:
1760     ExtType = ISD::EXTLOAD;
1761     break;
1762   }
1763 
1764   ArgValue = DAG.getExtLoad(
1765     ExtType, SL, VA.getLocVT(), Chain, FIN,
1766     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1767     MemVT);
1768   return ArgValue;
1769 }
1770 
1771 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1772   const SIMachineFunctionInfo &MFI,
1773   EVT VT,
1774   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1775   const ArgDescriptor *Reg;
1776   const TargetRegisterClass *RC;
1777   LLT Ty;
1778 
1779   std::tie(Reg, RC, Ty) = MFI.getPreloadedValue(PVID);
1780   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1781 }
1782 
1783 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1784                                    CallingConv::ID CallConv,
1785                                    ArrayRef<ISD::InputArg> Ins,
1786                                    BitVector &Skipped,
1787                                    FunctionType *FType,
1788                                    SIMachineFunctionInfo *Info) {
1789   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1790     const ISD::InputArg *Arg = &Ins[I];
1791 
1792     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1793            "vector type argument should have been split");
1794 
1795     // First check if it's a PS input addr.
1796     if (CallConv == CallingConv::AMDGPU_PS &&
1797         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1798       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1799 
1800       // Inconveniently only the first part of the split is marked as isSplit,
1801       // so skip to the end. We only want to increment PSInputNum once for the
1802       // entire split argument.
1803       if (Arg->Flags.isSplit()) {
1804         while (!Arg->Flags.isSplitEnd()) {
1805           assert((!Arg->VT.isVector() ||
1806                   Arg->VT.getScalarSizeInBits() == 16) &&
1807                  "unexpected vector split in ps argument type");
1808           if (!SkipArg)
1809             Splits.push_back(*Arg);
1810           Arg = &Ins[++I];
1811         }
1812       }
1813 
1814       if (SkipArg) {
1815         // We can safely skip PS inputs.
1816         Skipped.set(Arg->getOrigArgIndex());
1817         ++PSInputNum;
1818         continue;
1819       }
1820 
1821       Info->markPSInputAllocated(PSInputNum);
1822       if (Arg->Used)
1823         Info->markPSInputEnabled(PSInputNum);
1824 
1825       ++PSInputNum;
1826     }
1827 
1828     Splits.push_back(*Arg);
1829   }
1830 }
1831 
1832 // Allocate special inputs passed in VGPRs.
1833 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1834                                                       MachineFunction &MF,
1835                                                       const SIRegisterInfo &TRI,
1836                                                       SIMachineFunctionInfo &Info) const {
1837   const LLT S32 = LLT::scalar(32);
1838   MachineRegisterInfo &MRI = MF.getRegInfo();
1839 
1840   if (Info.hasWorkItemIDX()) {
1841     Register Reg = AMDGPU::VGPR0;
1842     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1843 
1844     CCInfo.AllocateReg(Reg);
1845     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1846   }
1847 
1848   if (Info.hasWorkItemIDY()) {
1849     Register Reg = AMDGPU::VGPR1;
1850     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1851 
1852     CCInfo.AllocateReg(Reg);
1853     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1854   }
1855 
1856   if (Info.hasWorkItemIDZ()) {
1857     Register Reg = AMDGPU::VGPR2;
1858     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1859 
1860     CCInfo.AllocateReg(Reg);
1861     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1862   }
1863 }
1864 
1865 // Try to allocate a VGPR at the end of the argument list, or if no argument
1866 // VGPRs are left allocating a stack slot.
1867 // If \p Mask is is given it indicates bitfield position in the register.
1868 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1869 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1870                                          ArgDescriptor Arg = ArgDescriptor()) {
1871   if (Arg.isSet())
1872     return ArgDescriptor::createArg(Arg, Mask);
1873 
1874   ArrayRef<MCPhysReg> ArgVGPRs
1875     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1876   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1877   if (RegIdx == ArgVGPRs.size()) {
1878     // Spill to stack required.
1879     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1880 
1881     return ArgDescriptor::createStack(Offset, Mask);
1882   }
1883 
1884   unsigned Reg = ArgVGPRs[RegIdx];
1885   Reg = CCInfo.AllocateReg(Reg);
1886   assert(Reg != AMDGPU::NoRegister);
1887 
1888   MachineFunction &MF = CCInfo.getMachineFunction();
1889   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1890   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1891   return ArgDescriptor::createRegister(Reg, Mask);
1892 }
1893 
1894 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1895                                              const TargetRegisterClass *RC,
1896                                              unsigned NumArgRegs) {
1897   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1898   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1899   if (RegIdx == ArgSGPRs.size())
1900     report_fatal_error("ran out of SGPRs for arguments");
1901 
1902   unsigned Reg = ArgSGPRs[RegIdx];
1903   Reg = CCInfo.AllocateReg(Reg);
1904   assert(Reg != AMDGPU::NoRegister);
1905 
1906   MachineFunction &MF = CCInfo.getMachineFunction();
1907   MF.addLiveIn(Reg, RC);
1908   return ArgDescriptor::createRegister(Reg);
1909 }
1910 
1911 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1912   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1913 }
1914 
1915 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1916   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1917 }
1918 
1919 /// Allocate implicit function VGPR arguments at the end of allocated user
1920 /// arguments.
1921 void SITargetLowering::allocateSpecialInputVGPRs(
1922   CCState &CCInfo, MachineFunction &MF,
1923   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1924   const unsigned Mask = 0x3ff;
1925   ArgDescriptor Arg;
1926 
1927   if (Info.hasWorkItemIDX()) {
1928     Arg = allocateVGPR32Input(CCInfo, Mask);
1929     Info.setWorkItemIDX(Arg);
1930   }
1931 
1932   if (Info.hasWorkItemIDY()) {
1933     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1934     Info.setWorkItemIDY(Arg);
1935   }
1936 
1937   if (Info.hasWorkItemIDZ())
1938     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1939 }
1940 
1941 /// Allocate implicit function VGPR arguments in fixed registers.
1942 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1943   CCState &CCInfo, MachineFunction &MF,
1944   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1945   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1946   if (!Reg)
1947     report_fatal_error("failed to allocated VGPR for implicit arguments");
1948 
1949   const unsigned Mask = 0x3ff;
1950   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1951   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1952   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1953 }
1954 
1955 void SITargetLowering::allocateSpecialInputSGPRs(
1956   CCState &CCInfo,
1957   MachineFunction &MF,
1958   const SIRegisterInfo &TRI,
1959   SIMachineFunctionInfo &Info) const {
1960   auto &ArgInfo = Info.getArgInfo();
1961 
1962   // TODO: Unify handling with private memory pointers.
1963 
1964   if (Info.hasDispatchPtr())
1965     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1966 
1967   if (Info.hasQueuePtr())
1968     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1969 
1970   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1971   // constant offset from the kernarg segment.
1972   if (Info.hasImplicitArgPtr())
1973     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1974 
1975   if (Info.hasDispatchID())
1976     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1977 
1978   // flat_scratch_init is not applicable for non-kernel functions.
1979 
1980   if (Info.hasWorkGroupIDX())
1981     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1982 
1983   if (Info.hasWorkGroupIDY())
1984     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1985 
1986   if (Info.hasWorkGroupIDZ())
1987     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1988 }
1989 
1990 // Allocate special inputs passed in user SGPRs.
1991 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1992                                             MachineFunction &MF,
1993                                             const SIRegisterInfo &TRI,
1994                                             SIMachineFunctionInfo &Info) const {
1995   if (Info.hasImplicitBufferPtr()) {
1996     Register ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1997     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1998     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1999   }
2000 
2001   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
2002   if (Info.hasPrivateSegmentBuffer()) {
2003     Register PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
2004     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
2005     CCInfo.AllocateReg(PrivateSegmentBufferReg);
2006   }
2007 
2008   if (Info.hasDispatchPtr()) {
2009     Register DispatchPtrReg = Info.addDispatchPtr(TRI);
2010     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
2011     CCInfo.AllocateReg(DispatchPtrReg);
2012   }
2013 
2014   if (Info.hasQueuePtr()) {
2015     Register QueuePtrReg = Info.addQueuePtr(TRI);
2016     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
2017     CCInfo.AllocateReg(QueuePtrReg);
2018   }
2019 
2020   if (Info.hasKernargSegmentPtr()) {
2021     MachineRegisterInfo &MRI = MF.getRegInfo();
2022     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
2023     CCInfo.AllocateReg(InputPtrReg);
2024 
2025     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
2026     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
2027   }
2028 
2029   if (Info.hasDispatchID()) {
2030     Register DispatchIDReg = Info.addDispatchID(TRI);
2031     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
2032     CCInfo.AllocateReg(DispatchIDReg);
2033   }
2034 
2035   if (Info.hasFlatScratchInit()) {
2036     Register FlatScratchInitReg = Info.addFlatScratchInit(TRI);
2037     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
2038     CCInfo.AllocateReg(FlatScratchInitReg);
2039   }
2040 
2041   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
2042   // these from the dispatch pointer.
2043 }
2044 
2045 // Allocate special input registers that are initialized per-wave.
2046 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
2047                                            MachineFunction &MF,
2048                                            SIMachineFunctionInfo &Info,
2049                                            CallingConv::ID CallConv,
2050                                            bool IsShader) const {
2051   if (Info.hasWorkGroupIDX()) {
2052     Register Reg = Info.addWorkGroupIDX();
2053     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2054     CCInfo.AllocateReg(Reg);
2055   }
2056 
2057   if (Info.hasWorkGroupIDY()) {
2058     Register Reg = Info.addWorkGroupIDY();
2059     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2060     CCInfo.AllocateReg(Reg);
2061   }
2062 
2063   if (Info.hasWorkGroupIDZ()) {
2064     Register Reg = Info.addWorkGroupIDZ();
2065     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2066     CCInfo.AllocateReg(Reg);
2067   }
2068 
2069   if (Info.hasWorkGroupInfo()) {
2070     Register Reg = Info.addWorkGroupInfo();
2071     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
2072     CCInfo.AllocateReg(Reg);
2073   }
2074 
2075   if (Info.hasPrivateSegmentWaveByteOffset()) {
2076     // Scratch wave offset passed in system SGPR.
2077     unsigned PrivateSegmentWaveByteOffsetReg;
2078 
2079     if (IsShader) {
2080       PrivateSegmentWaveByteOffsetReg =
2081         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
2082 
2083       // This is true if the scratch wave byte offset doesn't have a fixed
2084       // location.
2085       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
2086         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
2087         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
2088       }
2089     } else
2090       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
2091 
2092     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
2093     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
2094   }
2095 }
2096 
2097 static void reservePrivateMemoryRegs(const TargetMachine &TM,
2098                                      MachineFunction &MF,
2099                                      const SIRegisterInfo &TRI,
2100                                      SIMachineFunctionInfo &Info) {
2101   // Now that we've figured out where the scratch register inputs are, see if
2102   // should reserve the arguments and use them directly.
2103   MachineFrameInfo &MFI = MF.getFrameInfo();
2104   bool HasStackObjects = MFI.hasStackObjects();
2105   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
2106 
2107   // Record that we know we have non-spill stack objects so we don't need to
2108   // check all stack objects later.
2109   if (HasStackObjects)
2110     Info.setHasNonSpillStackObjects(true);
2111 
2112   // Everything live out of a block is spilled with fast regalloc, so it's
2113   // almost certain that spilling will be required.
2114   if (TM.getOptLevel() == CodeGenOpt::None)
2115     HasStackObjects = true;
2116 
2117   // For now assume stack access is needed in any callee functions, so we need
2118   // the scratch registers to pass in.
2119   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2120 
2121   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2122     // If we have stack objects, we unquestionably need the private buffer
2123     // resource. For the Code Object V2 ABI, this will be the first 4 user
2124     // SGPR inputs. We can reserve those and use them directly.
2125 
2126     Register PrivateSegmentBufferReg =
2127         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2128     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2129   } else {
2130     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2131     // We tentatively reserve the last registers (skipping the last registers
2132     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2133     // we'll replace these with the ones immediately after those which were
2134     // really allocated. In the prologue copies will be inserted from the
2135     // argument to these reserved registers.
2136 
2137     // Without HSA, relocations are used for the scratch pointer and the
2138     // buffer resource setup is always inserted in the prologue. Scratch wave
2139     // offset is still in an input SGPR.
2140     Info.setScratchRSrcReg(ReservedBufferReg);
2141   }
2142 
2143   MachineRegisterInfo &MRI = MF.getRegInfo();
2144 
2145   // For entry functions we have to set up the stack pointer if we use it,
2146   // whereas non-entry functions get this "for free". This means there is no
2147   // intrinsic advantage to using S32 over S34 in cases where we do not have
2148   // calls but do need a frame pointer (i.e. if we are requested to have one
2149   // because frame pointer elimination is disabled). To keep things simple we
2150   // only ever use S32 as the call ABI stack pointer, and so using it does not
2151   // imply we need a separate frame pointer.
2152   //
2153   // Try to use s32 as the SP, but move it if it would interfere with input
2154   // arguments. This won't work with calls though.
2155   //
2156   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2157   // registers.
2158   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2159     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2160   } else {
2161     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2162 
2163     if (MFI.hasCalls())
2164       report_fatal_error("call in graphics shader with too many input SGPRs");
2165 
2166     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2167       if (!MRI.isLiveIn(Reg)) {
2168         Info.setStackPtrOffsetReg(Reg);
2169         break;
2170       }
2171     }
2172 
2173     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2174       report_fatal_error("failed to find register for SP");
2175   }
2176 
2177   // hasFP should be accurate for entry functions even before the frame is
2178   // finalized, because it does not rely on the known stack size, only
2179   // properties like whether variable sized objects are present.
2180   if (ST.getFrameLowering()->hasFP(MF)) {
2181     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2182   }
2183 }
2184 
2185 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2186   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2187   return !Info->isEntryFunction();
2188 }
2189 
2190 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2191 
2192 }
2193 
2194 void SITargetLowering::insertCopiesSplitCSR(
2195   MachineBasicBlock *Entry,
2196   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2197   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2198 
2199   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2200   if (!IStart)
2201     return;
2202 
2203   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2204   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2205   MachineBasicBlock::iterator MBBI = Entry->begin();
2206   for (const MCPhysReg *I = IStart; *I; ++I) {
2207     const TargetRegisterClass *RC = nullptr;
2208     if (AMDGPU::SReg_64RegClass.contains(*I))
2209       RC = &AMDGPU::SGPR_64RegClass;
2210     else if (AMDGPU::SReg_32RegClass.contains(*I))
2211       RC = &AMDGPU::SGPR_32RegClass;
2212     else
2213       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2214 
2215     Register NewVR = MRI->createVirtualRegister(RC);
2216     // Create copy from CSR to a virtual register.
2217     Entry->addLiveIn(*I);
2218     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2219       .addReg(*I);
2220 
2221     // Insert the copy-back instructions right before the terminator.
2222     for (auto *Exit : Exits)
2223       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2224               TII->get(TargetOpcode::COPY), *I)
2225         .addReg(NewVR);
2226   }
2227 }
2228 
2229 SDValue SITargetLowering::LowerFormalArguments(
2230     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2231     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2232     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2233   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2234 
2235   MachineFunction &MF = DAG.getMachineFunction();
2236   const Function &Fn = MF.getFunction();
2237   FunctionType *FType = MF.getFunction().getFunctionType();
2238   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2239 
2240   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2241     DiagnosticInfoUnsupported NoGraphicsHSA(
2242         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2243     DAG.getContext()->diagnose(NoGraphicsHSA);
2244     return DAG.getEntryNode();
2245   }
2246 
2247   SmallVector<ISD::InputArg, 16> Splits;
2248   SmallVector<CCValAssign, 16> ArgLocs;
2249   BitVector Skipped(Ins.size());
2250   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2251                  *DAG.getContext());
2252 
2253   bool IsShader = AMDGPU::isShader(CallConv);
2254   bool IsKernel = AMDGPU::isKernel(CallConv);
2255   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2256 
2257   if (IsShader) {
2258     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2259 
2260     // At least one interpolation mode must be enabled or else the GPU will
2261     // hang.
2262     //
2263     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2264     // set PSInputAddr, the user wants to enable some bits after the compilation
2265     // based on run-time states. Since we can't know what the final PSInputEna
2266     // will look like, so we shouldn't do anything here and the user should take
2267     // responsibility for the correct programming.
2268     //
2269     // Otherwise, the following restrictions apply:
2270     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2271     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2272     //   enabled too.
2273     if (CallConv == CallingConv::AMDGPU_PS) {
2274       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2275            ((Info->getPSInputAddr() & 0xF) == 0 &&
2276             Info->isPSInputAllocated(11))) {
2277         CCInfo.AllocateReg(AMDGPU::VGPR0);
2278         CCInfo.AllocateReg(AMDGPU::VGPR1);
2279         Info->markPSInputAllocated(0);
2280         Info->markPSInputEnabled(0);
2281       }
2282       if (Subtarget->isAmdPalOS()) {
2283         // For isAmdPalOS, the user does not enable some bits after compilation
2284         // based on run-time states; the register values being generated here are
2285         // the final ones set in hardware. Therefore we need to apply the
2286         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2287         // a bit is set in PSInputAddr but not PSInputEnable is where the
2288         // frontend set up an input arg for a particular interpolation mode, but
2289         // nothing uses that input arg. Really we should have an earlier pass
2290         // that removes such an arg.)
2291         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2292         if ((PsInputBits & 0x7F) == 0 ||
2293             ((PsInputBits & 0xF) == 0 &&
2294              (PsInputBits >> 11 & 1)))
2295           Info->markPSInputEnabled(
2296               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2297       }
2298     }
2299 
2300     assert(!Info->hasDispatchPtr() &&
2301            !Info->hasKernargSegmentPtr() &&
2302            (!Info->hasFlatScratchInit() || Subtarget->enableFlatScratch()) &&
2303            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2304            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2305            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2306            !Info->hasWorkItemIDZ());
2307   } else if (IsKernel) {
2308     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2309   } else {
2310     Splits.append(Ins.begin(), Ins.end());
2311   }
2312 
2313   if (IsEntryFunc) {
2314     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2315     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2316   } else {
2317     // For the fixed ABI, pass workitem IDs in the last argument register.
2318     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2319       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2320   }
2321 
2322   if (IsKernel) {
2323     analyzeFormalArgumentsCompute(CCInfo, Ins);
2324   } else {
2325     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2326     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2327   }
2328 
2329   SmallVector<SDValue, 16> Chains;
2330 
2331   // FIXME: This is the minimum kernel argument alignment. We should improve
2332   // this to the maximum alignment of the arguments.
2333   //
2334   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2335   // kern arg offset.
2336   const Align KernelArgBaseAlign = Align(16);
2337 
2338   for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2339     const ISD::InputArg &Arg = Ins[i];
2340     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2341       InVals.push_back(DAG.getUNDEF(Arg.VT));
2342       continue;
2343     }
2344 
2345     CCValAssign &VA = ArgLocs[ArgIdx++];
2346     MVT VT = VA.getLocVT();
2347 
2348     if (IsEntryFunc && VA.isMemLoc()) {
2349       VT = Ins[i].VT;
2350       EVT MemVT = VA.getLocVT();
2351 
2352       const uint64_t Offset = VA.getLocMemOffset();
2353       Align Alignment = commonAlignment(KernelArgBaseAlign, Offset);
2354 
2355       if (Arg.Flags.isByRef()) {
2356         SDValue Ptr = lowerKernArgParameterPtr(DAG, DL, Chain, Offset);
2357 
2358         const GCNTargetMachine &TM =
2359             static_cast<const GCNTargetMachine &>(getTargetMachine());
2360         if (!TM.isNoopAddrSpaceCast(AMDGPUAS::CONSTANT_ADDRESS,
2361                                     Arg.Flags.getPointerAddrSpace())) {
2362           Ptr = DAG.getAddrSpaceCast(DL, VT, Ptr, AMDGPUAS::CONSTANT_ADDRESS,
2363                                      Arg.Flags.getPointerAddrSpace());
2364         }
2365 
2366         InVals.push_back(Ptr);
2367         continue;
2368       }
2369 
2370       SDValue Arg = lowerKernargMemParameter(
2371         DAG, VT, MemVT, DL, Chain, Offset, Alignment, Ins[i].Flags.isSExt(), &Ins[i]);
2372       Chains.push_back(Arg.getValue(1));
2373 
2374       auto *ParamTy =
2375         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2376       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2377           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2378                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2379         // On SI local pointers are just offsets into LDS, so they are always
2380         // less than 16-bits.  On CI and newer they could potentially be
2381         // real pointers, so we can't guarantee their size.
2382         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2383                           DAG.getValueType(MVT::i16));
2384       }
2385 
2386       InVals.push_back(Arg);
2387       continue;
2388     } else if (!IsEntryFunc && VA.isMemLoc()) {
2389       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2390       InVals.push_back(Val);
2391       if (!Arg.Flags.isByVal())
2392         Chains.push_back(Val.getValue(1));
2393       continue;
2394     }
2395 
2396     assert(VA.isRegLoc() && "Parameter must be in a register!");
2397 
2398     Register Reg = VA.getLocReg();
2399     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2400     EVT ValVT = VA.getValVT();
2401 
2402     Reg = MF.addLiveIn(Reg, RC);
2403     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2404 
2405     if (Arg.Flags.isSRet()) {
2406       // The return object should be reasonably addressable.
2407 
2408       // FIXME: This helps when the return is a real sret. If it is a
2409       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2410       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2411       unsigned NumBits
2412         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2413       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2414         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2415     }
2416 
2417     // If this is an 8 or 16-bit value, it is really passed promoted
2418     // to 32 bits. Insert an assert[sz]ext to capture this, then
2419     // truncate to the right size.
2420     switch (VA.getLocInfo()) {
2421     case CCValAssign::Full:
2422       break;
2423     case CCValAssign::BCvt:
2424       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2425       break;
2426     case CCValAssign::SExt:
2427       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2428                         DAG.getValueType(ValVT));
2429       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2430       break;
2431     case CCValAssign::ZExt:
2432       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2433                         DAG.getValueType(ValVT));
2434       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2435       break;
2436     case CCValAssign::AExt:
2437       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2438       break;
2439     default:
2440       llvm_unreachable("Unknown loc info!");
2441     }
2442 
2443     InVals.push_back(Val);
2444   }
2445 
2446   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2447     // Special inputs come after user arguments.
2448     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2449   }
2450 
2451   // Start adding system SGPRs.
2452   if (IsEntryFunc) {
2453     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2454   } else {
2455     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2456     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2457   }
2458 
2459   auto &ArgUsageInfo =
2460     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2461   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2462 
2463   unsigned StackArgSize = CCInfo.getNextStackOffset();
2464   Info->setBytesInStackArgArea(StackArgSize);
2465 
2466   return Chains.empty() ? Chain :
2467     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2468 }
2469 
2470 // TODO: If return values can't fit in registers, we should return as many as
2471 // possible in registers before passing on stack.
2472 bool SITargetLowering::CanLowerReturn(
2473   CallingConv::ID CallConv,
2474   MachineFunction &MF, bool IsVarArg,
2475   const SmallVectorImpl<ISD::OutputArg> &Outs,
2476   LLVMContext &Context) const {
2477   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2478   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2479   // for shaders. Vector types should be explicitly handled by CC.
2480   if (AMDGPU::isEntryFunctionCC(CallConv))
2481     return true;
2482 
2483   SmallVector<CCValAssign, 16> RVLocs;
2484   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2485   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2486 }
2487 
2488 SDValue
2489 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2490                               bool isVarArg,
2491                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2492                               const SmallVectorImpl<SDValue> &OutVals,
2493                               const SDLoc &DL, SelectionDAG &DAG) const {
2494   MachineFunction &MF = DAG.getMachineFunction();
2495   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2496 
2497   if (AMDGPU::isKernel(CallConv)) {
2498     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2499                                              OutVals, DL, DAG);
2500   }
2501 
2502   bool IsShader = AMDGPU::isShader(CallConv);
2503 
2504   Info->setIfReturnsVoid(Outs.empty());
2505   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2506 
2507   // CCValAssign - represent the assignment of the return value to a location.
2508   SmallVector<CCValAssign, 48> RVLocs;
2509   SmallVector<ISD::OutputArg, 48> Splits;
2510 
2511   // CCState - Info about the registers and stack slots.
2512   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2513                  *DAG.getContext());
2514 
2515   // Analyze outgoing return values.
2516   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2517 
2518   SDValue Flag;
2519   SmallVector<SDValue, 48> RetOps;
2520   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2521 
2522   // Add return address for callable functions.
2523   if (!Info->isEntryFunction()) {
2524     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2525     SDValue ReturnAddrReg = CreateLiveInRegister(
2526       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2527 
2528     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2529         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2530         MVT::i64);
2531     Chain =
2532         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2533     Flag = Chain.getValue(1);
2534     RetOps.push_back(ReturnAddrVirtualReg);
2535   }
2536 
2537   // Copy the result values into the output registers.
2538   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2539        ++I, ++RealRVLocIdx) {
2540     CCValAssign &VA = RVLocs[I];
2541     assert(VA.isRegLoc() && "Can only return in registers!");
2542     // TODO: Partially return in registers if return values don't fit.
2543     SDValue Arg = OutVals[RealRVLocIdx];
2544 
2545     // Copied from other backends.
2546     switch (VA.getLocInfo()) {
2547     case CCValAssign::Full:
2548       break;
2549     case CCValAssign::BCvt:
2550       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2551       break;
2552     case CCValAssign::SExt:
2553       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2554       break;
2555     case CCValAssign::ZExt:
2556       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2557       break;
2558     case CCValAssign::AExt:
2559       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2560       break;
2561     default:
2562       llvm_unreachable("Unknown loc info!");
2563     }
2564 
2565     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2566     Flag = Chain.getValue(1);
2567     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2568   }
2569 
2570   // FIXME: Does sret work properly?
2571   if (!Info->isEntryFunction()) {
2572     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2573     const MCPhysReg *I =
2574       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2575     if (I) {
2576       for (; *I; ++I) {
2577         if (AMDGPU::SReg_64RegClass.contains(*I))
2578           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2579         else if (AMDGPU::SReg_32RegClass.contains(*I))
2580           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2581         else
2582           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2583       }
2584     }
2585   }
2586 
2587   // Update chain and glue.
2588   RetOps[0] = Chain;
2589   if (Flag.getNode())
2590     RetOps.push_back(Flag);
2591 
2592   unsigned Opc = AMDGPUISD::ENDPGM;
2593   if (!IsWaveEnd)
2594     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2595   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2596 }
2597 
2598 SDValue SITargetLowering::LowerCallResult(
2599     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2600     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2601     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2602     SDValue ThisVal) const {
2603   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2604 
2605   // Assign locations to each value returned by this call.
2606   SmallVector<CCValAssign, 16> RVLocs;
2607   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2608                  *DAG.getContext());
2609   CCInfo.AnalyzeCallResult(Ins, RetCC);
2610 
2611   // Copy all of the result registers out of their specified physreg.
2612   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2613     CCValAssign VA = RVLocs[i];
2614     SDValue Val;
2615 
2616     if (VA.isRegLoc()) {
2617       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2618       Chain = Val.getValue(1);
2619       InFlag = Val.getValue(2);
2620     } else if (VA.isMemLoc()) {
2621       report_fatal_error("TODO: return values in memory");
2622     } else
2623       llvm_unreachable("unknown argument location type");
2624 
2625     switch (VA.getLocInfo()) {
2626     case CCValAssign::Full:
2627       break;
2628     case CCValAssign::BCvt:
2629       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2630       break;
2631     case CCValAssign::ZExt:
2632       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2633                         DAG.getValueType(VA.getValVT()));
2634       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2635       break;
2636     case CCValAssign::SExt:
2637       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2638                         DAG.getValueType(VA.getValVT()));
2639       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2640       break;
2641     case CCValAssign::AExt:
2642       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2643       break;
2644     default:
2645       llvm_unreachable("Unknown loc info!");
2646     }
2647 
2648     InVals.push_back(Val);
2649   }
2650 
2651   return Chain;
2652 }
2653 
2654 // Add code to pass special inputs required depending on used features separate
2655 // from the explicit user arguments present in the IR.
2656 void SITargetLowering::passSpecialInputs(
2657     CallLoweringInfo &CLI,
2658     CCState &CCInfo,
2659     const SIMachineFunctionInfo &Info,
2660     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2661     SmallVectorImpl<SDValue> &MemOpChains,
2662     SDValue Chain) const {
2663   // If we don't have a call site, this was a call inserted by
2664   // legalization. These can never use special inputs.
2665   if (!CLI.CB)
2666     return;
2667 
2668   SelectionDAG &DAG = CLI.DAG;
2669   const SDLoc &DL = CLI.DL;
2670 
2671   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2672   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2673 
2674   const AMDGPUFunctionArgInfo *CalleeArgInfo
2675     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2676   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2677     auto &ArgUsageInfo =
2678       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2679     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2680   }
2681 
2682   // TODO: Unify with private memory register handling. This is complicated by
2683   // the fact that at least in kernels, the input argument is not necessarily
2684   // in the same location as the input.
2685   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2686     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2687     AMDGPUFunctionArgInfo::QUEUE_PTR,
2688     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2689     AMDGPUFunctionArgInfo::DISPATCH_ID,
2690     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2691     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2692     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2693   };
2694 
2695   for (auto InputID : InputRegs) {
2696     const ArgDescriptor *OutgoingArg;
2697     const TargetRegisterClass *ArgRC;
2698     LLT ArgTy;
2699 
2700     std::tie(OutgoingArg, ArgRC, ArgTy) =
2701         CalleeArgInfo->getPreloadedValue(InputID);
2702     if (!OutgoingArg)
2703       continue;
2704 
2705     const ArgDescriptor *IncomingArg;
2706     const TargetRegisterClass *IncomingArgRC;
2707     LLT Ty;
2708     std::tie(IncomingArg, IncomingArgRC, Ty) =
2709         CallerArgInfo.getPreloadedValue(InputID);
2710     assert(IncomingArgRC == ArgRC);
2711 
2712     // All special arguments are ints for now.
2713     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2714     SDValue InputReg;
2715 
2716     if (IncomingArg) {
2717       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2718     } else {
2719       // The implicit arg ptr is special because it doesn't have a corresponding
2720       // input for kernels, and is computed from the kernarg segment pointer.
2721       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2722       InputReg = getImplicitArgPtr(DAG, DL);
2723     }
2724 
2725     if (OutgoingArg->isRegister()) {
2726       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2727       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2728         report_fatal_error("failed to allocate implicit input argument");
2729     } else {
2730       unsigned SpecialArgOffset =
2731           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2732       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2733                                               SpecialArgOffset);
2734       MemOpChains.push_back(ArgStore);
2735     }
2736   }
2737 
2738   // Pack workitem IDs into a single register or pass it as is if already
2739   // packed.
2740   const ArgDescriptor *OutgoingArg;
2741   const TargetRegisterClass *ArgRC;
2742   LLT Ty;
2743 
2744   std::tie(OutgoingArg, ArgRC, Ty) =
2745       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2746   if (!OutgoingArg)
2747     std::tie(OutgoingArg, ArgRC, Ty) =
2748         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2749   if (!OutgoingArg)
2750     std::tie(OutgoingArg, ArgRC, Ty) =
2751         CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2752   if (!OutgoingArg)
2753     return;
2754 
2755   const ArgDescriptor *IncomingArgX = std::get<0>(
2756       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X));
2757   const ArgDescriptor *IncomingArgY = std::get<0>(
2758       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y));
2759   const ArgDescriptor *IncomingArgZ = std::get<0>(
2760       CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z));
2761 
2762   SDValue InputReg;
2763   SDLoc SL;
2764 
2765   // If incoming ids are not packed we need to pack them.
2766   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2767     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2768 
2769   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2770     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2771     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2772                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2773     InputReg = InputReg.getNode() ?
2774                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2775   }
2776 
2777   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2778     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2779     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2780                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2781     InputReg = InputReg.getNode() ?
2782                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2783   }
2784 
2785   if (!InputReg.getNode()) {
2786     // Workitem ids are already packed, any of present incoming arguments
2787     // will carry all required fields.
2788     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2789       IncomingArgX ? *IncomingArgX :
2790       IncomingArgY ? *IncomingArgY :
2791                      *IncomingArgZ, ~0u);
2792     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2793   }
2794 
2795   if (OutgoingArg->isRegister()) {
2796     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2797     CCInfo.AllocateReg(OutgoingArg->getRegister());
2798   } else {
2799     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2800     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2801                                             SpecialArgOffset);
2802     MemOpChains.push_back(ArgStore);
2803   }
2804 }
2805 
2806 static bool canGuaranteeTCO(CallingConv::ID CC) {
2807   return CC == CallingConv::Fast;
2808 }
2809 
2810 /// Return true if we might ever do TCO for calls with this calling convention.
2811 static bool mayTailCallThisCC(CallingConv::ID CC) {
2812   switch (CC) {
2813   case CallingConv::C:
2814     return true;
2815   default:
2816     return canGuaranteeTCO(CC);
2817   }
2818 }
2819 
2820 bool SITargetLowering::isEligibleForTailCallOptimization(
2821     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2822     const SmallVectorImpl<ISD::OutputArg> &Outs,
2823     const SmallVectorImpl<SDValue> &OutVals,
2824     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2825   if (!mayTailCallThisCC(CalleeCC))
2826     return false;
2827 
2828   MachineFunction &MF = DAG.getMachineFunction();
2829   const Function &CallerF = MF.getFunction();
2830   CallingConv::ID CallerCC = CallerF.getCallingConv();
2831   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2832   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2833 
2834   // Kernels aren't callable, and don't have a live in return address so it
2835   // doesn't make sense to do a tail call with entry functions.
2836   if (!CallerPreserved)
2837     return false;
2838 
2839   bool CCMatch = CallerCC == CalleeCC;
2840 
2841   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2842     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2843       return true;
2844     return false;
2845   }
2846 
2847   // TODO: Can we handle var args?
2848   if (IsVarArg)
2849     return false;
2850 
2851   for (const Argument &Arg : CallerF.args()) {
2852     if (Arg.hasByValAttr())
2853       return false;
2854   }
2855 
2856   LLVMContext &Ctx = *DAG.getContext();
2857 
2858   // Check that the call results are passed in the same way.
2859   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2860                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2861                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2862     return false;
2863 
2864   // The callee has to preserve all registers the caller needs to preserve.
2865   if (!CCMatch) {
2866     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2867     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2868       return false;
2869   }
2870 
2871   // Nothing more to check if the callee is taking no arguments.
2872   if (Outs.empty())
2873     return true;
2874 
2875   SmallVector<CCValAssign, 16> ArgLocs;
2876   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2877 
2878   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2879 
2880   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2881   // If the stack arguments for this call do not fit into our own save area then
2882   // the call cannot be made tail.
2883   // TODO: Is this really necessary?
2884   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2885     return false;
2886 
2887   const MachineRegisterInfo &MRI = MF.getRegInfo();
2888   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2889 }
2890 
2891 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2892   if (!CI->isTailCall())
2893     return false;
2894 
2895   const Function *ParentFn = CI->getParent()->getParent();
2896   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2897     return false;
2898   return true;
2899 }
2900 
2901 // The wave scratch offset register is used as the global base pointer.
2902 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2903                                     SmallVectorImpl<SDValue> &InVals) const {
2904   SelectionDAG &DAG = CLI.DAG;
2905   const SDLoc &DL = CLI.DL;
2906   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2907   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2908   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2909   SDValue Chain = CLI.Chain;
2910   SDValue Callee = CLI.Callee;
2911   bool &IsTailCall = CLI.IsTailCall;
2912   CallingConv::ID CallConv = CLI.CallConv;
2913   bool IsVarArg = CLI.IsVarArg;
2914   bool IsSibCall = false;
2915   bool IsThisReturn = false;
2916   MachineFunction &MF = DAG.getMachineFunction();
2917 
2918   if (Callee.isUndef() || isNullConstant(Callee)) {
2919     if (!CLI.IsTailCall) {
2920       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2921         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2922     }
2923 
2924     return Chain;
2925   }
2926 
2927   if (IsVarArg) {
2928     return lowerUnhandledCall(CLI, InVals,
2929                               "unsupported call to variadic function ");
2930   }
2931 
2932   if (!CLI.CB)
2933     report_fatal_error("unsupported libcall legalization");
2934 
2935   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2936       !CLI.CB->getCalledFunction()) {
2937     return lowerUnhandledCall(CLI, InVals,
2938                               "unsupported indirect call to function ");
2939   }
2940 
2941   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2942     return lowerUnhandledCall(CLI, InVals,
2943                               "unsupported required tail call to function ");
2944   }
2945 
2946   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2947     // Note the issue is with the CC of the calling function, not of the call
2948     // itself.
2949     return lowerUnhandledCall(CLI, InVals,
2950                           "unsupported call from graphics shader of function ");
2951   }
2952 
2953   if (IsTailCall) {
2954     IsTailCall = isEligibleForTailCallOptimization(
2955       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2956     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2957       report_fatal_error("failed to perform tail call elimination on a call "
2958                          "site marked musttail");
2959     }
2960 
2961     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2962 
2963     // A sibling call is one where we're under the usual C ABI and not planning
2964     // to change that but can still do a tail call:
2965     if (!TailCallOpt && IsTailCall)
2966       IsSibCall = true;
2967 
2968     if (IsTailCall)
2969       ++NumTailCalls;
2970   }
2971 
2972   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2973   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2974   SmallVector<SDValue, 8> MemOpChains;
2975 
2976   // Analyze operands of the call, assigning locations to each operand.
2977   SmallVector<CCValAssign, 16> ArgLocs;
2978   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2979   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2980 
2981   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2982     // With a fixed ABI, allocate fixed registers before user arguments.
2983     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2984   }
2985 
2986   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2987 
2988   // Get a count of how many bytes are to be pushed on the stack.
2989   unsigned NumBytes = CCInfo.getNextStackOffset();
2990 
2991   if (IsSibCall) {
2992     // Since we're not changing the ABI to make this a tail call, the memory
2993     // operands are already available in the caller's incoming argument space.
2994     NumBytes = 0;
2995   }
2996 
2997   // FPDiff is the byte offset of the call's argument area from the callee's.
2998   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2999   // by this amount for a tail call. In a sibling call it must be 0 because the
3000   // caller will deallocate the entire stack and the callee still expects its
3001   // arguments to begin at SP+0. Completely unused for non-tail calls.
3002   int32_t FPDiff = 0;
3003   MachineFrameInfo &MFI = MF.getFrameInfo();
3004 
3005   // Adjust the stack pointer for the new arguments...
3006   // These operations are automatically eliminated by the prolog/epilog pass
3007   if (!IsSibCall) {
3008     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
3009 
3010     SmallVector<SDValue, 4> CopyFromChains;
3011 
3012     // In the HSA case, this should be an identity copy.
3013     SDValue ScratchRSrcReg
3014       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
3015     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
3016     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
3017     Chain = DAG.getTokenFactor(DL, CopyFromChains);
3018   }
3019 
3020   MVT PtrVT = MVT::i32;
3021 
3022   // Walk the register/memloc assignments, inserting copies/loads.
3023   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3024     CCValAssign &VA = ArgLocs[i];
3025     SDValue Arg = OutVals[i];
3026 
3027     // Promote the value if needed.
3028     switch (VA.getLocInfo()) {
3029     case CCValAssign::Full:
3030       break;
3031     case CCValAssign::BCvt:
3032       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
3033       break;
3034     case CCValAssign::ZExt:
3035       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
3036       break;
3037     case CCValAssign::SExt:
3038       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
3039       break;
3040     case CCValAssign::AExt:
3041       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
3042       break;
3043     case CCValAssign::FPExt:
3044       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
3045       break;
3046     default:
3047       llvm_unreachable("Unknown loc info!");
3048     }
3049 
3050     if (VA.isRegLoc()) {
3051       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3052     } else {
3053       assert(VA.isMemLoc());
3054 
3055       SDValue DstAddr;
3056       MachinePointerInfo DstInfo;
3057 
3058       unsigned LocMemOffset = VA.getLocMemOffset();
3059       int32_t Offset = LocMemOffset;
3060 
3061       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
3062       MaybeAlign Alignment;
3063 
3064       if (IsTailCall) {
3065         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3066         unsigned OpSize = Flags.isByVal() ?
3067           Flags.getByValSize() : VA.getValVT().getStoreSize();
3068 
3069         // FIXME: We can have better than the minimum byval required alignment.
3070         Alignment =
3071             Flags.isByVal()
3072                 ? Flags.getNonZeroByValAlign()
3073                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
3074 
3075         Offset = Offset + FPDiff;
3076         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
3077 
3078         DstAddr = DAG.getFrameIndex(FI, PtrVT);
3079         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
3080 
3081         // Make sure any stack arguments overlapping with where we're storing
3082         // are loaded before this eventual operation. Otherwise they'll be
3083         // clobbered.
3084 
3085         // FIXME: Why is this really necessary? This seems to just result in a
3086         // lot of code to copy the stack and write them back to the same
3087         // locations, which are supposed to be immutable?
3088         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
3089       } else {
3090         DstAddr = PtrOff;
3091         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
3092         Alignment =
3093             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
3094       }
3095 
3096       if (Outs[i].Flags.isByVal()) {
3097         SDValue SizeNode =
3098             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
3099         SDValue Cpy =
3100             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
3101                           Outs[i].Flags.getNonZeroByValAlign(),
3102                           /*isVol = */ false, /*AlwaysInline = */ true,
3103                           /*isTailCall = */ false, DstInfo,
3104                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
3105 
3106         MemOpChains.push_back(Cpy);
3107       } else {
3108         SDValue Store =
3109             DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo, Alignment);
3110         MemOpChains.push_back(Store);
3111       }
3112     }
3113   }
3114 
3115   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
3116     // Copy special input registers after user input arguments.
3117     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
3118   }
3119 
3120   if (!MemOpChains.empty())
3121     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3122 
3123   // Build a sequence of copy-to-reg nodes chained together with token chain
3124   // and flag operands which copy the outgoing args into the appropriate regs.
3125   SDValue InFlag;
3126   for (auto &RegToPass : RegsToPass) {
3127     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
3128                              RegToPass.second, InFlag);
3129     InFlag = Chain.getValue(1);
3130   }
3131 
3132 
3133   SDValue PhysReturnAddrReg;
3134   if (IsTailCall) {
3135     // Since the return is being combined with the call, we need to pass on the
3136     // return address.
3137 
3138     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3139     SDValue ReturnAddrReg = CreateLiveInRegister(
3140       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3141 
3142     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3143                                         MVT::i64);
3144     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3145     InFlag = Chain.getValue(1);
3146   }
3147 
3148   // We don't usually want to end the call-sequence here because we would tidy
3149   // the frame up *after* the call, however in the ABI-changing tail-call case
3150   // we've carefully laid out the parameters so that when sp is reset they'll be
3151   // in the correct location.
3152   if (IsTailCall && !IsSibCall) {
3153     Chain = DAG.getCALLSEQ_END(Chain,
3154                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3155                                DAG.getTargetConstant(0, DL, MVT::i32),
3156                                InFlag, DL);
3157     InFlag = Chain.getValue(1);
3158   }
3159 
3160   std::vector<SDValue> Ops;
3161   Ops.push_back(Chain);
3162   Ops.push_back(Callee);
3163   // Add a redundant copy of the callee global which will not be legalized, as
3164   // we need direct access to the callee later.
3165   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3166     const GlobalValue *GV = GSD->getGlobal();
3167     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3168   } else {
3169     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3170   }
3171 
3172   if (IsTailCall) {
3173     // Each tail call may have to adjust the stack by a different amount, so
3174     // this information must travel along with the operation for eventual
3175     // consumption by emitEpilogue.
3176     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3177 
3178     Ops.push_back(PhysReturnAddrReg);
3179   }
3180 
3181   // Add argument registers to the end of the list so that they are known live
3182   // into the call.
3183   for (auto &RegToPass : RegsToPass) {
3184     Ops.push_back(DAG.getRegister(RegToPass.first,
3185                                   RegToPass.second.getValueType()));
3186   }
3187 
3188   // Add a register mask operand representing the call-preserved registers.
3189 
3190   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3191   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3192   assert(Mask && "Missing call preserved mask for calling convention");
3193   Ops.push_back(DAG.getRegisterMask(Mask));
3194 
3195   if (InFlag.getNode())
3196     Ops.push_back(InFlag);
3197 
3198   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3199 
3200   // If we're doing a tall call, use a TC_RETURN here rather than an
3201   // actual call instruction.
3202   if (IsTailCall) {
3203     MFI.setHasTailCall();
3204     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3205   }
3206 
3207   // Returns a chain and a flag for retval copy to use.
3208   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3209   Chain = Call.getValue(0);
3210   InFlag = Call.getValue(1);
3211 
3212   uint64_t CalleePopBytes = NumBytes;
3213   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3214                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3215                              InFlag, DL);
3216   if (!Ins.empty())
3217     InFlag = Chain.getValue(1);
3218 
3219   // Handle result values, copying them out of physregs into vregs that we
3220   // return.
3221   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3222                          InVals, IsThisReturn,
3223                          IsThisReturn ? OutVals[0] : SDValue());
3224 }
3225 
3226 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3227 // except for applying the wave size scale to the increment amount.
3228 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3229     SDValue Op, SelectionDAG &DAG) const {
3230   const MachineFunction &MF = DAG.getMachineFunction();
3231   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3232 
3233   SDLoc dl(Op);
3234   EVT VT = Op.getValueType();
3235   SDValue Tmp1 = Op;
3236   SDValue Tmp2 = Op.getValue(1);
3237   SDValue Tmp3 = Op.getOperand(2);
3238   SDValue Chain = Tmp1.getOperand(0);
3239 
3240   Register SPReg = Info->getStackPtrOffsetReg();
3241 
3242   // Chain the dynamic stack allocation so that it doesn't modify the stack
3243   // pointer when other instructions are using the stack.
3244   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3245 
3246   SDValue Size  = Tmp2.getOperand(1);
3247   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3248   Chain = SP.getValue(1);
3249   MaybeAlign Alignment = cast<ConstantSDNode>(Tmp3)->getMaybeAlignValue();
3250   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3251   const TargetFrameLowering *TFL = ST.getFrameLowering();
3252   unsigned Opc =
3253     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3254     ISD::ADD : ISD::SUB;
3255 
3256   SDValue ScaledSize = DAG.getNode(
3257       ISD::SHL, dl, VT, Size,
3258       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3259 
3260   Align StackAlign = TFL->getStackAlign();
3261   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3262   if (Alignment && *Alignment > StackAlign) {
3263     Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
3264                        DAG.getConstant(-(uint64_t)Alignment->value()
3265                                            << ST.getWavefrontSizeLog2(),
3266                                        dl, VT));
3267   }
3268 
3269   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3270   Tmp2 = DAG.getCALLSEQ_END(
3271       Chain, DAG.getIntPtrConstant(0, dl, true),
3272       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3273 
3274   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3275 }
3276 
3277 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3278                                                   SelectionDAG &DAG) const {
3279   // We only handle constant sizes here to allow non-entry block, static sized
3280   // allocas. A truly dynamic value is more difficult to support because we
3281   // don't know if the size value is uniform or not. If the size isn't uniform,
3282   // we would need to do a wave reduction to get the maximum size to know how
3283   // much to increment the uniform stack pointer.
3284   SDValue Size = Op.getOperand(1);
3285   if (isa<ConstantSDNode>(Size))
3286       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3287 
3288   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3289 }
3290 
3291 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3292                                              const MachineFunction &MF) const {
3293   Register Reg = StringSwitch<Register>(RegName)
3294     .Case("m0", AMDGPU::M0)
3295     .Case("exec", AMDGPU::EXEC)
3296     .Case("exec_lo", AMDGPU::EXEC_LO)
3297     .Case("exec_hi", AMDGPU::EXEC_HI)
3298     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3299     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3300     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3301     .Default(Register());
3302 
3303   if (Reg == AMDGPU::NoRegister) {
3304     report_fatal_error(Twine("invalid register name \""
3305                              + StringRef(RegName)  + "\"."));
3306 
3307   }
3308 
3309   if (!Subtarget->hasFlatScrRegister() &&
3310        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3311     report_fatal_error(Twine("invalid register \""
3312                              + StringRef(RegName)  + "\" for subtarget."));
3313   }
3314 
3315   switch (Reg) {
3316   case AMDGPU::M0:
3317   case AMDGPU::EXEC_LO:
3318   case AMDGPU::EXEC_HI:
3319   case AMDGPU::FLAT_SCR_LO:
3320   case AMDGPU::FLAT_SCR_HI:
3321     if (VT.getSizeInBits() == 32)
3322       return Reg;
3323     break;
3324   case AMDGPU::EXEC:
3325   case AMDGPU::FLAT_SCR:
3326     if (VT.getSizeInBits() == 64)
3327       return Reg;
3328     break;
3329   default:
3330     llvm_unreachable("missing register type checking");
3331   }
3332 
3333   report_fatal_error(Twine("invalid type for register \""
3334                            + StringRef(RegName) + "\"."));
3335 }
3336 
3337 // If kill is not the last instruction, split the block so kill is always a
3338 // proper terminator.
3339 MachineBasicBlock *
3340 SITargetLowering::splitKillBlock(MachineInstr &MI,
3341                                  MachineBasicBlock *BB) const {
3342   MachineBasicBlock *SplitBB = BB->splitAt(MI, false /*UpdateLiveIns*/);
3343   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3344   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3345   return SplitBB;
3346 }
3347 
3348 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3349 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3350 // be the first instruction in the remainder block.
3351 //
3352 /// \returns { LoopBody, Remainder }
3353 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3354 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3355   MachineFunction *MF = MBB.getParent();
3356   MachineBasicBlock::iterator I(&MI);
3357 
3358   // To insert the loop we need to split the block. Move everything after this
3359   // point to a new block, and insert a new empty block between the two.
3360   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3361   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3362   MachineFunction::iterator MBBI(MBB);
3363   ++MBBI;
3364 
3365   MF->insert(MBBI, LoopBB);
3366   MF->insert(MBBI, RemainderBB);
3367 
3368   LoopBB->addSuccessor(LoopBB);
3369   LoopBB->addSuccessor(RemainderBB);
3370 
3371   // Move the rest of the block into a new block.
3372   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3373 
3374   if (InstInLoop) {
3375     auto Next = std::next(I);
3376 
3377     // Move instruction to loop body.
3378     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3379 
3380     // Move the rest of the block.
3381     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3382   } else {
3383     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3384   }
3385 
3386   MBB.addSuccessor(LoopBB);
3387 
3388   return std::make_pair(LoopBB, RemainderBB);
3389 }
3390 
3391 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3392 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3393   MachineBasicBlock *MBB = MI.getParent();
3394   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3395   auto I = MI.getIterator();
3396   auto E = std::next(I);
3397 
3398   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3399     .addImm(0);
3400 
3401   MIBundleBuilder Bundler(*MBB, I, E);
3402   finalizeBundle(*MBB, Bundler.begin());
3403 }
3404 
3405 MachineBasicBlock *
3406 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3407                                          MachineBasicBlock *BB) const {
3408   const DebugLoc &DL = MI.getDebugLoc();
3409 
3410   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3411 
3412   MachineBasicBlock *LoopBB;
3413   MachineBasicBlock *RemainderBB;
3414   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3415 
3416   // Apparently kill flags are only valid if the def is in the same block?
3417   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3418     Src->setIsKill(false);
3419 
3420   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3421 
3422   MachineBasicBlock::iterator I = LoopBB->end();
3423 
3424   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3425     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3426 
3427   // Clear TRAP_STS.MEM_VIOL
3428   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3429     .addImm(0)
3430     .addImm(EncodedReg);
3431 
3432   bundleInstWithWaitcnt(MI);
3433 
3434   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3435 
3436   // Load and check TRAP_STS.MEM_VIOL
3437   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3438     .addImm(EncodedReg);
3439 
3440   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3441   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3442     .addReg(Reg, RegState::Kill)
3443     .addImm(0);
3444   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3445     .addMBB(LoopBB);
3446 
3447   return RemainderBB;
3448 }
3449 
3450 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3451 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3452 // will only do one iteration. In the worst case, this will loop 64 times.
3453 //
3454 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3455 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3456   const SIInstrInfo *TII,
3457   MachineRegisterInfo &MRI,
3458   MachineBasicBlock &OrigBB,
3459   MachineBasicBlock &LoopBB,
3460   const DebugLoc &DL,
3461   const MachineOperand &IdxReg,
3462   unsigned InitReg,
3463   unsigned ResultReg,
3464   unsigned PhiReg,
3465   unsigned InitSaveExecReg,
3466   int Offset,
3467   bool UseGPRIdxMode,
3468   bool IsIndirectSrc) {
3469   MachineFunction *MF = OrigBB.getParent();
3470   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3471   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3472   MachineBasicBlock::iterator I = LoopBB.begin();
3473 
3474   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3475   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3476   Register NewExec = MRI.createVirtualRegister(BoolRC);
3477   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3478   Register CondReg = MRI.createVirtualRegister(BoolRC);
3479 
3480   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3481     .addReg(InitReg)
3482     .addMBB(&OrigBB)
3483     .addReg(ResultReg)
3484     .addMBB(&LoopBB);
3485 
3486   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3487     .addReg(InitSaveExecReg)
3488     .addMBB(&OrigBB)
3489     .addReg(NewExec)
3490     .addMBB(&LoopBB);
3491 
3492   // Read the next variant <- also loop target.
3493   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3494     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3495 
3496   // Compare the just read M0 value to all possible Idx values.
3497   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3498     .addReg(CurrentIdxReg)
3499     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3500 
3501   // Update EXEC, save the original EXEC value to VCC.
3502   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3503                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3504           NewExec)
3505     .addReg(CondReg, RegState::Kill);
3506 
3507   MRI.setSimpleHint(NewExec, CondReg);
3508 
3509   if (UseGPRIdxMode) {
3510     unsigned IdxReg;
3511     if (Offset == 0) {
3512       IdxReg = CurrentIdxReg;
3513     } else {
3514       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3515       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3516         .addReg(CurrentIdxReg, RegState::Kill)
3517         .addImm(Offset);
3518     }
3519     unsigned IdxMode = IsIndirectSrc ?
3520       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3521     MachineInstr *SetOn =
3522       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3523       .addReg(IdxReg, RegState::Kill)
3524       .addImm(IdxMode);
3525     SetOn->getOperand(3).setIsUndef();
3526   } else {
3527     // Move index from VCC into M0
3528     if (Offset == 0) {
3529       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3530         .addReg(CurrentIdxReg, RegState::Kill);
3531     } else {
3532       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3533         .addReg(CurrentIdxReg, RegState::Kill)
3534         .addImm(Offset);
3535     }
3536   }
3537 
3538   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3539   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3540   MachineInstr *InsertPt =
3541     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3542                                                   : AMDGPU::S_XOR_B64_term), Exec)
3543       .addReg(Exec)
3544       .addReg(NewExec);
3545 
3546   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3547   // s_cbranch_scc0?
3548 
3549   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3550   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3551     .addMBB(&LoopBB);
3552 
3553   return InsertPt->getIterator();
3554 }
3555 
3556 // This has slightly sub-optimal regalloc when the source vector is killed by
3557 // the read. The register allocator does not understand that the kill is
3558 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3559 // subregister from it, using 1 more VGPR than necessary. This was saved when
3560 // this was expanded after register allocation.
3561 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3562                                                   MachineBasicBlock &MBB,
3563                                                   MachineInstr &MI,
3564                                                   unsigned InitResultReg,
3565                                                   unsigned PhiReg,
3566                                                   int Offset,
3567                                                   bool UseGPRIdxMode,
3568                                                   bool IsIndirectSrc) {
3569   MachineFunction *MF = MBB.getParent();
3570   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3571   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3572   MachineRegisterInfo &MRI = MF->getRegInfo();
3573   const DebugLoc &DL = MI.getDebugLoc();
3574   MachineBasicBlock::iterator I(&MI);
3575 
3576   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3577   Register DstReg = MI.getOperand(0).getReg();
3578   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3579   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3580   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3581   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3582 
3583   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3584 
3585   // Save the EXEC mask
3586   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3587     .addReg(Exec);
3588 
3589   MachineBasicBlock *LoopBB;
3590   MachineBasicBlock *RemainderBB;
3591   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3592 
3593   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3594 
3595   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3596                                       InitResultReg, DstReg, PhiReg, TmpExec,
3597                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3598   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3599   MachineFunction::iterator MBBI(LoopBB);
3600   ++MBBI;
3601   MF->insert(MBBI, LandingPad);
3602   LoopBB->removeSuccessor(RemainderBB);
3603   LandingPad->addSuccessor(RemainderBB);
3604   LoopBB->addSuccessor(LandingPad);
3605   MachineBasicBlock::iterator First = LandingPad->begin();
3606   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3607     .addReg(SaveExec);
3608 
3609   return InsPt;
3610 }
3611 
3612 // Returns subreg index, offset
3613 static std::pair<unsigned, int>
3614 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3615                             const TargetRegisterClass *SuperRC,
3616                             unsigned VecReg,
3617                             int Offset) {
3618   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3619 
3620   // Skip out of bounds offsets, or else we would end up using an undefined
3621   // register.
3622   if (Offset >= NumElts || Offset < 0)
3623     return std::make_pair(AMDGPU::sub0, Offset);
3624 
3625   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3626 }
3627 
3628 // Return true if the index is an SGPR and was set.
3629 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3630                                  MachineRegisterInfo &MRI,
3631                                  MachineInstr &MI,
3632                                  int Offset,
3633                                  bool UseGPRIdxMode,
3634                                  bool IsIndirectSrc) {
3635   MachineBasicBlock *MBB = MI.getParent();
3636   const DebugLoc &DL = MI.getDebugLoc();
3637   MachineBasicBlock::iterator I(&MI);
3638 
3639   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3640   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3641 
3642   assert(Idx->getReg() != AMDGPU::NoRegister);
3643 
3644   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3645     return false;
3646 
3647   if (UseGPRIdxMode) {
3648     unsigned IdxMode = IsIndirectSrc ?
3649       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3650     if (Offset == 0) {
3651       MachineInstr *SetOn =
3652           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3653               .add(*Idx)
3654               .addImm(IdxMode);
3655 
3656       SetOn->getOperand(3).setIsUndef();
3657     } else {
3658       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3659       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3660           .add(*Idx)
3661           .addImm(Offset);
3662       MachineInstr *SetOn =
3663         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3664         .addReg(Tmp, RegState::Kill)
3665         .addImm(IdxMode);
3666 
3667       SetOn->getOperand(3).setIsUndef();
3668     }
3669 
3670     return true;
3671   }
3672 
3673   if (Offset == 0) {
3674     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3675       .add(*Idx);
3676   } else {
3677     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3678       .add(*Idx)
3679       .addImm(Offset);
3680   }
3681 
3682   return true;
3683 }
3684 
3685 // Control flow needs to be inserted if indexing with a VGPR.
3686 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3687                                           MachineBasicBlock &MBB,
3688                                           const GCNSubtarget &ST) {
3689   const SIInstrInfo *TII = ST.getInstrInfo();
3690   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3691   MachineFunction *MF = MBB.getParent();
3692   MachineRegisterInfo &MRI = MF->getRegInfo();
3693 
3694   Register Dst = MI.getOperand(0).getReg();
3695   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3696   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3697 
3698   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3699 
3700   unsigned SubReg;
3701   std::tie(SubReg, Offset)
3702     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3703 
3704   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3705 
3706   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3707     MachineBasicBlock::iterator I(&MI);
3708     const DebugLoc &DL = MI.getDebugLoc();
3709 
3710     if (UseGPRIdxMode) {
3711       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3712       // to avoid interfering with other uses, so probably requires a new
3713       // optimization pass.
3714       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3715         .addReg(SrcReg, 0, SubReg)
3716         .addReg(SrcReg, RegState::Implicit)
3717         .addReg(AMDGPU::M0, RegState::Implicit);
3718       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3719     } else {
3720       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3721         .addReg(SrcReg, 0, SubReg)
3722         .addReg(SrcReg, RegState::Implicit);
3723     }
3724 
3725     MI.eraseFromParent();
3726 
3727     return &MBB;
3728   }
3729 
3730   const DebugLoc &DL = MI.getDebugLoc();
3731   MachineBasicBlock::iterator I(&MI);
3732 
3733   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3734   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3735 
3736   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3737 
3738   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3739                               Offset, UseGPRIdxMode, true);
3740   MachineBasicBlock *LoopBB = InsPt->getParent();
3741 
3742   if (UseGPRIdxMode) {
3743     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3744       .addReg(SrcReg, 0, SubReg)
3745       .addReg(SrcReg, RegState::Implicit)
3746       .addReg(AMDGPU::M0, RegState::Implicit);
3747     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3748   } else {
3749     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3750       .addReg(SrcReg, 0, SubReg)
3751       .addReg(SrcReg, RegState::Implicit);
3752   }
3753 
3754   MI.eraseFromParent();
3755 
3756   return LoopBB;
3757 }
3758 
3759 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3760                                           MachineBasicBlock &MBB,
3761                                           const GCNSubtarget &ST) {
3762   const SIInstrInfo *TII = ST.getInstrInfo();
3763   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3764   MachineFunction *MF = MBB.getParent();
3765   MachineRegisterInfo &MRI = MF->getRegInfo();
3766 
3767   Register Dst = MI.getOperand(0).getReg();
3768   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3769   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3770   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3771   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3772   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3773 
3774   // This can be an immediate, but will be folded later.
3775   assert(Val->getReg());
3776 
3777   unsigned SubReg;
3778   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3779                                                          SrcVec->getReg(),
3780                                                          Offset);
3781   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3782 
3783   if (Idx->getReg() == AMDGPU::NoRegister) {
3784     MachineBasicBlock::iterator I(&MI);
3785     const DebugLoc &DL = MI.getDebugLoc();
3786 
3787     assert(Offset == 0);
3788 
3789     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3790         .add(*SrcVec)
3791         .add(*Val)
3792         .addImm(SubReg);
3793 
3794     MI.eraseFromParent();
3795     return &MBB;
3796   }
3797 
3798   const MCInstrDesc &MovRelDesc
3799     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3800 
3801   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3802     MachineBasicBlock::iterator I(&MI);
3803     const DebugLoc &DL = MI.getDebugLoc();
3804     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3805       .addReg(SrcVec->getReg())
3806       .add(*Val)
3807       .addImm(SubReg);
3808     if (UseGPRIdxMode)
3809       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3810 
3811     MI.eraseFromParent();
3812     return &MBB;
3813   }
3814 
3815   if (Val->isReg())
3816     MRI.clearKillFlags(Val->getReg());
3817 
3818   const DebugLoc &DL = MI.getDebugLoc();
3819 
3820   Register PhiReg = MRI.createVirtualRegister(VecRC);
3821 
3822   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3823                               Offset, UseGPRIdxMode, false);
3824   MachineBasicBlock *LoopBB = InsPt->getParent();
3825 
3826   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3827     .addReg(PhiReg)
3828     .add(*Val)
3829     .addImm(AMDGPU::sub0);
3830   if (UseGPRIdxMode)
3831     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3832 
3833   MI.eraseFromParent();
3834   return LoopBB;
3835 }
3836 
3837 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3838   MachineInstr &MI, MachineBasicBlock *BB) const {
3839 
3840   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3841   MachineFunction *MF = BB->getParent();
3842   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3843 
3844   switch (MI.getOpcode()) {
3845   case AMDGPU::S_UADDO_PSEUDO:
3846   case AMDGPU::S_USUBO_PSEUDO: {
3847     const DebugLoc &DL = MI.getDebugLoc();
3848     MachineOperand &Dest0 = MI.getOperand(0);
3849     MachineOperand &Dest1 = MI.getOperand(1);
3850     MachineOperand &Src0 = MI.getOperand(2);
3851     MachineOperand &Src1 = MI.getOperand(3);
3852 
3853     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3854                        ? AMDGPU::S_ADD_I32
3855                        : AMDGPU::S_SUB_I32;
3856     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3857 
3858     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3859         .addImm(1)
3860         .addImm(0);
3861 
3862     MI.eraseFromParent();
3863     return BB;
3864   }
3865   case AMDGPU::S_ADD_U64_PSEUDO:
3866   case AMDGPU::S_SUB_U64_PSEUDO: {
3867     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3868     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3869     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3870     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3871     const DebugLoc &DL = MI.getDebugLoc();
3872 
3873     MachineOperand &Dest = MI.getOperand(0);
3874     MachineOperand &Src0 = MI.getOperand(1);
3875     MachineOperand &Src1 = MI.getOperand(2);
3876 
3877     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3878     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3879 
3880     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3881         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3882     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3883         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3884 
3885     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3886         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3887     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3888         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3889 
3890     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3891 
3892     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3893     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3894     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3895     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3896     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3897         .addReg(DestSub0)
3898         .addImm(AMDGPU::sub0)
3899         .addReg(DestSub1)
3900         .addImm(AMDGPU::sub1);
3901     MI.eraseFromParent();
3902     return BB;
3903   }
3904   case AMDGPU::V_ADD_U64_PSEUDO:
3905   case AMDGPU::V_SUB_U64_PSEUDO: {
3906     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3907     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3908     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3909     const DebugLoc &DL = MI.getDebugLoc();
3910 
3911     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3912 
3913     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3914 
3915     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3916     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3917 
3918     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3919     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3920 
3921     MachineOperand &Dest = MI.getOperand(0);
3922     MachineOperand &Src0 = MI.getOperand(1);
3923     MachineOperand &Src1 = MI.getOperand(2);
3924 
3925     const TargetRegisterClass *Src0RC = Src0.isReg()
3926                                             ? MRI.getRegClass(Src0.getReg())
3927                                             : &AMDGPU::VReg_64RegClass;
3928     const TargetRegisterClass *Src1RC = Src1.isReg()
3929                                             ? MRI.getRegClass(Src1.getReg())
3930                                             : &AMDGPU::VReg_64RegClass;
3931 
3932     const TargetRegisterClass *Src0SubRC =
3933         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3934     const TargetRegisterClass *Src1SubRC =
3935         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3936 
3937     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3938         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3939     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3940         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3941 
3942     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3943         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3944     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3945         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3946 
3947     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_CO_U32_e64 : AMDGPU::V_SUB_CO_U32_e64;
3948     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3949                                .addReg(CarryReg, RegState::Define)
3950                                .add(SrcReg0Sub0)
3951                                .add(SrcReg1Sub0)
3952                                .addImm(0); // clamp bit
3953 
3954     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3955     MachineInstr *HiHalf =
3956         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3957             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3958             .add(SrcReg0Sub1)
3959             .add(SrcReg1Sub1)
3960             .addReg(CarryReg, RegState::Kill)
3961             .addImm(0); // clamp bit
3962 
3963     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3964         .addReg(DestSub0)
3965         .addImm(AMDGPU::sub0)
3966         .addReg(DestSub1)
3967         .addImm(AMDGPU::sub1);
3968     TII->legalizeOperands(*LoHalf);
3969     TII->legalizeOperands(*HiHalf);
3970     MI.eraseFromParent();
3971     return BB;
3972   }
3973   case AMDGPU::S_ADD_CO_PSEUDO:
3974   case AMDGPU::S_SUB_CO_PSEUDO: {
3975     // This pseudo has a chance to be selected
3976     // only from uniform add/subcarry node. All the VGPR operands
3977     // therefore assumed to be splat vectors.
3978     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3979     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3980     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3981     MachineBasicBlock::iterator MII = MI;
3982     const DebugLoc &DL = MI.getDebugLoc();
3983     MachineOperand &Dest = MI.getOperand(0);
3984     MachineOperand &CarryDest = MI.getOperand(1);
3985     MachineOperand &Src0 = MI.getOperand(2);
3986     MachineOperand &Src1 = MI.getOperand(3);
3987     MachineOperand &Src2 = MI.getOperand(4);
3988     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3989                        ? AMDGPU::S_ADDC_U32
3990                        : AMDGPU::S_SUBB_U32;
3991     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3992       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3993       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3994           .addReg(Src0.getReg());
3995       Src0.setReg(RegOp0);
3996     }
3997     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3998       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3999       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
4000           .addReg(Src1.getReg());
4001       Src1.setReg(RegOp1);
4002     }
4003     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4004     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
4005       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
4006           .addReg(Src2.getReg());
4007       Src2.setReg(RegOp2);
4008     }
4009 
4010     const TargetRegisterClass *Src2RC = MRI.getRegClass(Src2.getReg());
4011     if (TRI->getRegSizeInBits(*Src2RC) == 64) {
4012       if (ST.hasScalarCompareEq64()) {
4013         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
4014             .addReg(Src2.getReg())
4015             .addImm(0);
4016       } else {
4017         const TargetRegisterClass *SubRC =
4018             TRI->getSubRegClass(Src2RC, AMDGPU::sub0);
4019         MachineOperand Src2Sub0 = TII->buildExtractSubRegOrImm(
4020             MII, MRI, Src2, Src2RC, AMDGPU::sub0, SubRC);
4021         MachineOperand Src2Sub1 = TII->buildExtractSubRegOrImm(
4022             MII, MRI, Src2, Src2RC, AMDGPU::sub1, SubRC);
4023         Register Src2_32 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
4024 
4025         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_OR_B32), Src2_32)
4026             .add(Src2Sub0)
4027             .add(Src2Sub1);
4028 
4029         BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U32))
4030             .addReg(Src2_32, RegState::Kill)
4031             .addImm(0);
4032       }
4033     } else {
4034       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
4035           .addReg(Src2.getReg())
4036           .addImm(0);
4037     }
4038 
4039     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
4040 
4041     BuildMI(*BB, MII, DL, TII->get(AMDGPU::COPY), CarryDest.getReg())
4042       .addReg(AMDGPU::SCC);
4043     MI.eraseFromParent();
4044     return BB;
4045   }
4046   case AMDGPU::SI_INIT_M0: {
4047     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
4048             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
4049         .add(MI.getOperand(0));
4050     MI.eraseFromParent();
4051     return BB;
4052   }
4053   case AMDGPU::SI_INIT_EXEC:
4054     // This should be before all vector instructions.
4055     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
4056             AMDGPU::EXEC)
4057         .addImm(MI.getOperand(0).getImm());
4058     MI.eraseFromParent();
4059     return BB;
4060 
4061   case AMDGPU::SI_INIT_EXEC_LO:
4062     // This should be before all vector instructions.
4063     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
4064             AMDGPU::EXEC_LO)
4065         .addImm(MI.getOperand(0).getImm());
4066     MI.eraseFromParent();
4067     return BB;
4068 
4069   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
4070     // Extract the thread count from an SGPR input and set EXEC accordingly.
4071     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
4072     //
4073     // S_BFE_U32 count, input, {shift, 7}
4074     // S_BFM_B64 exec, count, 0
4075     // S_CMP_EQ_U32 count, 64
4076     // S_CMOV_B64 exec, -1
4077     MachineInstr *FirstMI = &*BB->begin();
4078     MachineRegisterInfo &MRI = MF->getRegInfo();
4079     Register InputReg = MI.getOperand(0).getReg();
4080     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
4081     bool Found = false;
4082 
4083     // Move the COPY of the input reg to the beginning, so that we can use it.
4084     for (auto I = BB->begin(); I != &MI; I++) {
4085       if (I->getOpcode() != TargetOpcode::COPY ||
4086           I->getOperand(0).getReg() != InputReg)
4087         continue;
4088 
4089       if (I == FirstMI) {
4090         FirstMI = &*++BB->begin();
4091       } else {
4092         I->removeFromParent();
4093         BB->insert(FirstMI, &*I);
4094       }
4095       Found = true;
4096       break;
4097     }
4098     assert(Found);
4099     (void)Found;
4100 
4101     // This should be before all vector instructions.
4102     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
4103     bool isWave32 = getSubtarget()->isWave32();
4104     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
4105     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
4106         .addReg(InputReg)
4107         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
4108     BuildMI(*BB, FirstMI, DebugLoc(),
4109             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
4110             Exec)
4111         .addReg(CountReg)
4112         .addImm(0);
4113     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
4114         .addReg(CountReg, RegState::Kill)
4115         .addImm(getSubtarget()->getWavefrontSize());
4116     BuildMI(*BB, FirstMI, DebugLoc(),
4117             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
4118             Exec)
4119         .addImm(-1);
4120     MI.eraseFromParent();
4121     return BB;
4122   }
4123 
4124   case AMDGPU::GET_GROUPSTATICSIZE: {
4125     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
4126            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
4127     DebugLoc DL = MI.getDebugLoc();
4128     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
4129         .add(MI.getOperand(0))
4130         .addImm(MFI->getLDSSize());
4131     MI.eraseFromParent();
4132     return BB;
4133   }
4134   case AMDGPU::SI_INDIRECT_SRC_V1:
4135   case AMDGPU::SI_INDIRECT_SRC_V2:
4136   case AMDGPU::SI_INDIRECT_SRC_V4:
4137   case AMDGPU::SI_INDIRECT_SRC_V8:
4138   case AMDGPU::SI_INDIRECT_SRC_V16:
4139   case AMDGPU::SI_INDIRECT_SRC_V32:
4140     return emitIndirectSrc(MI, *BB, *getSubtarget());
4141   case AMDGPU::SI_INDIRECT_DST_V1:
4142   case AMDGPU::SI_INDIRECT_DST_V2:
4143   case AMDGPU::SI_INDIRECT_DST_V4:
4144   case AMDGPU::SI_INDIRECT_DST_V8:
4145   case AMDGPU::SI_INDIRECT_DST_V16:
4146   case AMDGPU::SI_INDIRECT_DST_V32:
4147     return emitIndirectDst(MI, *BB, *getSubtarget());
4148   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4149   case AMDGPU::SI_KILL_I1_PSEUDO:
4150     return splitKillBlock(MI, BB);
4151   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4152     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4153     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4154     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4155 
4156     Register Dst = MI.getOperand(0).getReg();
4157     Register Src0 = MI.getOperand(1).getReg();
4158     Register Src1 = MI.getOperand(2).getReg();
4159     const DebugLoc &DL = MI.getDebugLoc();
4160     Register SrcCond = MI.getOperand(3).getReg();
4161 
4162     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4163     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4164     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4165     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4166 
4167     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4168       .addReg(SrcCond);
4169     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4170       .addImm(0)
4171       .addReg(Src0, 0, AMDGPU::sub0)
4172       .addImm(0)
4173       .addReg(Src1, 0, AMDGPU::sub0)
4174       .addReg(SrcCondCopy);
4175     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4176       .addImm(0)
4177       .addReg(Src0, 0, AMDGPU::sub1)
4178       .addImm(0)
4179       .addReg(Src1, 0, AMDGPU::sub1)
4180       .addReg(SrcCondCopy);
4181 
4182     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4183       .addReg(DstLo)
4184       .addImm(AMDGPU::sub0)
4185       .addReg(DstHi)
4186       .addImm(AMDGPU::sub1);
4187     MI.eraseFromParent();
4188     return BB;
4189   }
4190   case AMDGPU::SI_BR_UNDEF: {
4191     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4192     const DebugLoc &DL = MI.getDebugLoc();
4193     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4194                            .add(MI.getOperand(0));
4195     Br->getOperand(1).setIsUndef(true); // read undef SCC
4196     MI.eraseFromParent();
4197     return BB;
4198   }
4199   case AMDGPU::ADJCALLSTACKUP:
4200   case AMDGPU::ADJCALLSTACKDOWN: {
4201     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4202     MachineInstrBuilder MIB(*MF, &MI);
4203     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4204        .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit);
4205     return BB;
4206   }
4207   case AMDGPU::SI_CALL_ISEL: {
4208     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4209     const DebugLoc &DL = MI.getDebugLoc();
4210 
4211     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4212 
4213     MachineInstrBuilder MIB;
4214     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4215 
4216     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4217       MIB.add(MI.getOperand(I));
4218 
4219     MIB.cloneMemRefs(MI);
4220     MI.eraseFromParent();
4221     return BB;
4222   }
4223   case AMDGPU::V_ADD_CO_U32_e32:
4224   case AMDGPU::V_SUB_CO_U32_e32:
4225   case AMDGPU::V_SUBREV_CO_U32_e32: {
4226     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4227     const DebugLoc &DL = MI.getDebugLoc();
4228     unsigned Opc = MI.getOpcode();
4229 
4230     bool NeedClampOperand = false;
4231     if (TII->pseudoToMCOpcode(Opc) == -1) {
4232       Opc = AMDGPU::getVOPe64(Opc);
4233       NeedClampOperand = true;
4234     }
4235 
4236     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4237     if (TII->isVOP3(*I)) {
4238       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4239       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4240       I.addReg(TRI->getVCC(), RegState::Define);
4241     }
4242     I.add(MI.getOperand(1))
4243      .add(MI.getOperand(2));
4244     if (NeedClampOperand)
4245       I.addImm(0); // clamp bit for e64 encoding
4246 
4247     TII->legalizeOperands(*I);
4248 
4249     MI.eraseFromParent();
4250     return BB;
4251   }
4252   case AMDGPU::DS_GWS_INIT:
4253   case AMDGPU::DS_GWS_SEMA_V:
4254   case AMDGPU::DS_GWS_SEMA_BR:
4255   case AMDGPU::DS_GWS_SEMA_P:
4256   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4257   case AMDGPU::DS_GWS_BARRIER:
4258     // A s_waitcnt 0 is required to be the instruction immediately following.
4259     if (getSubtarget()->hasGWSAutoReplay()) {
4260       bundleInstWithWaitcnt(MI);
4261       return BB;
4262     }
4263 
4264     return emitGWSMemViolTestLoop(MI, BB);
4265   case AMDGPU::S_SETREG_B32: {
4266     // Try to optimize cases that only set the denormal mode or rounding mode.
4267     //
4268     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4269     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4270     // instead.
4271     //
4272     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4273     // allow you to have a no side effect instruction in the output of a
4274     // sideeffecting pattern.
4275     unsigned ID, Offset, Width;
4276     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4277     if (ID != AMDGPU::Hwreg::ID_MODE)
4278       return BB;
4279 
4280     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4281     const unsigned SetMask = WidthMask << Offset;
4282 
4283     if (getSubtarget()->hasDenormModeInst()) {
4284       unsigned SetDenormOp = 0;
4285       unsigned SetRoundOp = 0;
4286 
4287       // The dedicated instructions can only set the whole denorm or round mode
4288       // at once, not a subset of bits in either.
4289       if (SetMask ==
4290           (AMDGPU::Hwreg::FP_ROUND_MASK | AMDGPU::Hwreg::FP_DENORM_MASK)) {
4291         // If this fully sets both the round and denorm mode, emit the two
4292         // dedicated instructions for these.
4293         SetRoundOp = AMDGPU::S_ROUND_MODE;
4294         SetDenormOp = AMDGPU::S_DENORM_MODE;
4295       } else if (SetMask == AMDGPU::Hwreg::FP_ROUND_MASK) {
4296         SetRoundOp = AMDGPU::S_ROUND_MODE;
4297       } else if (SetMask == AMDGPU::Hwreg::FP_DENORM_MASK) {
4298         SetDenormOp = AMDGPU::S_DENORM_MODE;
4299       }
4300 
4301       if (SetRoundOp || SetDenormOp) {
4302         MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4303         MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4304         if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4305           unsigned ImmVal = Def->getOperand(1).getImm();
4306           if (SetRoundOp) {
4307             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4308                 .addImm(ImmVal & 0xf);
4309 
4310             // If we also have the denorm mode, get just the denorm mode bits.
4311             ImmVal >>= 4;
4312           }
4313 
4314           if (SetDenormOp) {
4315             BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4316                 .addImm(ImmVal & 0xf);
4317           }
4318 
4319           MI.eraseFromParent();
4320           return BB;
4321         }
4322       }
4323     }
4324 
4325     // If only FP bits are touched, used the no side effects pseudo.
4326     if ((SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4327                     AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask)
4328       MI.setDesc(TII->get(AMDGPU::S_SETREG_B32_mode));
4329 
4330     return BB;
4331   }
4332   default:
4333     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4334   }
4335 }
4336 
4337 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4338   return isTypeLegal(VT.getScalarType());
4339 }
4340 
4341 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4342   // This currently forces unfolding various combinations of fsub into fma with
4343   // free fneg'd operands. As long as we have fast FMA (controlled by
4344   // isFMAFasterThanFMulAndFAdd), we should perform these.
4345 
4346   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4347   // most of these combines appear to be cycle neutral but save on instruction
4348   // count / code size.
4349   return true;
4350 }
4351 
4352 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4353                                          EVT VT) const {
4354   if (!VT.isVector()) {
4355     return MVT::i1;
4356   }
4357   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4358 }
4359 
4360 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4361   // TODO: Should i16 be used always if legal? For now it would force VALU
4362   // shifts.
4363   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4364 }
4365 
4366 LLT SITargetLowering::getPreferredShiftAmountTy(LLT Ty) const {
4367   return (Ty.getScalarSizeInBits() <= 16 && Subtarget->has16BitInsts())
4368              ? Ty.changeElementSize(16)
4369              : Ty.changeElementSize(32);
4370 }
4371 
4372 // Answering this is somewhat tricky and depends on the specific device which
4373 // have different rates for fma or all f64 operations.
4374 //
4375 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4376 // regardless of which device (although the number of cycles differs between
4377 // devices), so it is always profitable for f64.
4378 //
4379 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4380 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4381 // which we can always do even without fused FP ops since it returns the same
4382 // result as the separate operations and since it is always full
4383 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4384 // however does not support denormals, so we do report fma as faster if we have
4385 // a fast fma device and require denormals.
4386 //
4387 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4388                                                   EVT VT) const {
4389   VT = VT.getScalarType();
4390 
4391   switch (VT.getSimpleVT().SimpleTy) {
4392   case MVT::f32: {
4393     // If mad is not available this depends only on if f32 fma is full rate.
4394     if (!Subtarget->hasMadMacF32Insts())
4395       return Subtarget->hasFastFMAF32();
4396 
4397     // Otherwise f32 mad is always full rate and returns the same result as
4398     // the separate operations so should be preferred over fma.
4399     // However does not support denomals.
4400     if (hasFP32Denormals(MF))
4401       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4402 
4403     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4404     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4405   }
4406   case MVT::f64:
4407     return true;
4408   case MVT::f16:
4409     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4410   default:
4411     break;
4412   }
4413 
4414   return false;
4415 }
4416 
4417 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4418                                    const SDNode *N) const {
4419   // TODO: Check future ftz flag
4420   // v_mad_f32/v_mac_f32 do not support denormals.
4421   EVT VT = N->getValueType(0);
4422   if (VT == MVT::f32)
4423     return Subtarget->hasMadMacF32Insts() &&
4424            !hasFP32Denormals(DAG.getMachineFunction());
4425   if (VT == MVT::f16) {
4426     return Subtarget->hasMadF16() &&
4427            !hasFP64FP16Denormals(DAG.getMachineFunction());
4428   }
4429 
4430   return false;
4431 }
4432 
4433 //===----------------------------------------------------------------------===//
4434 // Custom DAG Lowering Operations
4435 //===----------------------------------------------------------------------===//
4436 
4437 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4438 // wider vector type is legal.
4439 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4440                                              SelectionDAG &DAG) const {
4441   unsigned Opc = Op.getOpcode();
4442   EVT VT = Op.getValueType();
4443   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4444 
4445   SDValue Lo, Hi;
4446   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4447 
4448   SDLoc SL(Op);
4449   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4450                              Op->getFlags());
4451   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4452                              Op->getFlags());
4453 
4454   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4455 }
4456 
4457 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4458 // wider vector type is legal.
4459 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4460                                               SelectionDAG &DAG) const {
4461   unsigned Opc = Op.getOpcode();
4462   EVT VT = Op.getValueType();
4463   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4464 
4465   SDValue Lo0, Hi0;
4466   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4467   SDValue Lo1, Hi1;
4468   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4469 
4470   SDLoc SL(Op);
4471 
4472   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4473                              Op->getFlags());
4474   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4475                              Op->getFlags());
4476 
4477   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4478 }
4479 
4480 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4481                                               SelectionDAG &DAG) const {
4482   unsigned Opc = Op.getOpcode();
4483   EVT VT = Op.getValueType();
4484   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4485 
4486   SDValue Lo0, Hi0;
4487   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4488   SDValue Lo1, Hi1;
4489   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4490   SDValue Lo2, Hi2;
4491   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4492 
4493   SDLoc SL(Op);
4494 
4495   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4496                              Op->getFlags());
4497   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4498                              Op->getFlags());
4499 
4500   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4501 }
4502 
4503 
4504 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4505   switch (Op.getOpcode()) {
4506   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4507   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4508   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4509   case ISD::LOAD: {
4510     SDValue Result = LowerLOAD(Op, DAG);
4511     assert((!Result.getNode() ||
4512             Result.getNode()->getNumValues() == 2) &&
4513            "Load should return a value and a chain");
4514     return Result;
4515   }
4516 
4517   case ISD::FSIN:
4518   case ISD::FCOS:
4519     return LowerTrig(Op, DAG);
4520   case ISD::SELECT: return LowerSELECT(Op, DAG);
4521   case ISD::FDIV: return LowerFDIV(Op, DAG);
4522   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4523   case ISD::STORE: return LowerSTORE(Op, DAG);
4524   case ISD::GlobalAddress: {
4525     MachineFunction &MF = DAG.getMachineFunction();
4526     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4527     return LowerGlobalAddress(MFI, Op, DAG);
4528   }
4529   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4530   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4531   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4532   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4533   case ISD::INSERT_SUBVECTOR:
4534     return lowerINSERT_SUBVECTOR(Op, DAG);
4535   case ISD::INSERT_VECTOR_ELT:
4536     return lowerINSERT_VECTOR_ELT(Op, DAG);
4537   case ISD::EXTRACT_VECTOR_ELT:
4538     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4539   case ISD::VECTOR_SHUFFLE:
4540     return lowerVECTOR_SHUFFLE(Op, DAG);
4541   case ISD::BUILD_VECTOR:
4542     return lowerBUILD_VECTOR(Op, DAG);
4543   case ISD::FP_ROUND:
4544     return lowerFP_ROUND(Op, DAG);
4545   case ISD::TRAP:
4546     return lowerTRAP(Op, DAG);
4547   case ISD::DEBUGTRAP:
4548     return lowerDEBUGTRAP(Op, DAG);
4549   case ISD::FABS:
4550   case ISD::FNEG:
4551   case ISD::FCANONICALIZE:
4552   case ISD::BSWAP:
4553     return splitUnaryVectorOp(Op, DAG);
4554   case ISD::FMINNUM:
4555   case ISD::FMAXNUM:
4556     return lowerFMINNUM_FMAXNUM(Op, DAG);
4557   case ISD::FMA:
4558     return splitTernaryVectorOp(Op, DAG);
4559   case ISD::SHL:
4560   case ISD::SRA:
4561   case ISD::SRL:
4562   case ISD::ADD:
4563   case ISD::SUB:
4564   case ISD::MUL:
4565   case ISD::SMIN:
4566   case ISD::SMAX:
4567   case ISD::UMIN:
4568   case ISD::UMAX:
4569   case ISD::FADD:
4570   case ISD::FMUL:
4571   case ISD::FMINNUM_IEEE:
4572   case ISD::FMAXNUM_IEEE:
4573   case ISD::UADDSAT:
4574   case ISD::USUBSAT:
4575   case ISD::SADDSAT:
4576   case ISD::SSUBSAT:
4577     return splitBinaryVectorOp(Op, DAG);
4578   case ISD::SMULO:
4579   case ISD::UMULO:
4580     return lowerXMULO(Op, DAG);
4581   case ISD::DYNAMIC_STACKALLOC:
4582     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4583   }
4584   return SDValue();
4585 }
4586 
4587 // Used for D16: Casts the result of an instruction into the right vector,
4588 // packs values if loads return unpacked values.
4589 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4590                                        const SDLoc &DL,
4591                                        SelectionDAG &DAG, bool Unpacked) {
4592   if (!LoadVT.isVector())
4593     return Result;
4594 
4595   // Cast back to the original packed type or to a larger type that is a
4596   // multiple of 32 bit for D16. Widening the return type is a required for
4597   // legalization.
4598   EVT FittingLoadVT = LoadVT;
4599   if ((LoadVT.getVectorNumElements() % 2) == 1) {
4600     FittingLoadVT =
4601         EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4602                          LoadVT.getVectorNumElements() + 1);
4603   }
4604 
4605   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4606     // Truncate to v2i16/v4i16.
4607     EVT IntLoadVT = FittingLoadVT.changeTypeToInteger();
4608 
4609     // Workaround legalizer not scalarizing truncate after vector op
4610     // legalization but not creating intermediate vector trunc.
4611     SmallVector<SDValue, 4> Elts;
4612     DAG.ExtractVectorElements(Result, Elts);
4613     for (SDValue &Elt : Elts)
4614       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4615 
4616     // Pad illegal v1i16/v3fi6 to v4i16
4617     if ((LoadVT.getVectorNumElements() % 2) == 1)
4618       Elts.push_back(DAG.getUNDEF(MVT::i16));
4619 
4620     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4621 
4622     // Bitcast to original type (v2f16/v4f16).
4623     return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4624   }
4625 
4626   // Cast back to the original packed type.
4627   return DAG.getNode(ISD::BITCAST, DL, FittingLoadVT, Result);
4628 }
4629 
4630 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4631                                               MemSDNode *M,
4632                                               SelectionDAG &DAG,
4633                                               ArrayRef<SDValue> Ops,
4634                                               bool IsIntrinsic) const {
4635   SDLoc DL(M);
4636 
4637   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4638   EVT LoadVT = M->getValueType(0);
4639 
4640   EVT EquivLoadVT = LoadVT;
4641   if (LoadVT.isVector()) {
4642     if (Unpacked) {
4643       EquivLoadVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4644                                      LoadVT.getVectorNumElements());
4645     } else if ((LoadVT.getVectorNumElements() % 2) == 1) {
4646       // Widen v3f16 to legal type
4647       EquivLoadVT =
4648           EVT::getVectorVT(*DAG.getContext(), LoadVT.getVectorElementType(),
4649                            LoadVT.getVectorNumElements() + 1);
4650     }
4651   }
4652 
4653   // Change from v4f16/v2f16 to EquivLoadVT.
4654   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4655 
4656   SDValue Load
4657     = DAG.getMemIntrinsicNode(
4658       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4659       VTList, Ops, M->getMemoryVT(),
4660       M->getMemOperand());
4661 
4662   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4663 
4664   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4665 }
4666 
4667 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4668                                              SelectionDAG &DAG,
4669                                              ArrayRef<SDValue> Ops) const {
4670   SDLoc DL(M);
4671   EVT LoadVT = M->getValueType(0);
4672   EVT EltType = LoadVT.getScalarType();
4673   EVT IntVT = LoadVT.changeTypeToInteger();
4674 
4675   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4676 
4677   unsigned Opc =
4678       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4679 
4680   if (IsD16) {
4681     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4682   }
4683 
4684   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4685   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4686     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4687 
4688   if (isTypeLegal(LoadVT)) {
4689     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4690                                M->getMemOperand(), DAG);
4691   }
4692 
4693   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4694   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4695   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4696                                         M->getMemOperand(), DAG);
4697   return DAG.getMergeValues(
4698       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4699       DL);
4700 }
4701 
4702 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4703                                   SDNode *N, SelectionDAG &DAG) {
4704   EVT VT = N->getValueType(0);
4705   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4706   unsigned CondCode = CD->getZExtValue();
4707   if (!ICmpInst::isIntPredicate(static_cast<ICmpInst::Predicate>(CondCode)))
4708     return DAG.getUNDEF(VT);
4709 
4710   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4711 
4712   SDValue LHS = N->getOperand(1);
4713   SDValue RHS = N->getOperand(2);
4714 
4715   SDLoc DL(N);
4716 
4717   EVT CmpVT = LHS.getValueType();
4718   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4719     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4720       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4721     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4722     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4723   }
4724 
4725   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4726 
4727   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4728   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4729 
4730   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4731                               DAG.getCondCode(CCOpcode));
4732   if (VT.bitsEq(CCVT))
4733     return SetCC;
4734   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4735 }
4736 
4737 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4738                                   SDNode *N, SelectionDAG &DAG) {
4739   EVT VT = N->getValueType(0);
4740   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4741 
4742   unsigned CondCode = CD->getZExtValue();
4743   if (!FCmpInst::isFPPredicate(static_cast<FCmpInst::Predicate>(CondCode)))
4744     return DAG.getUNDEF(VT);
4745 
4746   SDValue Src0 = N->getOperand(1);
4747   SDValue Src1 = N->getOperand(2);
4748   EVT CmpVT = Src0.getValueType();
4749   SDLoc SL(N);
4750 
4751   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4752     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4753     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4754   }
4755 
4756   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4757   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4758   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4759   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4760   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4761                               Src1, DAG.getCondCode(CCOpcode));
4762   if (VT.bitsEq(CCVT))
4763     return SetCC;
4764   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4765 }
4766 
4767 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4768                                     SelectionDAG &DAG) {
4769   EVT VT = N->getValueType(0);
4770   SDValue Src = N->getOperand(1);
4771   SDLoc SL(N);
4772 
4773   if (Src.getOpcode() == ISD::SETCC) {
4774     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4775     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4776                        Src.getOperand(1), Src.getOperand(2));
4777   }
4778   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4779     // (ballot 0) -> 0
4780     if (Arg->isNullValue())
4781       return DAG.getConstant(0, SL, VT);
4782 
4783     // (ballot 1) -> EXEC/EXEC_LO
4784     if (Arg->isOne()) {
4785       Register Exec;
4786       if (VT.getScalarSizeInBits() == 32)
4787         Exec = AMDGPU::EXEC_LO;
4788       else if (VT.getScalarSizeInBits() == 64)
4789         Exec = AMDGPU::EXEC;
4790       else
4791         return SDValue();
4792 
4793       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4794     }
4795   }
4796 
4797   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4798   // ISD::SETNE)
4799   return DAG.getNode(
4800       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4801       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4802 }
4803 
4804 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4805                                           SmallVectorImpl<SDValue> &Results,
4806                                           SelectionDAG &DAG) const {
4807   switch (N->getOpcode()) {
4808   case ISD::INSERT_VECTOR_ELT: {
4809     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4810       Results.push_back(Res);
4811     return;
4812   }
4813   case ISD::EXTRACT_VECTOR_ELT: {
4814     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4815       Results.push_back(Res);
4816     return;
4817   }
4818   case ISD::INTRINSIC_WO_CHAIN: {
4819     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4820     switch (IID) {
4821     case Intrinsic::amdgcn_cvt_pkrtz: {
4822       SDValue Src0 = N->getOperand(1);
4823       SDValue Src1 = N->getOperand(2);
4824       SDLoc SL(N);
4825       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4826                                 Src0, Src1);
4827       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4828       return;
4829     }
4830     case Intrinsic::amdgcn_cvt_pknorm_i16:
4831     case Intrinsic::amdgcn_cvt_pknorm_u16:
4832     case Intrinsic::amdgcn_cvt_pk_i16:
4833     case Intrinsic::amdgcn_cvt_pk_u16: {
4834       SDValue Src0 = N->getOperand(1);
4835       SDValue Src1 = N->getOperand(2);
4836       SDLoc SL(N);
4837       unsigned Opcode;
4838 
4839       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4840         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4841       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4842         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4843       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4844         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4845       else
4846         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4847 
4848       EVT VT = N->getValueType(0);
4849       if (isTypeLegal(VT))
4850         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4851       else {
4852         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4853         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4854       }
4855       return;
4856     }
4857     }
4858     break;
4859   }
4860   case ISD::INTRINSIC_W_CHAIN: {
4861     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4862       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4863         // FIXME: Hacky
4864         for (unsigned I = 0; I < Res.getNumOperands(); I++) {
4865           Results.push_back(Res.getOperand(I));
4866         }
4867       } else {
4868         Results.push_back(Res);
4869         Results.push_back(Res.getValue(1));
4870       }
4871       return;
4872     }
4873 
4874     break;
4875   }
4876   case ISD::SELECT: {
4877     SDLoc SL(N);
4878     EVT VT = N->getValueType(0);
4879     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4880     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4881     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4882 
4883     EVT SelectVT = NewVT;
4884     if (NewVT.bitsLT(MVT::i32)) {
4885       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4886       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4887       SelectVT = MVT::i32;
4888     }
4889 
4890     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4891                                     N->getOperand(0), LHS, RHS);
4892 
4893     if (NewVT != SelectVT)
4894       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4895     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4896     return;
4897   }
4898   case ISD::FNEG: {
4899     if (N->getValueType(0) != MVT::v2f16)
4900       break;
4901 
4902     SDLoc SL(N);
4903     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4904 
4905     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4906                              BC,
4907                              DAG.getConstant(0x80008000, SL, MVT::i32));
4908     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4909     return;
4910   }
4911   case ISD::FABS: {
4912     if (N->getValueType(0) != MVT::v2f16)
4913       break;
4914 
4915     SDLoc SL(N);
4916     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4917 
4918     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4919                              BC,
4920                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4921     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4922     return;
4923   }
4924   default:
4925     break;
4926   }
4927 }
4928 
4929 /// Helper function for LowerBRCOND
4930 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4931 
4932   SDNode *Parent = Value.getNode();
4933   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4934        I != E; ++I) {
4935 
4936     if (I.getUse().get() != Value)
4937       continue;
4938 
4939     if (I->getOpcode() == Opcode)
4940       return *I;
4941   }
4942   return nullptr;
4943 }
4944 
4945 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4946   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4947     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4948     case Intrinsic::amdgcn_if:
4949       return AMDGPUISD::IF;
4950     case Intrinsic::amdgcn_else:
4951       return AMDGPUISD::ELSE;
4952     case Intrinsic::amdgcn_loop:
4953       return AMDGPUISD::LOOP;
4954     case Intrinsic::amdgcn_end_cf:
4955       llvm_unreachable("should not occur");
4956     default:
4957       return 0;
4958     }
4959   }
4960 
4961   // break, if_break, else_break are all only used as inputs to loop, not
4962   // directly as branch conditions.
4963   return 0;
4964 }
4965 
4966 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4967   const Triple &TT = getTargetMachine().getTargetTriple();
4968   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4969           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4970          AMDGPU::shouldEmitConstantsToTextSection(TT);
4971 }
4972 
4973 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4974   // FIXME: Either avoid relying on address space here or change the default
4975   // address space for functions to avoid the explicit check.
4976   return (GV->getValueType()->isFunctionTy() ||
4977           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4978          !shouldEmitFixup(GV) &&
4979          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4980 }
4981 
4982 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4983   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4984 }
4985 
4986 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4987   if (!GV->hasExternalLinkage())
4988     return true;
4989 
4990   const auto OS = getTargetMachine().getTargetTriple().getOS();
4991   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4992 }
4993 
4994 /// This transforms the control flow intrinsics to get the branch destination as
4995 /// last parameter, also switches branch target with BR if the need arise
4996 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4997                                       SelectionDAG &DAG) const {
4998   SDLoc DL(BRCOND);
4999 
5000   SDNode *Intr = BRCOND.getOperand(1).getNode();
5001   SDValue Target = BRCOND.getOperand(2);
5002   SDNode *BR = nullptr;
5003   SDNode *SetCC = nullptr;
5004 
5005   if (Intr->getOpcode() == ISD::SETCC) {
5006     // As long as we negate the condition everything is fine
5007     SetCC = Intr;
5008     Intr = SetCC->getOperand(0).getNode();
5009 
5010   } else {
5011     // Get the target from BR if we don't negate the condition
5012     BR = findUser(BRCOND, ISD::BR);
5013     assert(BR && "brcond missing unconditional branch user");
5014     Target = BR->getOperand(1);
5015   }
5016 
5017   unsigned CFNode = isCFIntrinsic(Intr);
5018   if (CFNode == 0) {
5019     // This is a uniform branch so we don't need to legalize.
5020     return BRCOND;
5021   }
5022 
5023   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
5024                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
5025 
5026   assert(!SetCC ||
5027         (SetCC->getConstantOperandVal(1) == 1 &&
5028          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
5029                                                              ISD::SETNE));
5030 
5031   // operands of the new intrinsic call
5032   SmallVector<SDValue, 4> Ops;
5033   if (HaveChain)
5034     Ops.push_back(BRCOND.getOperand(0));
5035 
5036   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
5037   Ops.push_back(Target);
5038 
5039   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
5040 
5041   // build the new intrinsic call
5042   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
5043 
5044   if (!HaveChain) {
5045     SDValue Ops[] =  {
5046       SDValue(Result, 0),
5047       BRCOND.getOperand(0)
5048     };
5049 
5050     Result = DAG.getMergeValues(Ops, DL).getNode();
5051   }
5052 
5053   if (BR) {
5054     // Give the branch instruction our target
5055     SDValue Ops[] = {
5056       BR->getOperand(0),
5057       BRCOND.getOperand(2)
5058     };
5059     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
5060     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
5061   }
5062 
5063   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
5064 
5065   // Copy the intrinsic results to registers
5066   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
5067     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
5068     if (!CopyToReg)
5069       continue;
5070 
5071     Chain = DAG.getCopyToReg(
5072       Chain, DL,
5073       CopyToReg->getOperand(1),
5074       SDValue(Result, i - 1),
5075       SDValue());
5076 
5077     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
5078   }
5079 
5080   // Remove the old intrinsic from the chain
5081   DAG.ReplaceAllUsesOfValueWith(
5082     SDValue(Intr, Intr->getNumValues() - 1),
5083     Intr->getOperand(0));
5084 
5085   return Chain;
5086 }
5087 
5088 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
5089                                           SelectionDAG &DAG) const {
5090   MVT VT = Op.getSimpleValueType();
5091   SDLoc DL(Op);
5092   // Checking the depth
5093   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
5094     return DAG.getConstant(0, DL, VT);
5095 
5096   MachineFunction &MF = DAG.getMachineFunction();
5097   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5098   // Check for kernel and shader functions
5099   if (Info->isEntryFunction())
5100     return DAG.getConstant(0, DL, VT);
5101 
5102   MachineFrameInfo &MFI = MF.getFrameInfo();
5103   // There is a call to @llvm.returnaddress in this function
5104   MFI.setReturnAddressIsTaken(true);
5105 
5106   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
5107   // Get the return address reg and mark it as an implicit live-in
5108   Register Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
5109 
5110   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
5111 }
5112 
5113 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
5114                                             SDValue Op,
5115                                             const SDLoc &DL,
5116                                             EVT VT) const {
5117   return Op.getValueType().bitsLE(VT) ?
5118       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
5119     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
5120                 DAG.getTargetConstant(0, DL, MVT::i32));
5121 }
5122 
5123 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
5124   assert(Op.getValueType() == MVT::f16 &&
5125          "Do not know how to custom lower FP_ROUND for non-f16 type");
5126 
5127   SDValue Src = Op.getOperand(0);
5128   EVT SrcVT = Src.getValueType();
5129   if (SrcVT != MVT::f64)
5130     return Op;
5131 
5132   SDLoc DL(Op);
5133 
5134   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
5135   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
5136   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
5137 }
5138 
5139 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
5140                                                SelectionDAG &DAG) const {
5141   EVT VT = Op.getValueType();
5142   const MachineFunction &MF = DAG.getMachineFunction();
5143   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5144   bool IsIEEEMode = Info->getMode().IEEE;
5145 
5146   // FIXME: Assert during selection that this is only selected for
5147   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
5148   // mode functions, but this happens to be OK since it's only done in cases
5149   // where there is known no sNaN.
5150   if (IsIEEEMode)
5151     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
5152 
5153   if (VT == MVT::v4f16)
5154     return splitBinaryVectorOp(Op, DAG);
5155   return Op;
5156 }
5157 
5158 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
5159   EVT VT = Op.getValueType();
5160   SDLoc SL(Op);
5161   SDValue LHS = Op.getOperand(0);
5162   SDValue RHS = Op.getOperand(1);
5163   bool isSigned = Op.getOpcode() == ISD::SMULO;
5164 
5165   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5166     const APInt &C = RHSC->getAPIntValue();
5167     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5168     if (C.isPowerOf2()) {
5169       // smulo(x, signed_min) is same as umulo(x, signed_min).
5170       bool UseArithShift = isSigned && !C.isMinSignedValue();
5171       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5172       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5173       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5174           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5175                       SL, VT, Result, ShiftAmt),
5176           LHS, ISD::SETNE);
5177       return DAG.getMergeValues({ Result, Overflow }, SL);
5178     }
5179   }
5180 
5181   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5182   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5183                             SL, VT, LHS, RHS);
5184 
5185   SDValue Sign = isSigned
5186     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5187                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5188     : DAG.getConstant(0, SL, VT);
5189   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5190 
5191   return DAG.getMergeValues({ Result, Overflow }, SL);
5192 }
5193 
5194 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5195   SDLoc SL(Op);
5196   SDValue Chain = Op.getOperand(0);
5197 
5198   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5199       !Subtarget->isTrapHandlerEnabled())
5200     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5201 
5202   MachineFunction &MF = DAG.getMachineFunction();
5203   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5204   Register UserSGPR = Info->getQueuePtrUserSGPR();
5205   assert(UserSGPR != AMDGPU::NoRegister);
5206   SDValue QueuePtr = CreateLiveInRegister(
5207     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5208   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5209   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5210                                    QueuePtr, SDValue());
5211   SDValue Ops[] = {
5212     ToReg,
5213     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5214     SGPR01,
5215     ToReg.getValue(1)
5216   };
5217   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5218 }
5219 
5220 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5221   SDLoc SL(Op);
5222   SDValue Chain = Op.getOperand(0);
5223   MachineFunction &MF = DAG.getMachineFunction();
5224 
5225   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5226       !Subtarget->isTrapHandlerEnabled()) {
5227     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5228                                      "debugtrap handler not supported",
5229                                      Op.getDebugLoc(),
5230                                      DS_Warning);
5231     LLVMContext &Ctx = MF.getFunction().getContext();
5232     Ctx.diagnose(NoTrap);
5233     return Chain;
5234   }
5235 
5236   SDValue Ops[] = {
5237     Chain,
5238     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5239   };
5240   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5241 }
5242 
5243 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5244                                              SelectionDAG &DAG) const {
5245   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5246   if (Subtarget->hasApertureRegs()) {
5247     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5248         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5249         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5250     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5251         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5252         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5253     unsigned Encoding =
5254         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5255         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5256         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5257 
5258     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5259     SDValue ApertureReg = SDValue(
5260         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5261     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5262     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5263   }
5264 
5265   MachineFunction &MF = DAG.getMachineFunction();
5266   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5267   Register UserSGPR = Info->getQueuePtrUserSGPR();
5268   assert(UserSGPR != AMDGPU::NoRegister);
5269 
5270   SDValue QueuePtr = CreateLiveInRegister(
5271     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5272 
5273   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5274   // private_segment_aperture_base_hi.
5275   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5276 
5277   SDValue Ptr =
5278       DAG.getObjectPtrOffset(DL, QueuePtr, TypeSize::Fixed(StructOffset));
5279 
5280   // TODO: Use custom target PseudoSourceValue.
5281   // TODO: We should use the value from the IR intrinsic call, but it might not
5282   // be available and how do we get it?
5283   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5284   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5285                      commonAlignment(Align(64), StructOffset),
5286                      MachineMemOperand::MODereferenceable |
5287                          MachineMemOperand::MOInvariant);
5288 }
5289 
5290 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5291                                              SelectionDAG &DAG) const {
5292   SDLoc SL(Op);
5293   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5294 
5295   SDValue Src = ASC->getOperand(0);
5296   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5297 
5298   const AMDGPUTargetMachine &TM =
5299     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5300 
5301   // flat -> local/private
5302   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5303     unsigned DestAS = ASC->getDestAddressSpace();
5304 
5305     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5306         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5307       unsigned NullVal = TM.getNullPointerValue(DestAS);
5308       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5309       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5310       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5311 
5312       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5313                          NonNull, Ptr, SegmentNullPtr);
5314     }
5315   }
5316 
5317   // local/private -> flat
5318   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5319     unsigned SrcAS = ASC->getSrcAddressSpace();
5320 
5321     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5322         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5323       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5324       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5325 
5326       SDValue NonNull
5327         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5328 
5329       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5330       SDValue CvtPtr
5331         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5332 
5333       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5334                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5335                          FlatNullPtr);
5336     }
5337   }
5338 
5339   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5340       Src.getValueType() == MVT::i64)
5341     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5342 
5343   // global <-> flat are no-ops and never emitted.
5344 
5345   const MachineFunction &MF = DAG.getMachineFunction();
5346   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5347     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5348   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5349 
5350   return DAG.getUNDEF(ASC->getValueType(0));
5351 }
5352 
5353 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5354 // the small vector and inserting them into the big vector. That is better than
5355 // the default expansion of doing it via a stack slot. Even though the use of
5356 // the stack slot would be optimized away afterwards, the stack slot itself
5357 // remains.
5358 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5359                                                 SelectionDAG &DAG) const {
5360   SDValue Vec = Op.getOperand(0);
5361   SDValue Ins = Op.getOperand(1);
5362   SDValue Idx = Op.getOperand(2);
5363   EVT VecVT = Vec.getValueType();
5364   EVT InsVT = Ins.getValueType();
5365   EVT EltVT = VecVT.getVectorElementType();
5366   unsigned InsNumElts = InsVT.getVectorNumElements();
5367   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5368   SDLoc SL(Op);
5369 
5370   for (unsigned I = 0; I != InsNumElts; ++I) {
5371     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5372                               DAG.getConstant(I, SL, MVT::i32));
5373     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5374                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5375   }
5376   return Vec;
5377 }
5378 
5379 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5380                                                  SelectionDAG &DAG) const {
5381   SDValue Vec = Op.getOperand(0);
5382   SDValue InsVal = Op.getOperand(1);
5383   SDValue Idx = Op.getOperand(2);
5384   EVT VecVT = Vec.getValueType();
5385   EVT EltVT = VecVT.getVectorElementType();
5386   unsigned VecSize = VecVT.getSizeInBits();
5387   unsigned EltSize = EltVT.getSizeInBits();
5388 
5389 
5390   assert(VecSize <= 64);
5391 
5392   unsigned NumElts = VecVT.getVectorNumElements();
5393   SDLoc SL(Op);
5394   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5395 
5396   if (NumElts == 4 && EltSize == 16 && KIdx) {
5397     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5398 
5399     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5400                                  DAG.getConstant(0, SL, MVT::i32));
5401     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5402                                  DAG.getConstant(1, SL, MVT::i32));
5403 
5404     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5405     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5406 
5407     unsigned Idx = KIdx->getZExtValue();
5408     bool InsertLo = Idx < 2;
5409     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5410       InsertLo ? LoVec : HiVec,
5411       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5412       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5413 
5414     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5415 
5416     SDValue Concat = InsertLo ?
5417       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5418       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5419 
5420     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5421   }
5422 
5423   if (isa<ConstantSDNode>(Idx))
5424     return SDValue();
5425 
5426   MVT IntVT = MVT::getIntegerVT(VecSize);
5427 
5428   // Avoid stack access for dynamic indexing.
5429   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5430 
5431   // Create a congruent vector with the target value in each element so that
5432   // the required element can be masked and ORed into the target vector.
5433   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5434                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5435 
5436   assert(isPowerOf2_32(EltSize));
5437   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5438 
5439   // Convert vector index to bit-index.
5440   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5441 
5442   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5443   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5444                             DAG.getConstant(0xffff, SL, IntVT),
5445                             ScaledIdx);
5446 
5447   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5448   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5449                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5450 
5451   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5452   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5453 }
5454 
5455 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5456                                                   SelectionDAG &DAG) const {
5457   SDLoc SL(Op);
5458 
5459   EVT ResultVT = Op.getValueType();
5460   SDValue Vec = Op.getOperand(0);
5461   SDValue Idx = Op.getOperand(1);
5462   EVT VecVT = Vec.getValueType();
5463   unsigned VecSize = VecVT.getSizeInBits();
5464   EVT EltVT = VecVT.getVectorElementType();
5465   assert(VecSize <= 64);
5466 
5467   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5468 
5469   // Make sure we do any optimizations that will make it easier to fold
5470   // source modifiers before obscuring it with bit operations.
5471 
5472   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5473   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5474     return Combined;
5475 
5476   unsigned EltSize = EltVT.getSizeInBits();
5477   assert(isPowerOf2_32(EltSize));
5478 
5479   MVT IntVT = MVT::getIntegerVT(VecSize);
5480   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5481 
5482   // Convert vector index to bit-index (* EltSize)
5483   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5484 
5485   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5486   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5487 
5488   if (ResultVT == MVT::f16) {
5489     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5490     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5491   }
5492 
5493   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5494 }
5495 
5496 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5497   assert(Elt % 2 == 0);
5498   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5499 }
5500 
5501 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5502                                               SelectionDAG &DAG) const {
5503   SDLoc SL(Op);
5504   EVT ResultVT = Op.getValueType();
5505   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5506 
5507   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5508   EVT EltVT = PackVT.getVectorElementType();
5509   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5510 
5511   // vector_shuffle <0,1,6,7> lhs, rhs
5512   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5513   //
5514   // vector_shuffle <6,7,2,3> lhs, rhs
5515   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5516   //
5517   // vector_shuffle <6,7,0,1> lhs, rhs
5518   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5519 
5520   // Avoid scalarizing when both halves are reading from consecutive elements.
5521   SmallVector<SDValue, 4> Pieces;
5522   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5523     if (elementPairIsContiguous(SVN->getMask(), I)) {
5524       const int Idx = SVN->getMaskElt(I);
5525       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5526       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5527       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5528                                     PackVT, SVN->getOperand(VecIdx),
5529                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5530       Pieces.push_back(SubVec);
5531     } else {
5532       const int Idx0 = SVN->getMaskElt(I);
5533       const int Idx1 = SVN->getMaskElt(I + 1);
5534       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5535       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5536       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5537       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5538 
5539       SDValue Vec0 = SVN->getOperand(VecIdx0);
5540       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5541                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5542 
5543       SDValue Vec1 = SVN->getOperand(VecIdx1);
5544       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5545                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5546       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5547     }
5548   }
5549 
5550   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5551 }
5552 
5553 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5554                                             SelectionDAG &DAG) const {
5555   SDLoc SL(Op);
5556   EVT VT = Op.getValueType();
5557 
5558   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5559     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5560 
5561     // Turn into pair of packed build_vectors.
5562     // TODO: Special case for constants that can be materialized with s_mov_b64.
5563     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5564                                     { Op.getOperand(0), Op.getOperand(1) });
5565     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5566                                     { Op.getOperand(2), Op.getOperand(3) });
5567 
5568     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5569     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5570 
5571     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5572     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5573   }
5574 
5575   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5576   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5577 
5578   SDValue Lo = Op.getOperand(0);
5579   SDValue Hi = Op.getOperand(1);
5580 
5581   // Avoid adding defined bits with the zero_extend.
5582   if (Hi.isUndef()) {
5583     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5584     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5585     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5586   }
5587 
5588   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5589   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5590 
5591   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5592                               DAG.getConstant(16, SL, MVT::i32));
5593   if (Lo.isUndef())
5594     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5595 
5596   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5597   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5598 
5599   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5600   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5601 }
5602 
5603 bool
5604 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5605   // We can fold offsets for anything that doesn't require a GOT relocation.
5606   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5607           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5608           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5609          !shouldEmitGOTReloc(GA->getGlobal());
5610 }
5611 
5612 static SDValue
5613 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5614                         const SDLoc &DL, int64_t Offset, EVT PtrVT,
5615                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5616   assert(isInt<32>(Offset + 4) && "32-bit offset is expected!");
5617   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5618   // lowered to the following code sequence:
5619   //
5620   // For constant address space:
5621   //   s_getpc_b64 s[0:1]
5622   //   s_add_u32 s0, s0, $symbol
5623   //   s_addc_u32 s1, s1, 0
5624   //
5625   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5626   //   a fixup or relocation is emitted to replace $symbol with a literal
5627   //   constant, which is a pc-relative offset from the encoding of the $symbol
5628   //   operand to the global variable.
5629   //
5630   // For global address space:
5631   //   s_getpc_b64 s[0:1]
5632   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5633   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5634   //
5635   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5636   //   fixups or relocations are emitted to replace $symbol@*@lo and
5637   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5638   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5639   //   operand to the global variable.
5640   //
5641   // What we want here is an offset from the value returned by s_getpc
5642   // (which is the address of the s_add_u32 instruction) to the global
5643   // variable, but since the encoding of $symbol starts 4 bytes after the start
5644   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5645   // small. This requires us to add 4 to the global variable offset in order to
5646   // compute the correct address. Similarly for the s_addc_u32 instruction, the
5647   // encoding of $symbol starts 12 bytes after the start of the s_add_u32
5648   // instruction.
5649   SDValue PtrLo =
5650       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5651   SDValue PtrHi;
5652   if (GAFlags == SIInstrInfo::MO_NONE) {
5653     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5654   } else {
5655     PtrHi =
5656         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 12, GAFlags + 1);
5657   }
5658   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5659 }
5660 
5661 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5662                                              SDValue Op,
5663                                              SelectionDAG &DAG) const {
5664   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5665   SDLoc DL(GSD);
5666   EVT PtrVT = Op.getValueType();
5667 
5668   const GlobalValue *GV = GSD->getGlobal();
5669   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5670        shouldUseLDSConstAddress(GV)) ||
5671       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5672       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS) {
5673     if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5674         GV->hasExternalLinkage()) {
5675       Type *Ty = GV->getValueType();
5676       // HIP uses an unsized array `extern __shared__ T s[]` or similar
5677       // zero-sized type in other languages to declare the dynamic shared
5678       // memory which size is not known at the compile time. They will be
5679       // allocated by the runtime and placed directly after the static
5680       // allocated ones. They all share the same offset.
5681       if (DAG.getDataLayout().getTypeAllocSize(Ty).isZero()) {
5682         assert(PtrVT == MVT::i32 && "32-bit pointer is expected.");
5683         // Adjust alignment for that dynamic shared memory array.
5684         MFI->setDynLDSAlign(DAG.getDataLayout(), *cast<GlobalVariable>(GV));
5685         return SDValue(
5686             DAG.getMachineNode(AMDGPU::GET_GROUPSTATICSIZE, DL, PtrVT), 0);
5687       }
5688     }
5689     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5690   }
5691 
5692   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5693     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5694                                             SIInstrInfo::MO_ABS32_LO);
5695     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5696   }
5697 
5698   if (shouldEmitFixup(GV))
5699     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5700   else if (shouldEmitPCReloc(GV))
5701     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5702                                    SIInstrInfo::MO_REL32);
5703 
5704   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5705                                             SIInstrInfo::MO_GOTPCREL32);
5706 
5707   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5708   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5709   const DataLayout &DataLayout = DAG.getDataLayout();
5710   Align Alignment = DataLayout.getABITypeAlign(PtrTy);
5711   MachinePointerInfo PtrInfo
5712     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5713 
5714   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Alignment,
5715                      MachineMemOperand::MODereferenceable |
5716                          MachineMemOperand::MOInvariant);
5717 }
5718 
5719 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5720                                    const SDLoc &DL, SDValue V) const {
5721   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5722   // the destination register.
5723   //
5724   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5725   // so we will end up with redundant moves to m0.
5726   //
5727   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5728 
5729   // A Null SDValue creates a glue result.
5730   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5731                                   V, Chain);
5732   return SDValue(M0, 0);
5733 }
5734 
5735 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5736                                                  SDValue Op,
5737                                                  MVT VT,
5738                                                  unsigned Offset) const {
5739   SDLoc SL(Op);
5740   SDValue Param = lowerKernargMemParameter(
5741       DAG, MVT::i32, MVT::i32, SL, DAG.getEntryNode(), Offset, Align(4), false);
5742   // The local size values will have the hi 16-bits as zero.
5743   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5744                      DAG.getValueType(VT));
5745 }
5746 
5747 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5748                                         EVT VT) {
5749   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5750                                       "non-hsa intrinsic with hsa target",
5751                                       DL.getDebugLoc());
5752   DAG.getContext()->diagnose(BadIntrin);
5753   return DAG.getUNDEF(VT);
5754 }
5755 
5756 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5757                                          EVT VT) {
5758   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5759                                       "intrinsic not supported on subtarget",
5760                                       DL.getDebugLoc());
5761   DAG.getContext()->diagnose(BadIntrin);
5762   return DAG.getUNDEF(VT);
5763 }
5764 
5765 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5766                                     ArrayRef<SDValue> Elts) {
5767   assert(!Elts.empty());
5768   MVT Type;
5769   unsigned NumElts;
5770 
5771   if (Elts.size() == 1) {
5772     Type = MVT::f32;
5773     NumElts = 1;
5774   } else if (Elts.size() == 2) {
5775     Type = MVT::v2f32;
5776     NumElts = 2;
5777   } else if (Elts.size() == 3) {
5778     Type = MVT::v3f32;
5779     NumElts = 3;
5780   } else if (Elts.size() <= 4) {
5781     Type = MVT::v4f32;
5782     NumElts = 4;
5783   } else if (Elts.size() <= 8) {
5784     Type = MVT::v8f32;
5785     NumElts = 8;
5786   } else {
5787     assert(Elts.size() <= 16);
5788     Type = MVT::v16f32;
5789     NumElts = 16;
5790   }
5791 
5792   SmallVector<SDValue, 16> VecElts(NumElts);
5793   for (unsigned i = 0; i < Elts.size(); ++i) {
5794     SDValue Elt = Elts[i];
5795     if (Elt.getValueType() != MVT::f32)
5796       Elt = DAG.getBitcast(MVT::f32, Elt);
5797     VecElts[i] = Elt;
5798   }
5799   for (unsigned i = Elts.size(); i < NumElts; ++i)
5800     VecElts[i] = DAG.getUNDEF(MVT::f32);
5801 
5802   if (NumElts == 1)
5803     return VecElts[0];
5804   return DAG.getBuildVector(Type, DL, VecElts);
5805 }
5806 
5807 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5808                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5809   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5810 
5811   uint64_t Value = CachePolicyConst->getZExtValue();
5812   SDLoc DL(CachePolicy);
5813   if (GLC) {
5814     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5815     Value &= ~(uint64_t)0x1;
5816   }
5817   if (SLC) {
5818     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5819     Value &= ~(uint64_t)0x2;
5820   }
5821   if (DLC) {
5822     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5823     Value &= ~(uint64_t)0x4;
5824   }
5825 
5826   return Value == 0;
5827 }
5828 
5829 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5830                               SDValue Src, int ExtraElts) {
5831   EVT SrcVT = Src.getValueType();
5832 
5833   SmallVector<SDValue, 8> Elts;
5834 
5835   if (SrcVT.isVector())
5836     DAG.ExtractVectorElements(Src, Elts);
5837   else
5838     Elts.push_back(Src);
5839 
5840   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5841   while (ExtraElts--)
5842     Elts.push_back(Undef);
5843 
5844   return DAG.getBuildVector(CastVT, DL, Elts);
5845 }
5846 
5847 // Re-construct the required return value for a image load intrinsic.
5848 // This is more complicated due to the optional use TexFailCtrl which means the required
5849 // return type is an aggregate
5850 static SDValue constructRetValue(SelectionDAG &DAG,
5851                                  MachineSDNode *Result,
5852                                  ArrayRef<EVT> ResultTypes,
5853                                  bool IsTexFail, bool Unpacked, bool IsD16,
5854                                  int DMaskPop, int NumVDataDwords,
5855                                  const SDLoc &DL, LLVMContext &Context) {
5856   // Determine the required return type. This is the same regardless of IsTexFail flag
5857   EVT ReqRetVT = ResultTypes[0];
5858   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5859   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5860     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5861 
5862   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5863     DMaskPop : (DMaskPop + 1) / 2;
5864 
5865   MVT DataDwordVT = NumDataDwords == 1 ?
5866     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5867 
5868   MVT MaskPopVT = MaskPopDwords == 1 ?
5869     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5870 
5871   SDValue Data(Result, 0);
5872   SDValue TexFail;
5873 
5874   if (DMaskPop > 0 && Data.getValueType() != MaskPopVT) {
5875     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5876     if (MaskPopVT.isVector()) {
5877       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5878                          SDValue(Result, 0), ZeroIdx);
5879     } else {
5880       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5881                          SDValue(Result, 0), ZeroIdx);
5882     }
5883   }
5884 
5885   if (DataDwordVT.isVector())
5886     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5887                           NumDataDwords - MaskPopDwords);
5888 
5889   if (IsD16)
5890     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5891 
5892   EVT LegalReqRetVT = ReqRetVT;
5893   if (!ReqRetVT.isVector()) {
5894     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5895   } else {
5896     // We need to widen the return vector to a legal type
5897     if ((ReqRetVT.getVectorNumElements() % 2) == 1 &&
5898         ReqRetVT.getVectorElementType().getSizeInBits() == 16) {
5899       LegalReqRetVT =
5900           EVT::getVectorVT(*DAG.getContext(), ReqRetVT.getVectorElementType(),
5901                            ReqRetVT.getVectorNumElements() + 1);
5902     }
5903   }
5904   Data = DAG.getNode(ISD::BITCAST, DL, LegalReqRetVT, Data);
5905 
5906   if (IsTexFail) {
5907     TexFail =
5908         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, SDValue(Result, 0),
5909                     DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5910 
5911     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5912   }
5913 
5914   if (Result->getNumValues() == 1)
5915     return Data;
5916 
5917   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5918 }
5919 
5920 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5921                          SDValue *LWE, bool &IsTexFail) {
5922   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5923 
5924   uint64_t Value = TexFailCtrlConst->getZExtValue();
5925   if (Value) {
5926     IsTexFail = true;
5927   }
5928 
5929   SDLoc DL(TexFailCtrlConst);
5930   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5931   Value &= ~(uint64_t)0x1;
5932   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5933   Value &= ~(uint64_t)0x2;
5934 
5935   return Value == 0;
5936 }
5937 
5938 static void packImageA16AddressToDwords(SelectionDAG &DAG, SDValue Op,
5939                                         MVT PackVectorVT,
5940                                         SmallVectorImpl<SDValue> &PackedAddrs,
5941                                         unsigned DimIdx, unsigned EndIdx,
5942                                         unsigned NumGradients) {
5943   SDLoc DL(Op);
5944   for (unsigned I = DimIdx; I < EndIdx; I++) {
5945     SDValue Addr = Op.getOperand(I);
5946 
5947     // Gradients are packed with undef for each coordinate.
5948     // In <hi 16 bit>,<lo 16 bit> notation, the registers look like this:
5949     // 1D: undef,dx/dh; undef,dx/dv
5950     // 2D: dy/dh,dx/dh; dy/dv,dx/dv
5951     // 3D: dy/dh,dx/dh; undef,dz/dh; dy/dv,dx/dv; undef,dz/dv
5952     if (((I + 1) >= EndIdx) ||
5953         ((NumGradients / 2) % 2 == 1 && (I == DimIdx + (NumGradients / 2) - 1 ||
5954                                          I == DimIdx + NumGradients - 1))) {
5955       if (Addr.getValueType() != MVT::i16)
5956         Addr = DAG.getBitcast(MVT::i16, Addr);
5957       Addr = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Addr);
5958     } else {
5959       Addr = DAG.getBuildVector(PackVectorVT, DL, {Addr, Op.getOperand(I + 1)});
5960       I++;
5961     }
5962     Addr = DAG.getBitcast(MVT::f32, Addr);
5963     PackedAddrs.push_back(Addr);
5964   }
5965 }
5966 
5967 SDValue SITargetLowering::lowerImage(SDValue Op,
5968                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5969                                      SelectionDAG &DAG, bool WithChain) const {
5970   SDLoc DL(Op);
5971   MachineFunction &MF = DAG.getMachineFunction();
5972   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5973   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5974       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5975   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5976   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5977       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5978   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5979       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5980   unsigned IntrOpcode = Intr->BaseOpcode;
5981   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5982 
5983   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5984   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5985   bool IsD16 = false;
5986   bool IsG16 = false;
5987   bool IsA16 = false;
5988   SDValue VData;
5989   int NumVDataDwords;
5990   bool AdjustRetType = false;
5991 
5992   // Offset of intrinsic arguments
5993   const unsigned ArgOffset = WithChain ? 2 : 1;
5994 
5995   unsigned DMask;
5996   unsigned DMaskLanes = 0;
5997 
5998   if (BaseOpcode->Atomic) {
5999     VData = Op.getOperand(2);
6000 
6001     bool Is64Bit = VData.getValueType() == MVT::i64;
6002     if (BaseOpcode->AtomicX2) {
6003       SDValue VData2 = Op.getOperand(3);
6004       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
6005                                  {VData, VData2});
6006       if (Is64Bit)
6007         VData = DAG.getBitcast(MVT::v4i32, VData);
6008 
6009       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
6010       DMask = Is64Bit ? 0xf : 0x3;
6011       NumVDataDwords = Is64Bit ? 4 : 2;
6012     } else {
6013       DMask = Is64Bit ? 0x3 : 0x1;
6014       NumVDataDwords = Is64Bit ? 2 : 1;
6015     }
6016   } else {
6017     auto *DMaskConst =
6018         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->DMaskIndex));
6019     DMask = DMaskConst->getZExtValue();
6020     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
6021 
6022     if (BaseOpcode->Store) {
6023       VData = Op.getOperand(2);
6024 
6025       MVT StoreVT = VData.getSimpleValueType();
6026       if (StoreVT.getScalarType() == MVT::f16) {
6027         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6028           return Op; // D16 is unsupported for this instruction
6029 
6030         IsD16 = true;
6031         VData = handleD16VData(VData, DAG, true);
6032       }
6033 
6034       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
6035     } else {
6036       // Work out the num dwords based on the dmask popcount and underlying type
6037       // and whether packing is supported.
6038       MVT LoadVT = ResultTypes[0].getSimpleVT();
6039       if (LoadVT.getScalarType() == MVT::f16) {
6040         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
6041           return Op; // D16 is unsupported for this instruction
6042 
6043         IsD16 = true;
6044       }
6045 
6046       // Confirm that the return type is large enough for the dmask specified
6047       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
6048           (!LoadVT.isVector() && DMaskLanes > 1))
6049           return Op;
6050 
6051       // The sq block of gfx8 and gfx9 do not estimate register use correctly
6052       // for d16 image_gather4, image_gather4_l, and image_gather4_lz
6053       // instructions.
6054       if (IsD16 && !Subtarget->hasUnpackedD16VMem() &&
6055           !(BaseOpcode->Gather4 && Subtarget->hasImageGather4D16Bug()))
6056         NumVDataDwords = (DMaskLanes + 1) / 2;
6057       else
6058         NumVDataDwords = DMaskLanes;
6059 
6060       AdjustRetType = true;
6061     }
6062   }
6063 
6064   unsigned VAddrEnd = ArgOffset + Intr->VAddrEnd;
6065   SmallVector<SDValue, 4> VAddrs;
6066 
6067   // Optimize _L to _LZ when _L is zero
6068   if (LZMappingInfo) {
6069     if (auto *ConstantLod = dyn_cast<ConstantFPSDNode>(
6070             Op.getOperand(ArgOffset + Intr->LodIndex))) {
6071       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
6072         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
6073         VAddrEnd--;                      // remove 'lod'
6074       }
6075     }
6076   }
6077 
6078   // Optimize _mip away, when 'lod' is zero
6079   if (MIPMappingInfo) {
6080     if (auto *ConstantLod = dyn_cast<ConstantSDNode>(
6081             Op.getOperand(ArgOffset + Intr->MipIndex))) {
6082       if (ConstantLod->isNullValue()) {
6083         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
6084         VAddrEnd--;                           // remove 'mip'
6085       }
6086     }
6087   }
6088 
6089   // Push back extra arguments.
6090   for (unsigned I = Intr->VAddrStart; I < Intr->GradientStart; I++)
6091     VAddrs.push_back(Op.getOperand(ArgOffset + I));
6092 
6093   // Check for 16 bit addresses or derivatives and pack if true.
6094   MVT VAddrVT =
6095       Op.getOperand(ArgOffset + Intr->GradientStart).getSimpleValueType();
6096   MVT VAddrScalarVT = VAddrVT.getScalarType();
6097   MVT PackVectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
6098   IsG16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6099 
6100   VAddrVT = Op.getOperand(ArgOffset + Intr->CoordStart).getSimpleValueType();
6101   VAddrScalarVT = VAddrVT.getScalarType();
6102   IsA16 = VAddrScalarVT == MVT::f16 || VAddrScalarVT == MVT::i16;
6103   if (IsA16 || IsG16) {
6104     if (IsA16) {
6105       if (!ST->hasA16()) {
6106         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6107                              "support 16 bit addresses\n");
6108         return Op;
6109       }
6110       if (!IsG16) {
6111         LLVM_DEBUG(
6112             dbgs() << "Failed to lower image intrinsic: 16 bit addresses "
6113                       "need 16 bit derivatives but got 32 bit derivatives\n");
6114         return Op;
6115       }
6116     } else if (!ST->hasG16()) {
6117       LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6118                            "support 16 bit derivatives\n");
6119       return Op;
6120     }
6121 
6122     if (BaseOpcode->Gradients && !IsA16) {
6123       if (!ST->hasG16()) {
6124         LLVM_DEBUG(dbgs() << "Failed to lower image intrinsic: Target does not "
6125                              "support 16 bit derivatives\n");
6126         return Op;
6127       }
6128       // Activate g16
6129       const AMDGPU::MIMGG16MappingInfo *G16MappingInfo =
6130           AMDGPU::getMIMGG16MappingInfo(Intr->BaseOpcode);
6131       IntrOpcode = G16MappingInfo->G16; // set new opcode to variant with _g16
6132     }
6133 
6134     // Don't compress addresses for G16
6135     const int PackEndIdx = IsA16 ? VAddrEnd : (ArgOffset + Intr->CoordStart);
6136     packImageA16AddressToDwords(DAG, Op, PackVectorVT, VAddrs,
6137                                 ArgOffset + Intr->GradientStart, PackEndIdx,
6138                                 Intr->NumGradients);
6139 
6140     if (!IsA16) {
6141       // Add uncompressed address
6142       for (unsigned I = ArgOffset + Intr->CoordStart; I < VAddrEnd; I++)
6143         VAddrs.push_back(Op.getOperand(I));
6144     }
6145   } else {
6146     for (unsigned I = ArgOffset + Intr->GradientStart; I < VAddrEnd; I++)
6147       VAddrs.push_back(Op.getOperand(I));
6148   }
6149 
6150   // If the register allocator cannot place the address registers contiguously
6151   // without introducing moves, then using the non-sequential address encoding
6152   // is always preferable, since it saves VALU instructions and is usually a
6153   // wash in terms of code size or even better.
6154   //
6155   // However, we currently have no way of hinting to the register allocator that
6156   // MIMG addresses should be placed contiguously when it is possible to do so,
6157   // so force non-NSA for the common 2-address case as a heuristic.
6158   //
6159   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
6160   // allocation when possible.
6161   bool UseNSA =
6162       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
6163   SDValue VAddr;
6164   if (!UseNSA)
6165     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
6166 
6167   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
6168   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
6169   SDValue Unorm;
6170   if (!BaseOpcode->Sampler) {
6171     Unorm = True;
6172   } else {
6173     auto UnormConst =
6174         cast<ConstantSDNode>(Op.getOperand(ArgOffset + Intr->UnormIndex));
6175 
6176     Unorm = UnormConst->getZExtValue() ? True : False;
6177   }
6178 
6179   SDValue TFE;
6180   SDValue LWE;
6181   SDValue TexFail = Op.getOperand(ArgOffset + Intr->TexFailCtrlIndex);
6182   bool IsTexFail = false;
6183   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
6184     return Op;
6185 
6186   if (IsTexFail) {
6187     if (!DMaskLanes) {
6188       // Expecting to get an error flag since TFC is on - and dmask is 0
6189       // Force dmask to be at least 1 otherwise the instruction will fail
6190       DMask = 0x1;
6191       DMaskLanes = 1;
6192       NumVDataDwords = 1;
6193     }
6194     NumVDataDwords += 1;
6195     AdjustRetType = true;
6196   }
6197 
6198   // Has something earlier tagged that the return type needs adjusting
6199   // This happens if the instruction is a load or has set TexFailCtrl flags
6200   if (AdjustRetType) {
6201     // NumVDataDwords reflects the true number of dwords required in the return type
6202     if (DMaskLanes == 0 && !BaseOpcode->Store) {
6203       // This is a no-op load. This can be eliminated
6204       SDValue Undef = DAG.getUNDEF(Op.getValueType());
6205       if (isa<MemSDNode>(Op))
6206         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
6207       return Undef;
6208     }
6209 
6210     EVT NewVT = NumVDataDwords > 1 ?
6211                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
6212                 : MVT::i32;
6213 
6214     ResultTypes[0] = NewVT;
6215     if (ResultTypes.size() == 3) {
6216       // Original result was aggregate type used for TexFailCtrl results
6217       // The actual instruction returns as a vector type which has now been
6218       // created. Remove the aggregate result.
6219       ResultTypes.erase(&ResultTypes[1]);
6220     }
6221   }
6222 
6223   SDValue GLC;
6224   SDValue SLC;
6225   SDValue DLC;
6226   if (BaseOpcode->Atomic) {
6227     GLC = True; // TODO no-return optimization
6228     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6229                           DAG, nullptr, &SLC, IsGFX10 ? &DLC : nullptr))
6230       return Op;
6231   } else {
6232     if (!parseCachePolicy(Op.getOperand(ArgOffset + Intr->CachePolicyIndex),
6233                           DAG, &GLC, &SLC, IsGFX10 ? &DLC : nullptr))
6234       return Op;
6235   }
6236 
6237   SmallVector<SDValue, 26> Ops;
6238   if (BaseOpcode->Store || BaseOpcode->Atomic)
6239     Ops.push_back(VData); // vdata
6240   if (UseNSA) {
6241     for (const SDValue &Addr : VAddrs)
6242       Ops.push_back(Addr);
6243   } else {
6244     Ops.push_back(VAddr);
6245   }
6246   Ops.push_back(Op.getOperand(ArgOffset + Intr->RsrcIndex));
6247   if (BaseOpcode->Sampler)
6248     Ops.push_back(Op.getOperand(ArgOffset + Intr->SampIndex));
6249   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6250   if (IsGFX10)
6251     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6252   Ops.push_back(Unorm);
6253   if (IsGFX10)
6254     Ops.push_back(DLC);
6255   Ops.push_back(GLC);
6256   Ops.push_back(SLC);
6257   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6258                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6259   if (IsGFX10)
6260     Ops.push_back(IsA16 ? True : False);
6261   Ops.push_back(TFE);
6262   Ops.push_back(LWE);
6263   if (!IsGFX10)
6264     Ops.push_back(DimInfo->DA ? True : False);
6265   if (BaseOpcode->HasD16)
6266     Ops.push_back(IsD16 ? True : False);
6267   if (isa<MemSDNode>(Op))
6268     Ops.push_back(Op.getOperand(0)); // chain
6269 
6270   int NumVAddrDwords =
6271       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6272   int Opcode = -1;
6273 
6274   if (IsGFX10) {
6275     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6276                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6277                                           : AMDGPU::MIMGEncGfx10Default,
6278                                    NumVDataDwords, NumVAddrDwords);
6279   } else {
6280     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6281       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6282                                      NumVDataDwords, NumVAddrDwords);
6283     if (Opcode == -1)
6284       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6285                                      NumVDataDwords, NumVAddrDwords);
6286   }
6287   assert(Opcode != -1);
6288 
6289   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6290   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6291     MachineMemOperand *MemRef = MemOp->getMemOperand();
6292     DAG.setNodeMemRefs(NewNode, {MemRef});
6293   }
6294 
6295   if (BaseOpcode->AtomicX2) {
6296     SmallVector<SDValue, 1> Elt;
6297     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6298     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6299   } else if (!BaseOpcode->Store) {
6300     return constructRetValue(DAG, NewNode,
6301                              OrigResultTypes, IsTexFail,
6302                              Subtarget->hasUnpackedD16VMem(), IsD16,
6303                              DMaskLanes, NumVDataDwords, DL,
6304                              *DAG.getContext());
6305   }
6306 
6307   return SDValue(NewNode, 0);
6308 }
6309 
6310 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6311                                        SDValue Offset, SDValue CachePolicy,
6312                                        SelectionDAG &DAG) const {
6313   MachineFunction &MF = DAG.getMachineFunction();
6314 
6315   const DataLayout &DataLayout = DAG.getDataLayout();
6316   Align Alignment =
6317       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6318 
6319   MachineMemOperand *MMO = MF.getMachineMemOperand(
6320       MachinePointerInfo(),
6321       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6322           MachineMemOperand::MOInvariant,
6323       VT.getStoreSize(), Alignment);
6324 
6325   if (!Offset->isDivergent()) {
6326     SDValue Ops[] = {
6327         Rsrc,
6328         Offset, // Offset
6329         CachePolicy
6330     };
6331 
6332     // Widen vec3 load to vec4.
6333     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6334       EVT WidenedVT =
6335           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6336       auto WidenedOp = DAG.getMemIntrinsicNode(
6337           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6338           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6339       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6340                                    DAG.getVectorIdxConstant(0, DL));
6341       return Subvector;
6342     }
6343 
6344     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6345                                    DAG.getVTList(VT), Ops, VT, MMO);
6346   }
6347 
6348   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6349   // assume that the buffer is unswizzled.
6350   SmallVector<SDValue, 4> Loads;
6351   unsigned NumLoads = 1;
6352   MVT LoadVT = VT.getSimpleVT();
6353   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6354   assert((LoadVT.getScalarType() == MVT::i32 ||
6355           LoadVT.getScalarType() == MVT::f32));
6356 
6357   if (NumElts == 8 || NumElts == 16) {
6358     NumLoads = NumElts / 4;
6359     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6360   }
6361 
6362   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6363   SDValue Ops[] = {
6364       DAG.getEntryNode(),                               // Chain
6365       Rsrc,                                             // rsrc
6366       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6367       {},                                               // voffset
6368       {},                                               // soffset
6369       {},                                               // offset
6370       CachePolicy,                                      // cachepolicy
6371       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6372   };
6373 
6374   // Use the alignment to ensure that the required offsets will fit into the
6375   // immediate offsets.
6376   setBufferOffsets(Offset, DAG, &Ops[3],
6377                    NumLoads > 1 ? Align(16 * NumLoads) : Align(4));
6378 
6379   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6380   for (unsigned i = 0; i < NumLoads; ++i) {
6381     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6382     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6383                                         LoadVT, MMO, DAG));
6384   }
6385 
6386   if (NumElts == 8 || NumElts == 16)
6387     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6388 
6389   return Loads[0];
6390 }
6391 
6392 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6393                                                   SelectionDAG &DAG) const {
6394   MachineFunction &MF = DAG.getMachineFunction();
6395   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6396 
6397   EVT VT = Op.getValueType();
6398   SDLoc DL(Op);
6399   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6400 
6401   // TODO: Should this propagate fast-math-flags?
6402 
6403   switch (IntrinsicID) {
6404   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6405     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6406       return emitNonHSAIntrinsicError(DAG, DL, VT);
6407     return getPreloadedValue(DAG, *MFI, VT,
6408                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6409   }
6410   case Intrinsic::amdgcn_dispatch_ptr:
6411   case Intrinsic::amdgcn_queue_ptr: {
6412     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6413       DiagnosticInfoUnsupported BadIntrin(
6414           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6415           DL.getDebugLoc());
6416       DAG.getContext()->diagnose(BadIntrin);
6417       return DAG.getUNDEF(VT);
6418     }
6419 
6420     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6421       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6422     return getPreloadedValue(DAG, *MFI, VT, RegID);
6423   }
6424   case Intrinsic::amdgcn_implicitarg_ptr: {
6425     if (MFI->isEntryFunction())
6426       return getImplicitArgPtr(DAG, DL);
6427     return getPreloadedValue(DAG, *MFI, VT,
6428                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6429   }
6430   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6431     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6432       // This only makes sense to call in a kernel, so just lower to null.
6433       return DAG.getConstant(0, DL, VT);
6434     }
6435 
6436     return getPreloadedValue(DAG, *MFI, VT,
6437                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6438   }
6439   case Intrinsic::amdgcn_dispatch_id: {
6440     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6441   }
6442   case Intrinsic::amdgcn_rcp:
6443     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6444   case Intrinsic::amdgcn_rsq:
6445     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6446   case Intrinsic::amdgcn_rsq_legacy:
6447     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6448       return emitRemovedIntrinsicError(DAG, DL, VT);
6449     return SDValue();
6450   case Intrinsic::amdgcn_rcp_legacy:
6451     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6452       return emitRemovedIntrinsicError(DAG, DL, VT);
6453     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6454   case Intrinsic::amdgcn_rsq_clamp: {
6455     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6456       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6457 
6458     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6459     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6460     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6461 
6462     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6463     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6464                               DAG.getConstantFP(Max, DL, VT));
6465     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6466                        DAG.getConstantFP(Min, DL, VT));
6467   }
6468   case Intrinsic::r600_read_ngroups_x:
6469     if (Subtarget->isAmdHsaOS())
6470       return emitNonHSAIntrinsicError(DAG, DL, VT);
6471 
6472     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6473                                     SI::KernelInputOffsets::NGROUPS_X, Align(4),
6474                                     false);
6475   case Intrinsic::r600_read_ngroups_y:
6476     if (Subtarget->isAmdHsaOS())
6477       return emitNonHSAIntrinsicError(DAG, DL, VT);
6478 
6479     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6480                                     SI::KernelInputOffsets::NGROUPS_Y, Align(4),
6481                                     false);
6482   case Intrinsic::r600_read_ngroups_z:
6483     if (Subtarget->isAmdHsaOS())
6484       return emitNonHSAIntrinsicError(DAG, DL, VT);
6485 
6486     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6487                                     SI::KernelInputOffsets::NGROUPS_Z, Align(4),
6488                                     false);
6489   case Intrinsic::r600_read_global_size_x:
6490     if (Subtarget->isAmdHsaOS())
6491       return emitNonHSAIntrinsicError(DAG, DL, VT);
6492 
6493     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6494                                     SI::KernelInputOffsets::GLOBAL_SIZE_X,
6495                                     Align(4), false);
6496   case Intrinsic::r600_read_global_size_y:
6497     if (Subtarget->isAmdHsaOS())
6498       return emitNonHSAIntrinsicError(DAG, DL, VT);
6499 
6500     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6501                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y,
6502                                     Align(4), false);
6503   case Intrinsic::r600_read_global_size_z:
6504     if (Subtarget->isAmdHsaOS())
6505       return emitNonHSAIntrinsicError(DAG, DL, VT);
6506 
6507     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6508                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z,
6509                                     Align(4), false);
6510   case Intrinsic::r600_read_local_size_x:
6511     if (Subtarget->isAmdHsaOS())
6512       return emitNonHSAIntrinsicError(DAG, DL, VT);
6513 
6514     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6515                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6516   case Intrinsic::r600_read_local_size_y:
6517     if (Subtarget->isAmdHsaOS())
6518       return emitNonHSAIntrinsicError(DAG, DL, VT);
6519 
6520     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6521                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6522   case Intrinsic::r600_read_local_size_z:
6523     if (Subtarget->isAmdHsaOS())
6524       return emitNonHSAIntrinsicError(DAG, DL, VT);
6525 
6526     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6527                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6528   case Intrinsic::amdgcn_workgroup_id_x:
6529     return getPreloadedValue(DAG, *MFI, VT,
6530                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6531   case Intrinsic::amdgcn_workgroup_id_y:
6532     return getPreloadedValue(DAG, *MFI, VT,
6533                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6534   case Intrinsic::amdgcn_workgroup_id_z:
6535     return getPreloadedValue(DAG, *MFI, VT,
6536                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6537   case Intrinsic::amdgcn_workitem_id_x:
6538     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6539                           SDLoc(DAG.getEntryNode()),
6540                           MFI->getArgInfo().WorkItemIDX);
6541   case Intrinsic::amdgcn_workitem_id_y:
6542     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6543                           SDLoc(DAG.getEntryNode()),
6544                           MFI->getArgInfo().WorkItemIDY);
6545   case Intrinsic::amdgcn_workitem_id_z:
6546     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6547                           SDLoc(DAG.getEntryNode()),
6548                           MFI->getArgInfo().WorkItemIDZ);
6549   case Intrinsic::amdgcn_wavefrontsize:
6550     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6551                            SDLoc(Op), MVT::i32);
6552   case Intrinsic::amdgcn_s_buffer_load: {
6553     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6554     SDValue GLC;
6555     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6556     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6557                           IsGFX10 ? &DLC : nullptr))
6558       return Op;
6559     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6560                         DAG);
6561   }
6562   case Intrinsic::amdgcn_fdiv_fast:
6563     return lowerFDIV_FAST(Op, DAG);
6564   case Intrinsic::amdgcn_sin:
6565     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6566 
6567   case Intrinsic::amdgcn_cos:
6568     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6569 
6570   case Intrinsic::amdgcn_mul_u24:
6571     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6572   case Intrinsic::amdgcn_mul_i24:
6573     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6574 
6575   case Intrinsic::amdgcn_log_clamp: {
6576     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6577       return SDValue();
6578 
6579     DiagnosticInfoUnsupported BadIntrin(
6580       MF.getFunction(), "intrinsic not supported on subtarget",
6581       DL.getDebugLoc());
6582       DAG.getContext()->diagnose(BadIntrin);
6583       return DAG.getUNDEF(VT);
6584   }
6585   case Intrinsic::amdgcn_ldexp:
6586     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6587                        Op.getOperand(1), Op.getOperand(2));
6588 
6589   case Intrinsic::amdgcn_fract:
6590     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6591 
6592   case Intrinsic::amdgcn_class:
6593     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6594                        Op.getOperand(1), Op.getOperand(2));
6595   case Intrinsic::amdgcn_div_fmas:
6596     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6597                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6598                        Op.getOperand(4));
6599 
6600   case Intrinsic::amdgcn_div_fixup:
6601     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6602                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6603 
6604   case Intrinsic::amdgcn_div_scale: {
6605     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6606 
6607     // Translate to the operands expected by the machine instruction. The
6608     // first parameter must be the same as the first instruction.
6609     SDValue Numerator = Op.getOperand(1);
6610     SDValue Denominator = Op.getOperand(2);
6611 
6612     // Note this order is opposite of the machine instruction's operations,
6613     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6614     // intrinsic has the numerator as the first operand to match a normal
6615     // division operation.
6616 
6617     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6618 
6619     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6620                        Denominator, Numerator);
6621   }
6622   case Intrinsic::amdgcn_icmp: {
6623     // There is a Pat that handles this variant, so return it as-is.
6624     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6625         Op.getConstantOperandVal(2) == 0 &&
6626         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6627       return Op;
6628     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6629   }
6630   case Intrinsic::amdgcn_fcmp: {
6631     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6632   }
6633   case Intrinsic::amdgcn_ballot:
6634     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6635   case Intrinsic::amdgcn_fmed3:
6636     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6637                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6638   case Intrinsic::amdgcn_fdot2:
6639     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6640                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6641                        Op.getOperand(4));
6642   case Intrinsic::amdgcn_fmul_legacy:
6643     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6644                        Op.getOperand(1), Op.getOperand(2));
6645   case Intrinsic::amdgcn_sffbh:
6646     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6647   case Intrinsic::amdgcn_sbfe:
6648     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6649                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6650   case Intrinsic::amdgcn_ubfe:
6651     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6652                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6653   case Intrinsic::amdgcn_cvt_pkrtz:
6654   case Intrinsic::amdgcn_cvt_pknorm_i16:
6655   case Intrinsic::amdgcn_cvt_pknorm_u16:
6656   case Intrinsic::amdgcn_cvt_pk_i16:
6657   case Intrinsic::amdgcn_cvt_pk_u16: {
6658     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6659     EVT VT = Op.getValueType();
6660     unsigned Opcode;
6661 
6662     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6663       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6664     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6665       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6666     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6667       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6668     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6669       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6670     else
6671       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6672 
6673     if (isTypeLegal(VT))
6674       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6675 
6676     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6677                                Op.getOperand(1), Op.getOperand(2));
6678     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6679   }
6680   case Intrinsic::amdgcn_fmad_ftz:
6681     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6682                        Op.getOperand(2), Op.getOperand(3));
6683 
6684   case Intrinsic::amdgcn_if_break:
6685     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6686                                       Op->getOperand(1), Op->getOperand(2)), 0);
6687 
6688   case Intrinsic::amdgcn_groupstaticsize: {
6689     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6690     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6691       return Op;
6692 
6693     const Module *M = MF.getFunction().getParent();
6694     const GlobalValue *GV =
6695         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6696     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6697                                             SIInstrInfo::MO_ABS32_LO);
6698     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6699   }
6700   case Intrinsic::amdgcn_is_shared:
6701   case Intrinsic::amdgcn_is_private: {
6702     SDLoc SL(Op);
6703     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6704       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6705     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6706     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6707                                  Op.getOperand(1));
6708 
6709     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6710                                 DAG.getConstant(1, SL, MVT::i32));
6711     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6712   }
6713   case Intrinsic::amdgcn_alignbit:
6714     return DAG.getNode(ISD::FSHR, DL, VT,
6715                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6716   case Intrinsic::amdgcn_reloc_constant: {
6717     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6718     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6719     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6720     auto RelocSymbol = cast<GlobalVariable>(
6721         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6722     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6723                                             SIInstrInfo::MO_ABS32_LO);
6724     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6725   }
6726   default:
6727     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6728             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6729       return lowerImage(Op, ImageDimIntr, DAG, false);
6730 
6731     return Op;
6732   }
6733 }
6734 
6735 // This function computes an appropriate offset to pass to
6736 // MachineMemOperand::setOffset() based on the offset inputs to
6737 // an intrinsic.  If any of the offsets are non-contstant or
6738 // if VIndex is non-zero then this function returns 0.  Otherwise,
6739 // it returns the sum of VOffset, SOffset, and Offset.
6740 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6741                                       SDValue SOffset,
6742                                       SDValue Offset,
6743                                       SDValue VIndex = SDValue()) {
6744 
6745   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6746       !isa<ConstantSDNode>(Offset))
6747     return 0;
6748 
6749   if (VIndex) {
6750     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6751       return 0;
6752   }
6753 
6754   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6755          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6756          cast<ConstantSDNode>(Offset)->getSExtValue();
6757 }
6758 
6759 SDValue SITargetLowering::lowerRawBufferAtomicIntrin(SDValue Op,
6760                                                      SelectionDAG &DAG,
6761                                                      unsigned NewOpcode) const {
6762   SDLoc DL(Op);
6763 
6764   SDValue VData = Op.getOperand(2);
6765   auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6766   SDValue Ops[] = {
6767     Op.getOperand(0), // Chain
6768     VData,            // vdata
6769     Op.getOperand(3), // rsrc
6770     DAG.getConstant(0, DL, MVT::i32), // vindex
6771     Offsets.first,    // voffset
6772     Op.getOperand(5), // soffset
6773     Offsets.second,   // offset
6774     Op.getOperand(6), // cachepolicy
6775     DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6776   };
6777 
6778   auto *M = cast<MemSDNode>(Op);
6779   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6780 
6781   EVT MemVT = VData.getValueType();
6782   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6783                                  M->getMemOperand());
6784 }
6785 
6786 SDValue
6787 SITargetLowering::lowerStructBufferAtomicIntrin(SDValue Op, SelectionDAG &DAG,
6788                                                 unsigned NewOpcode) const {
6789   SDLoc DL(Op);
6790 
6791   SDValue VData = Op.getOperand(2);
6792   auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6793   SDValue Ops[] = {
6794     Op.getOperand(0), // Chain
6795     VData,            // vdata
6796     Op.getOperand(3), // rsrc
6797     Op.getOperand(4), // vindex
6798     Offsets.first,    // voffset
6799     Op.getOperand(6), // soffset
6800     Offsets.second,   // offset
6801     Op.getOperand(7), // cachepolicy
6802     DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6803   };
6804 
6805   auto *M = cast<MemSDNode>(Op);
6806   M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6807                                                       Ops[3]));
6808 
6809   EVT MemVT = VData.getValueType();
6810   return DAG.getMemIntrinsicNode(NewOpcode, DL, Op->getVTList(), Ops, MemVT,
6811                                  M->getMemOperand());
6812 }
6813 
6814 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6815                                                  SelectionDAG &DAG) const {
6816   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6817   SDLoc DL(Op);
6818 
6819   switch (IntrID) {
6820   case Intrinsic::amdgcn_ds_ordered_add:
6821   case Intrinsic::amdgcn_ds_ordered_swap: {
6822     MemSDNode *M = cast<MemSDNode>(Op);
6823     SDValue Chain = M->getOperand(0);
6824     SDValue M0 = M->getOperand(2);
6825     SDValue Value = M->getOperand(3);
6826     unsigned IndexOperand = M->getConstantOperandVal(7);
6827     unsigned WaveRelease = M->getConstantOperandVal(8);
6828     unsigned WaveDone = M->getConstantOperandVal(9);
6829 
6830     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6831     IndexOperand &= ~0x3f;
6832     unsigned CountDw = 0;
6833 
6834     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6835       CountDw = (IndexOperand >> 24) & 0xf;
6836       IndexOperand &= ~(0xf << 24);
6837 
6838       if (CountDw < 1 || CountDw > 4) {
6839         report_fatal_error(
6840             "ds_ordered_count: dword count must be between 1 and 4");
6841       }
6842     }
6843 
6844     if (IndexOperand)
6845       report_fatal_error("ds_ordered_count: bad index operand");
6846 
6847     if (WaveDone && !WaveRelease)
6848       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6849 
6850     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6851     unsigned ShaderType =
6852         SIInstrInfo::getDSShaderTypeValue(DAG.getMachineFunction());
6853     unsigned Offset0 = OrderedCountIndex << 2;
6854     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6855                        (Instruction << 4);
6856 
6857     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6858       Offset1 |= (CountDw - 1) << 6;
6859 
6860     unsigned Offset = Offset0 | (Offset1 << 8);
6861 
6862     SDValue Ops[] = {
6863       Chain,
6864       Value,
6865       DAG.getTargetConstant(Offset, DL, MVT::i16),
6866       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6867     };
6868     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6869                                    M->getVTList(), Ops, M->getMemoryVT(),
6870                                    M->getMemOperand());
6871   }
6872   case Intrinsic::amdgcn_ds_fadd: {
6873     MemSDNode *M = cast<MemSDNode>(Op);
6874     unsigned Opc;
6875     switch (IntrID) {
6876     case Intrinsic::amdgcn_ds_fadd:
6877       Opc = ISD::ATOMIC_LOAD_FADD;
6878       break;
6879     }
6880 
6881     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6882                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6883                          M->getMemOperand());
6884   }
6885   case Intrinsic::amdgcn_atomic_inc:
6886   case Intrinsic::amdgcn_atomic_dec:
6887   case Intrinsic::amdgcn_ds_fmin:
6888   case Intrinsic::amdgcn_ds_fmax: {
6889     MemSDNode *M = cast<MemSDNode>(Op);
6890     unsigned Opc;
6891     switch (IntrID) {
6892     case Intrinsic::amdgcn_atomic_inc:
6893       Opc = AMDGPUISD::ATOMIC_INC;
6894       break;
6895     case Intrinsic::amdgcn_atomic_dec:
6896       Opc = AMDGPUISD::ATOMIC_DEC;
6897       break;
6898     case Intrinsic::amdgcn_ds_fmin:
6899       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6900       break;
6901     case Intrinsic::amdgcn_ds_fmax:
6902       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6903       break;
6904     default:
6905       llvm_unreachable("Unknown intrinsic!");
6906     }
6907     SDValue Ops[] = {
6908       M->getOperand(0), // Chain
6909       M->getOperand(2), // Ptr
6910       M->getOperand(3)  // Value
6911     };
6912 
6913     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6914                                    M->getMemoryVT(), M->getMemOperand());
6915   }
6916   case Intrinsic::amdgcn_buffer_load:
6917   case Intrinsic::amdgcn_buffer_load_format: {
6918     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6919     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6920     unsigned IdxEn = 1;
6921     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6922       IdxEn = Idx->getZExtValue() != 0;
6923     SDValue Ops[] = {
6924       Op.getOperand(0), // Chain
6925       Op.getOperand(2), // rsrc
6926       Op.getOperand(3), // vindex
6927       SDValue(),        // voffset -- will be set by setBufferOffsets
6928       SDValue(),        // soffset -- will be set by setBufferOffsets
6929       SDValue(),        // offset -- will be set by setBufferOffsets
6930       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6931       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6932     };
6933 
6934     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6935     // We don't know the offset if vindex is non-zero, so clear it.
6936     if (IdxEn)
6937       Offset = 0;
6938 
6939     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6940         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6941 
6942     EVT VT = Op.getValueType();
6943     EVT IntVT = VT.changeTypeToInteger();
6944     auto *M = cast<MemSDNode>(Op);
6945     M->getMemOperand()->setOffset(Offset);
6946     EVT LoadVT = Op.getValueType();
6947 
6948     if (LoadVT.getScalarType() == MVT::f16)
6949       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6950                                  M, DAG, Ops);
6951 
6952     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6953     if (LoadVT.getScalarType() == MVT::i8 ||
6954         LoadVT.getScalarType() == MVT::i16)
6955       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6956 
6957     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6958                                M->getMemOperand(), DAG);
6959   }
6960   case Intrinsic::amdgcn_raw_buffer_load:
6961   case Intrinsic::amdgcn_raw_buffer_load_format: {
6962     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6963 
6964     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6965     SDValue Ops[] = {
6966       Op.getOperand(0), // Chain
6967       Op.getOperand(2), // rsrc
6968       DAG.getConstant(0, DL, MVT::i32), // vindex
6969       Offsets.first,    // voffset
6970       Op.getOperand(4), // soffset
6971       Offsets.second,   // offset
6972       Op.getOperand(5), // cachepolicy, swizzled buffer
6973       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6974     };
6975 
6976     auto *M = cast<MemSDNode>(Op);
6977     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6978     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6979   }
6980   case Intrinsic::amdgcn_struct_buffer_load:
6981   case Intrinsic::amdgcn_struct_buffer_load_format: {
6982     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6983 
6984     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6985     SDValue Ops[] = {
6986       Op.getOperand(0), // Chain
6987       Op.getOperand(2), // rsrc
6988       Op.getOperand(3), // vindex
6989       Offsets.first,    // voffset
6990       Op.getOperand(5), // soffset
6991       Offsets.second,   // offset
6992       Op.getOperand(6), // cachepolicy, swizzled buffer
6993       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6994     };
6995 
6996     auto *M = cast<MemSDNode>(Op);
6997     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6998                                                         Ops[2]));
6999     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
7000   }
7001   case Intrinsic::amdgcn_tbuffer_load: {
7002     MemSDNode *M = cast<MemSDNode>(Op);
7003     EVT LoadVT = Op.getValueType();
7004 
7005     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7006     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7007     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7008     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7009     unsigned IdxEn = 1;
7010     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
7011       IdxEn = Idx->getZExtValue() != 0;
7012     SDValue Ops[] = {
7013       Op.getOperand(0),  // Chain
7014       Op.getOperand(2),  // rsrc
7015       Op.getOperand(3),  // vindex
7016       Op.getOperand(4),  // voffset
7017       Op.getOperand(5),  // soffset
7018       Op.getOperand(6),  // offset
7019       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7020       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7021       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
7022     };
7023 
7024     if (LoadVT.getScalarType() == MVT::f16)
7025       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7026                                  M, DAG, Ops);
7027     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7028                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7029                                DAG);
7030   }
7031   case Intrinsic::amdgcn_raw_tbuffer_load: {
7032     MemSDNode *M = cast<MemSDNode>(Op);
7033     EVT LoadVT = Op.getValueType();
7034     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
7035 
7036     SDValue Ops[] = {
7037       Op.getOperand(0),  // Chain
7038       Op.getOperand(2),  // rsrc
7039       DAG.getConstant(0, DL, MVT::i32), // vindex
7040       Offsets.first,     // voffset
7041       Op.getOperand(4),  // soffset
7042       Offsets.second,    // offset
7043       Op.getOperand(5),  // format
7044       Op.getOperand(6),  // cachepolicy, swizzled buffer
7045       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7046     };
7047 
7048     if (LoadVT.getScalarType() == MVT::f16)
7049       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7050                                  M, DAG, Ops);
7051     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7052                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7053                                DAG);
7054   }
7055   case Intrinsic::amdgcn_struct_tbuffer_load: {
7056     MemSDNode *M = cast<MemSDNode>(Op);
7057     EVT LoadVT = Op.getValueType();
7058     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7059 
7060     SDValue Ops[] = {
7061       Op.getOperand(0),  // Chain
7062       Op.getOperand(2),  // rsrc
7063       Op.getOperand(3),  // vindex
7064       Offsets.first,     // voffset
7065       Op.getOperand(5),  // soffset
7066       Offsets.second,    // offset
7067       Op.getOperand(6),  // format
7068       Op.getOperand(7),  // cachepolicy, swizzled buffer
7069       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7070     };
7071 
7072     if (LoadVT.getScalarType() == MVT::f16)
7073       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
7074                                  M, DAG, Ops);
7075     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
7076                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
7077                                DAG);
7078   }
7079   case Intrinsic::amdgcn_buffer_atomic_swap:
7080   case Intrinsic::amdgcn_buffer_atomic_add:
7081   case Intrinsic::amdgcn_buffer_atomic_sub:
7082   case Intrinsic::amdgcn_buffer_atomic_csub:
7083   case Intrinsic::amdgcn_buffer_atomic_smin:
7084   case Intrinsic::amdgcn_buffer_atomic_umin:
7085   case Intrinsic::amdgcn_buffer_atomic_smax:
7086   case Intrinsic::amdgcn_buffer_atomic_umax:
7087   case Intrinsic::amdgcn_buffer_atomic_and:
7088   case Intrinsic::amdgcn_buffer_atomic_or:
7089   case Intrinsic::amdgcn_buffer_atomic_xor:
7090   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7091     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7092     unsigned IdxEn = 1;
7093     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7094       IdxEn = Idx->getZExtValue() != 0;
7095     SDValue Ops[] = {
7096       Op.getOperand(0), // Chain
7097       Op.getOperand(2), // vdata
7098       Op.getOperand(3), // rsrc
7099       Op.getOperand(4), // vindex
7100       SDValue(),        // voffset -- will be set by setBufferOffsets
7101       SDValue(),        // soffset -- will be set by setBufferOffsets
7102       SDValue(),        // offset -- will be set by setBufferOffsets
7103       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7104       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7105     };
7106     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7107     // We don't know the offset if vindex is non-zero, so clear it.
7108     if (IdxEn)
7109       Offset = 0;
7110     EVT VT = Op.getValueType();
7111 
7112     auto *M = cast<MemSDNode>(Op);
7113     M->getMemOperand()->setOffset(Offset);
7114     unsigned Opcode = 0;
7115 
7116     switch (IntrID) {
7117     case Intrinsic::amdgcn_buffer_atomic_swap:
7118       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
7119       break;
7120     case Intrinsic::amdgcn_buffer_atomic_add:
7121       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
7122       break;
7123     case Intrinsic::amdgcn_buffer_atomic_sub:
7124       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
7125       break;
7126     case Intrinsic::amdgcn_buffer_atomic_csub:
7127       Opcode = AMDGPUISD::BUFFER_ATOMIC_CSUB;
7128       break;
7129     case Intrinsic::amdgcn_buffer_atomic_smin:
7130       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
7131       break;
7132     case Intrinsic::amdgcn_buffer_atomic_umin:
7133       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7134       break;
7135     case Intrinsic::amdgcn_buffer_atomic_smax:
7136       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7137       break;
7138     case Intrinsic::amdgcn_buffer_atomic_umax:
7139       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7140       break;
7141     case Intrinsic::amdgcn_buffer_atomic_and:
7142       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7143       break;
7144     case Intrinsic::amdgcn_buffer_atomic_or:
7145       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7146       break;
7147     case Intrinsic::amdgcn_buffer_atomic_xor:
7148       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7149       break;
7150     case Intrinsic::amdgcn_buffer_atomic_fadd:
7151       if (!Op.getValue(0).use_empty()) {
7152         DiagnosticInfoUnsupported
7153           NoFpRet(DAG.getMachineFunction().getFunction(),
7154                   "return versions of fp atomics not supported",
7155                   DL.getDebugLoc(), DS_Error);
7156         DAG.getContext()->diagnose(NoFpRet);
7157         return SDValue();
7158       }
7159       Opcode = AMDGPUISD::BUFFER_ATOMIC_FADD;
7160       break;
7161     default:
7162       llvm_unreachable("unhandled atomic opcode");
7163     }
7164 
7165     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7166                                    M->getMemOperand());
7167   }
7168   case Intrinsic::amdgcn_raw_buffer_atomic_fadd:
7169     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7170   case Intrinsic::amdgcn_struct_buffer_atomic_fadd:
7171     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_FADD);
7172   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
7173     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SWAP);
7174   case Intrinsic::amdgcn_raw_buffer_atomic_add:
7175     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7176   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
7177     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7178   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
7179     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMIN);
7180   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
7181     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMIN);
7182   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
7183     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SMAX);
7184   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
7185     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_UMAX);
7186   case Intrinsic::amdgcn_raw_buffer_atomic_and:
7187     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7188   case Intrinsic::amdgcn_raw_buffer_atomic_or:
7189     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7190   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
7191     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7192   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
7193     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7194   case Intrinsic::amdgcn_raw_buffer_atomic_dec:
7195     return lowerRawBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7196   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
7197     return lowerStructBufferAtomicIntrin(Op, DAG,
7198                                          AMDGPUISD::BUFFER_ATOMIC_SWAP);
7199   case Intrinsic::amdgcn_struct_buffer_atomic_add:
7200     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_ADD);
7201   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
7202     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_SUB);
7203   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
7204     return lowerStructBufferAtomicIntrin(Op, DAG,
7205                                          AMDGPUISD::BUFFER_ATOMIC_SMIN);
7206   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
7207     return lowerStructBufferAtomicIntrin(Op, DAG,
7208                                          AMDGPUISD::BUFFER_ATOMIC_UMIN);
7209   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7210     return lowerStructBufferAtomicIntrin(Op, DAG,
7211                                          AMDGPUISD::BUFFER_ATOMIC_SMAX);
7212   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7213     return lowerStructBufferAtomicIntrin(Op, DAG,
7214                                          AMDGPUISD::BUFFER_ATOMIC_UMAX);
7215   case Intrinsic::amdgcn_struct_buffer_atomic_and:
7216     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_AND);
7217   case Intrinsic::amdgcn_struct_buffer_atomic_or:
7218     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_OR);
7219   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7220     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_XOR);
7221   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7222     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_INC);
7223   case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7224     return lowerStructBufferAtomicIntrin(Op, DAG, AMDGPUISD::BUFFER_ATOMIC_DEC);
7225 
7226   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7227     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7228     unsigned IdxEn = 1;
7229     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7230       IdxEn = Idx->getZExtValue() != 0;
7231     SDValue Ops[] = {
7232       Op.getOperand(0), // Chain
7233       Op.getOperand(2), // src
7234       Op.getOperand(3), // cmp
7235       Op.getOperand(4), // rsrc
7236       Op.getOperand(5), // vindex
7237       SDValue(),        // voffset -- will be set by setBufferOffsets
7238       SDValue(),        // soffset -- will be set by setBufferOffsets
7239       SDValue(),        // offset -- will be set by setBufferOffsets
7240       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7241       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7242     };
7243     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7244     // We don't know the offset if vindex is non-zero, so clear it.
7245     if (IdxEn)
7246       Offset = 0;
7247     EVT VT = Op.getValueType();
7248     auto *M = cast<MemSDNode>(Op);
7249     M->getMemOperand()->setOffset(Offset);
7250 
7251     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7252                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7253   }
7254   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7255     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7256     SDValue Ops[] = {
7257       Op.getOperand(0), // Chain
7258       Op.getOperand(2), // src
7259       Op.getOperand(3), // cmp
7260       Op.getOperand(4), // rsrc
7261       DAG.getConstant(0, DL, MVT::i32), // vindex
7262       Offsets.first,    // voffset
7263       Op.getOperand(6), // soffset
7264       Offsets.second,   // offset
7265       Op.getOperand(7), // cachepolicy
7266       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7267     };
7268     EVT VT = Op.getValueType();
7269     auto *M = cast<MemSDNode>(Op);
7270     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7271 
7272     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7273                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7274   }
7275   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7276     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7277     SDValue Ops[] = {
7278       Op.getOperand(0), // Chain
7279       Op.getOperand(2), // src
7280       Op.getOperand(3), // cmp
7281       Op.getOperand(4), // rsrc
7282       Op.getOperand(5), // vindex
7283       Offsets.first,    // voffset
7284       Op.getOperand(7), // soffset
7285       Offsets.second,   // offset
7286       Op.getOperand(8), // cachepolicy
7287       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7288     };
7289     EVT VT = Op.getValueType();
7290     auto *M = cast<MemSDNode>(Op);
7291     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7292                                                         Ops[4]));
7293 
7294     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7295                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7296   }
7297   case Intrinsic::amdgcn_global_atomic_fadd: {
7298     if (!Op.getValue(0).use_empty()) {
7299       DiagnosticInfoUnsupported
7300         NoFpRet(DAG.getMachineFunction().getFunction(),
7301                 "return versions of fp atomics not supported",
7302                 DL.getDebugLoc(), DS_Error);
7303       DAG.getContext()->diagnose(NoFpRet);
7304       return SDValue();
7305     }
7306     MemSDNode *M = cast<MemSDNode>(Op);
7307     SDValue Ops[] = {
7308       M->getOperand(0), // Chain
7309       M->getOperand(2), // Ptr
7310       M->getOperand(3)  // Value
7311     };
7312 
7313     EVT VT = Op.getOperand(3).getValueType();
7314     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7315                          DAG.getVTList(VT, MVT::Other), Ops,
7316                          M->getMemOperand());
7317   }
7318   case Intrinsic::amdgcn_image_bvh_intersect_ray: {
7319     SDLoc DL(Op);
7320     MemSDNode *M = cast<MemSDNode>(Op);
7321     SDValue NodePtr = M->getOperand(2);
7322     SDValue RayExtent = M->getOperand(3);
7323     SDValue RayOrigin = M->getOperand(4);
7324     SDValue RayDir = M->getOperand(5);
7325     SDValue RayInvDir = M->getOperand(6);
7326     SDValue TDescr = M->getOperand(7);
7327 
7328     assert(NodePtr.getValueType() == MVT::i32 ||
7329            NodePtr.getValueType() == MVT::i64);
7330     assert(RayDir.getValueType() == MVT::v4f16 ||
7331            RayDir.getValueType() == MVT::v4f32);
7332 
7333     bool IsA16 = RayDir.getValueType().getVectorElementType() == MVT::f16;
7334     bool Is64 = NodePtr.getValueType() == MVT::i64;
7335     unsigned Opcode = IsA16 ? Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_a16_nsa
7336                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_a16_nsa
7337                             : Is64 ? AMDGPU::IMAGE_BVH64_INTERSECT_RAY_nsa
7338                                    : AMDGPU::IMAGE_BVH_INTERSECT_RAY_nsa;
7339 
7340     SmallVector<SDValue, 16> Ops;
7341 
7342     auto packLanes = [&DAG, &Ops, &DL] (SDValue Op, bool IsAligned) {
7343       SmallVector<SDValue, 3> Lanes;
7344       DAG.ExtractVectorElements(Op, Lanes, 0, 3);
7345       if (Lanes[0].getValueSizeInBits() == 32) {
7346         for (unsigned I = 0; I < 3; ++I)
7347           Ops.push_back(DAG.getBitcast(MVT::i32, Lanes[I]));
7348       } else {
7349         if (IsAligned) {
7350           Ops.push_back(
7351             DAG.getBitcast(MVT::i32,
7352                            DAG.getBuildVector(MVT::v2f16, DL,
7353                                               { Lanes[0], Lanes[1] })));
7354           Ops.push_back(Lanes[2]);
7355         } else {
7356           SDValue Elt0 = Ops.pop_back_val();
7357           Ops.push_back(
7358             DAG.getBitcast(MVT::i32,
7359                            DAG.getBuildVector(MVT::v2f16, DL,
7360                                               { Elt0, Lanes[0] })));
7361           Ops.push_back(
7362             DAG.getBitcast(MVT::i32,
7363                            DAG.getBuildVector(MVT::v2f16, DL,
7364                                               { Lanes[1], Lanes[2] })));
7365         }
7366       }
7367     };
7368 
7369     if (Is64)
7370       DAG.ExtractVectorElements(DAG.getBitcast(MVT::v2i32, NodePtr), Ops, 0, 2);
7371     else
7372       Ops.push_back(NodePtr);
7373 
7374     Ops.push_back(DAG.getBitcast(MVT::i32, RayExtent));
7375     packLanes(RayOrigin, true);
7376     packLanes(RayDir, true);
7377     packLanes(RayInvDir, false);
7378     Ops.push_back(TDescr);
7379     if (IsA16)
7380       Ops.push_back(DAG.getTargetConstant(1, DL, MVT::i1));
7381     Ops.push_back(M->getChain());
7382 
7383     auto *NewNode = DAG.getMachineNode(Opcode, DL, M->getVTList(), Ops);
7384     MachineMemOperand *MemRef = M->getMemOperand();
7385     DAG.setNodeMemRefs(NewNode, {MemRef});
7386     return SDValue(NewNode, 0);
7387   }
7388   default:
7389     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7390             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7391       return lowerImage(Op, ImageDimIntr, DAG, true);
7392 
7393     return SDValue();
7394   }
7395 }
7396 
7397 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7398 // dwordx4 if on SI.
7399 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7400                                               SDVTList VTList,
7401                                               ArrayRef<SDValue> Ops, EVT MemVT,
7402                                               MachineMemOperand *MMO,
7403                                               SelectionDAG &DAG) const {
7404   EVT VT = VTList.VTs[0];
7405   EVT WidenedVT = VT;
7406   EVT WidenedMemVT = MemVT;
7407   if (!Subtarget->hasDwordx3LoadStores() &&
7408       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7409     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7410                                  WidenedVT.getVectorElementType(), 4);
7411     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7412                                     WidenedMemVT.getVectorElementType(), 4);
7413     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7414   }
7415 
7416   assert(VTList.NumVTs == 2);
7417   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7418 
7419   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7420                                        WidenedMemVT, MMO);
7421   if (WidenedVT != VT) {
7422     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7423                                DAG.getVectorIdxConstant(0, DL));
7424     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7425   }
7426   return NewOp;
7427 }
7428 
7429 SDValue SITargetLowering::handleD16VData(SDValue VData, SelectionDAG &DAG,
7430                                          bool ImageStore) const {
7431   EVT StoreVT = VData.getValueType();
7432 
7433   // No change for f16 and legal vector D16 types.
7434   if (!StoreVT.isVector())
7435     return VData;
7436 
7437   SDLoc DL(VData);
7438   unsigned NumElements = StoreVT.getVectorNumElements();
7439 
7440   if (Subtarget->hasUnpackedD16VMem()) {
7441     // We need to unpack the packed data to store.
7442     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7443     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7444 
7445     EVT EquivStoreVT =
7446         EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumElements);
7447     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7448     return DAG.UnrollVectorOp(ZExt.getNode());
7449   } else if (NumElements == 3) {
7450     EVT IntStoreVT =
7451         EVT::getIntegerVT(*DAG.getContext(), StoreVT.getStoreSizeInBits());
7452     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7453 
7454     EVT WidenedStoreVT = EVT::getVectorVT(
7455         *DAG.getContext(), StoreVT.getVectorElementType(), NumElements + 1);
7456     EVT WidenedIntVT = EVT::getIntegerVT(*DAG.getContext(),
7457                                          WidenedStoreVT.getStoreSizeInBits());
7458     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenedIntVT, IntVData);
7459     return DAG.getNode(ISD::BITCAST, DL, WidenedStoreVT, ZExt);
7460   }
7461 
7462   // The sq block of gfx8.1 does not estimate register use correctly for d16
7463   // image store instructions. The data operand is computed as if it were not a
7464   // d16 image instruction.
7465   if (ImageStore && Subtarget->hasImageStoreD16Bug()) {
7466     // Bitcast to i16
7467     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7468     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7469 
7470     // Decompose into scalars
7471     SmallVector<SDValue, 4> Elts;
7472     DAG.ExtractVectorElements(IntVData, Elts);
7473 
7474     // Group pairs of i16 into v2i16 and bitcast to i32
7475     SmallVector<SDValue, 4> PackedElts;
7476     for (unsigned I = 0; I < Elts.size() / 2; I += 1) {
7477       SDValue Pair =
7478           DAG.getBuildVector(MVT::v2i16, DL, {Elts[I * 2], Elts[I * 2 + 1]});
7479       SDValue IntPair = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Pair);
7480       PackedElts.push_back(IntPair);
7481     }
7482 
7483     // Pad using UNDEF
7484     PackedElts.resize(PackedElts.size() * 2, DAG.getUNDEF(MVT::i32));
7485 
7486     // Build final vector
7487     EVT VecVT =
7488         EVT::getVectorVT(*DAG.getContext(), MVT::i32, PackedElts.size());
7489     return DAG.getBuildVector(VecVT, DL, PackedElts);
7490   }
7491 
7492   assert(isTypeLegal(StoreVT));
7493   return VData;
7494 }
7495 
7496 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7497                                               SelectionDAG &DAG) const {
7498   SDLoc DL(Op);
7499   SDValue Chain = Op.getOperand(0);
7500   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7501   MachineFunction &MF = DAG.getMachineFunction();
7502 
7503   switch (IntrinsicID) {
7504   case Intrinsic::amdgcn_exp_compr: {
7505     SDValue Src0 = Op.getOperand(4);
7506     SDValue Src1 = Op.getOperand(5);
7507     // Hack around illegal type on SI by directly selecting it.
7508     if (isTypeLegal(Src0.getValueType()))
7509       return SDValue();
7510 
7511     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7512     SDValue Undef = DAG.getUNDEF(MVT::f32);
7513     const SDValue Ops[] = {
7514       Op.getOperand(2), // tgt
7515       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7516       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7517       Undef, // src2
7518       Undef, // src3
7519       Op.getOperand(7), // vm
7520       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7521       Op.getOperand(3), // en
7522       Op.getOperand(0) // Chain
7523     };
7524 
7525     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7526     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7527   }
7528   case Intrinsic::amdgcn_s_barrier: {
7529     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7530       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7531       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7532       if (WGSize <= ST.getWavefrontSize())
7533         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7534                                           Op.getOperand(0)), 0);
7535     }
7536     return SDValue();
7537   };
7538   case Intrinsic::amdgcn_tbuffer_store: {
7539     SDValue VData = Op.getOperand(2);
7540     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7541     if (IsD16)
7542       VData = handleD16VData(VData, DAG);
7543     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7544     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7545     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7546     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7547     unsigned IdxEn = 1;
7548     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7549       IdxEn = Idx->getZExtValue() != 0;
7550     SDValue Ops[] = {
7551       Chain,
7552       VData,             // vdata
7553       Op.getOperand(3),  // rsrc
7554       Op.getOperand(4),  // vindex
7555       Op.getOperand(5),  // voffset
7556       Op.getOperand(6),  // soffset
7557       Op.getOperand(7),  // offset
7558       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7559       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7560       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7561     };
7562     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7563                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7564     MemSDNode *M = cast<MemSDNode>(Op);
7565     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7566                                    M->getMemoryVT(), M->getMemOperand());
7567   }
7568 
7569   case Intrinsic::amdgcn_struct_tbuffer_store: {
7570     SDValue VData = Op.getOperand(2);
7571     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7572     if (IsD16)
7573       VData = handleD16VData(VData, DAG);
7574     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7575     SDValue Ops[] = {
7576       Chain,
7577       VData,             // vdata
7578       Op.getOperand(3),  // rsrc
7579       Op.getOperand(4),  // vindex
7580       Offsets.first,     // voffset
7581       Op.getOperand(6),  // soffset
7582       Offsets.second,    // offset
7583       Op.getOperand(7),  // format
7584       Op.getOperand(8),  // cachepolicy, swizzled buffer
7585       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7586     };
7587     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7588                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7589     MemSDNode *M = cast<MemSDNode>(Op);
7590     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7591                                    M->getMemoryVT(), M->getMemOperand());
7592   }
7593 
7594   case Intrinsic::amdgcn_raw_tbuffer_store: {
7595     SDValue VData = Op.getOperand(2);
7596     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7597     if (IsD16)
7598       VData = handleD16VData(VData, DAG);
7599     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7600     SDValue Ops[] = {
7601       Chain,
7602       VData,             // vdata
7603       Op.getOperand(3),  // rsrc
7604       DAG.getConstant(0, DL, MVT::i32), // vindex
7605       Offsets.first,     // voffset
7606       Op.getOperand(5),  // soffset
7607       Offsets.second,    // offset
7608       Op.getOperand(6),  // format
7609       Op.getOperand(7),  // cachepolicy, swizzled buffer
7610       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7611     };
7612     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7613                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7614     MemSDNode *M = cast<MemSDNode>(Op);
7615     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7616                                    M->getMemoryVT(), M->getMemOperand());
7617   }
7618 
7619   case Intrinsic::amdgcn_buffer_store:
7620   case Intrinsic::amdgcn_buffer_store_format: {
7621     SDValue VData = Op.getOperand(2);
7622     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7623     if (IsD16)
7624       VData = handleD16VData(VData, DAG);
7625     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7626     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7627     unsigned IdxEn = 1;
7628     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7629       IdxEn = Idx->getZExtValue() != 0;
7630     SDValue Ops[] = {
7631       Chain,
7632       VData,
7633       Op.getOperand(3), // rsrc
7634       Op.getOperand(4), // vindex
7635       SDValue(), // voffset -- will be set by setBufferOffsets
7636       SDValue(), // soffset -- will be set by setBufferOffsets
7637       SDValue(), // offset -- will be set by setBufferOffsets
7638       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7639       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7640     };
7641     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7642     // We don't know the offset if vindex is non-zero, so clear it.
7643     if (IdxEn)
7644       Offset = 0;
7645     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7646                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7647     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7648     MemSDNode *M = cast<MemSDNode>(Op);
7649     M->getMemOperand()->setOffset(Offset);
7650 
7651     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7652     EVT VDataType = VData.getValueType().getScalarType();
7653     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7654       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7655 
7656     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7657                                    M->getMemoryVT(), M->getMemOperand());
7658   }
7659 
7660   case Intrinsic::amdgcn_raw_buffer_store:
7661   case Intrinsic::amdgcn_raw_buffer_store_format: {
7662     const bool IsFormat =
7663         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7664 
7665     SDValue VData = Op.getOperand(2);
7666     EVT VDataVT = VData.getValueType();
7667     EVT EltType = VDataVT.getScalarType();
7668     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7669     if (IsD16) {
7670       VData = handleD16VData(VData, DAG);
7671       VDataVT = VData.getValueType();
7672     }
7673 
7674     if (!isTypeLegal(VDataVT)) {
7675       VData =
7676           DAG.getNode(ISD::BITCAST, DL,
7677                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7678     }
7679 
7680     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7681     SDValue Ops[] = {
7682       Chain,
7683       VData,
7684       Op.getOperand(3), // rsrc
7685       DAG.getConstant(0, DL, MVT::i32), // vindex
7686       Offsets.first,    // voffset
7687       Op.getOperand(5), // soffset
7688       Offsets.second,   // offset
7689       Op.getOperand(6), // cachepolicy, swizzled buffer
7690       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7691     };
7692     unsigned Opc =
7693         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7694     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7695     MemSDNode *M = cast<MemSDNode>(Op);
7696     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7697 
7698     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7699     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7700       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7701 
7702     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7703                                    M->getMemoryVT(), M->getMemOperand());
7704   }
7705 
7706   case Intrinsic::amdgcn_struct_buffer_store:
7707   case Intrinsic::amdgcn_struct_buffer_store_format: {
7708     const bool IsFormat =
7709         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7710 
7711     SDValue VData = Op.getOperand(2);
7712     EVT VDataVT = VData.getValueType();
7713     EVT EltType = VDataVT.getScalarType();
7714     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7715 
7716     if (IsD16) {
7717       VData = handleD16VData(VData, DAG);
7718       VDataVT = VData.getValueType();
7719     }
7720 
7721     if (!isTypeLegal(VDataVT)) {
7722       VData =
7723           DAG.getNode(ISD::BITCAST, DL,
7724                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7725     }
7726 
7727     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7728     SDValue Ops[] = {
7729       Chain,
7730       VData,
7731       Op.getOperand(3), // rsrc
7732       Op.getOperand(4), // vindex
7733       Offsets.first,    // voffset
7734       Op.getOperand(6), // soffset
7735       Offsets.second,   // offset
7736       Op.getOperand(7), // cachepolicy, swizzled buffer
7737       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7738     };
7739     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7740                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7741     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7742     MemSDNode *M = cast<MemSDNode>(Op);
7743     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7744                                                         Ops[3]));
7745 
7746     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7747     EVT VDataType = VData.getValueType().getScalarType();
7748     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7749       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7750 
7751     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7752                                    M->getMemoryVT(), M->getMemOperand());
7753   }
7754   case Intrinsic::amdgcn_end_cf:
7755     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7756                                       Op->getOperand(2), Chain), 0);
7757 
7758   default: {
7759     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7760             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7761       return lowerImage(Op, ImageDimIntr, DAG, true);
7762 
7763     return Op;
7764   }
7765   }
7766 }
7767 
7768 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7769 // offset (the offset that is included in bounds checking and swizzling, to be
7770 // split between the instruction's voffset and immoffset fields) and soffset
7771 // (the offset that is excluded from bounds checking and swizzling, to go in
7772 // the instruction's soffset field).  This function takes the first kind of
7773 // offset and figures out how to split it between voffset and immoffset.
7774 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7775     SDValue Offset, SelectionDAG &DAG) const {
7776   SDLoc DL(Offset);
7777   const unsigned MaxImm = 4095;
7778   SDValue N0 = Offset;
7779   ConstantSDNode *C1 = nullptr;
7780 
7781   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7782     N0 = SDValue();
7783   else if (DAG.isBaseWithConstantOffset(N0)) {
7784     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7785     N0 = N0.getOperand(0);
7786   }
7787 
7788   if (C1) {
7789     unsigned ImmOffset = C1->getZExtValue();
7790     // If the immediate value is too big for the immoffset field, put the value
7791     // and -4096 into the immoffset field so that the value that is copied/added
7792     // for the voffset field is a multiple of 4096, and it stands more chance
7793     // of being CSEd with the copy/add for another similar load/store.
7794     // However, do not do that rounding down to a multiple of 4096 if that is a
7795     // negative number, as it appears to be illegal to have a negative offset
7796     // in the vgpr, even if adding the immediate offset makes it positive.
7797     unsigned Overflow = ImmOffset & ~MaxImm;
7798     ImmOffset -= Overflow;
7799     if ((int32_t)Overflow < 0) {
7800       Overflow += ImmOffset;
7801       ImmOffset = 0;
7802     }
7803     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7804     if (Overflow) {
7805       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7806       if (!N0)
7807         N0 = OverflowVal;
7808       else {
7809         SDValue Ops[] = { N0, OverflowVal };
7810         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7811       }
7812     }
7813   }
7814   if (!N0)
7815     N0 = DAG.getConstant(0, DL, MVT::i32);
7816   if (!C1)
7817     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7818   return {N0, SDValue(C1, 0)};
7819 }
7820 
7821 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7822 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7823 // pointed to by Offsets.
7824 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7825                                             SelectionDAG &DAG, SDValue *Offsets,
7826                                             Align Alignment) const {
7827   SDLoc DL(CombinedOffset);
7828   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7829     uint32_t Imm = C->getZExtValue();
7830     uint32_t SOffset, ImmOffset;
7831     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget,
7832                                  Alignment)) {
7833       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7834       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7835       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7836       return SOffset + ImmOffset;
7837     }
7838   }
7839   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7840     SDValue N0 = CombinedOffset.getOperand(0);
7841     SDValue N1 = CombinedOffset.getOperand(1);
7842     uint32_t SOffset, ImmOffset;
7843     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7844     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7845                                                 Subtarget, Alignment)) {
7846       Offsets[0] = N0;
7847       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7848       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7849       return 0;
7850     }
7851   }
7852   Offsets[0] = CombinedOffset;
7853   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7854   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7855   return 0;
7856 }
7857 
7858 // Handle 8 bit and 16 bit buffer loads
7859 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7860                                                      EVT LoadVT, SDLoc DL,
7861                                                      ArrayRef<SDValue> Ops,
7862                                                      MemSDNode *M) const {
7863   EVT IntVT = LoadVT.changeTypeToInteger();
7864   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7865          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7866 
7867   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7868   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7869                                                Ops, IntVT,
7870                                                M->getMemOperand());
7871   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7872   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7873 
7874   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7875 }
7876 
7877 // Handle 8 bit and 16 bit buffer stores
7878 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7879                                                       EVT VDataType, SDLoc DL,
7880                                                       SDValue Ops[],
7881                                                       MemSDNode *M) const {
7882   if (VDataType == MVT::f16)
7883     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7884 
7885   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7886   Ops[1] = BufferStoreExt;
7887   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7888                                  AMDGPUISD::BUFFER_STORE_SHORT;
7889   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7890   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7891                                      M->getMemOperand());
7892 }
7893 
7894 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7895                                  ISD::LoadExtType ExtType, SDValue Op,
7896                                  const SDLoc &SL, EVT VT) {
7897   if (VT.bitsLT(Op.getValueType()))
7898     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7899 
7900   switch (ExtType) {
7901   case ISD::SEXTLOAD:
7902     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7903   case ISD::ZEXTLOAD:
7904     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7905   case ISD::EXTLOAD:
7906     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7907   case ISD::NON_EXTLOAD:
7908     return Op;
7909   }
7910 
7911   llvm_unreachable("invalid ext type");
7912 }
7913 
7914 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7915   SelectionDAG &DAG = DCI.DAG;
7916   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7917     return SDValue();
7918 
7919   // FIXME: Constant loads should all be marked invariant.
7920   unsigned AS = Ld->getAddressSpace();
7921   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7922       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7923       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7924     return SDValue();
7925 
7926   // Don't do this early, since it may interfere with adjacent load merging for
7927   // illegal types. We can avoid losing alignment information for exotic types
7928   // pre-legalize.
7929   EVT MemVT = Ld->getMemoryVT();
7930   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7931       MemVT.getSizeInBits() >= 32)
7932     return SDValue();
7933 
7934   SDLoc SL(Ld);
7935 
7936   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7937          "unexpected vector extload");
7938 
7939   // TODO: Drop only high part of range.
7940   SDValue Ptr = Ld->getBasePtr();
7941   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7942                                 MVT::i32, SL, Ld->getChain(), Ptr,
7943                                 Ld->getOffset(),
7944                                 Ld->getPointerInfo(), MVT::i32,
7945                                 Ld->getAlignment(),
7946                                 Ld->getMemOperand()->getFlags(),
7947                                 Ld->getAAInfo(),
7948                                 nullptr); // Drop ranges
7949 
7950   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7951   if (MemVT.isFloatingPoint()) {
7952     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7953            "unexpected fp extload");
7954     TruncVT = MemVT.changeTypeToInteger();
7955   }
7956 
7957   SDValue Cvt = NewLoad;
7958   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7959     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7960                       DAG.getValueType(TruncVT));
7961   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7962              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7963     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7964   } else {
7965     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7966   }
7967 
7968   EVT VT = Ld->getValueType(0);
7969   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7970 
7971   DCI.AddToWorklist(Cvt.getNode());
7972 
7973   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7974   // the appropriate extension from the 32-bit load.
7975   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7976   DCI.AddToWorklist(Cvt.getNode());
7977 
7978   // Handle conversion back to floating point if necessary.
7979   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7980 
7981   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7982 }
7983 
7984 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7985   SDLoc DL(Op);
7986   LoadSDNode *Load = cast<LoadSDNode>(Op);
7987   ISD::LoadExtType ExtType = Load->getExtensionType();
7988   EVT MemVT = Load->getMemoryVT();
7989 
7990   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7991     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7992       return SDValue();
7993 
7994     // FIXME: Copied from PPC
7995     // First, load into 32 bits, then truncate to 1 bit.
7996 
7997     SDValue Chain = Load->getChain();
7998     SDValue BasePtr = Load->getBasePtr();
7999     MachineMemOperand *MMO = Load->getMemOperand();
8000 
8001     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
8002 
8003     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
8004                                    BasePtr, RealMemVT, MMO);
8005 
8006     if (!MemVT.isVector()) {
8007       SDValue Ops[] = {
8008         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
8009         NewLD.getValue(1)
8010       };
8011 
8012       return DAG.getMergeValues(Ops, DL);
8013     }
8014 
8015     SmallVector<SDValue, 3> Elts;
8016     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
8017       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
8018                                 DAG.getConstant(I, DL, MVT::i32));
8019 
8020       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
8021     }
8022 
8023     SDValue Ops[] = {
8024       DAG.getBuildVector(MemVT, DL, Elts),
8025       NewLD.getValue(1)
8026     };
8027 
8028     return DAG.getMergeValues(Ops, DL);
8029   }
8030 
8031   if (!MemVT.isVector())
8032     return SDValue();
8033 
8034   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
8035          "Custom lowering for non-i32 vectors hasn't been implemented.");
8036 
8037   unsigned Alignment = Load->getAlignment();
8038   unsigned AS = Load->getAddressSpace();
8039   if (Subtarget->hasLDSMisalignedBug() &&
8040       AS == AMDGPUAS::FLAT_ADDRESS &&
8041       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
8042     return SplitVectorLoad(Op, DAG);
8043   }
8044 
8045   MachineFunction &MF = DAG.getMachineFunction();
8046   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8047   // If there is a possibilty that flat instruction access scratch memory
8048   // then we need to use the same legalization rules we use for private.
8049   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8050       !Subtarget->hasMultiDwordFlatScratchAddressing())
8051     AS = MFI->hasFlatScratchInit() ?
8052          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8053 
8054   unsigned NumElements = MemVT.getVectorNumElements();
8055 
8056   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8057       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
8058     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
8059       if (MemVT.isPow2VectorType())
8060         return SDValue();
8061       if (NumElements == 3)
8062         return WidenVectorLoad(Op, DAG);
8063       return SplitVectorLoad(Op, DAG);
8064     }
8065     // Non-uniform loads will be selected to MUBUF instructions, so they
8066     // have the same legalization requirements as global and private
8067     // loads.
8068     //
8069   }
8070 
8071   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8072       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8073       AS == AMDGPUAS::GLOBAL_ADDRESS) {
8074     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
8075         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
8076         Alignment >= 4 && NumElements < 32) {
8077       if (MemVT.isPow2VectorType())
8078         return SDValue();
8079       if (NumElements == 3)
8080         return WidenVectorLoad(Op, DAG);
8081       return SplitVectorLoad(Op, DAG);
8082     }
8083     // Non-uniform loads will be selected to MUBUF instructions, so they
8084     // have the same legalization requirements as global and private
8085     // loads.
8086     //
8087   }
8088   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
8089       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
8090       AS == AMDGPUAS::GLOBAL_ADDRESS ||
8091       AS == AMDGPUAS::FLAT_ADDRESS) {
8092     if (NumElements > 4)
8093       return SplitVectorLoad(Op, DAG);
8094     // v3 loads not supported on SI.
8095     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8096       return WidenVectorLoad(Op, DAG);
8097     // v3 and v4 loads are supported for private and global memory.
8098     return SDValue();
8099   }
8100   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8101     // Depending on the setting of the private_element_size field in the
8102     // resource descriptor, we can only make private accesses up to a certain
8103     // size.
8104     switch (Subtarget->getMaxPrivateElementSize()) {
8105     case 4: {
8106       SDValue Ops[2];
8107       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
8108       return DAG.getMergeValues(Ops, DL);
8109     }
8110     case 8:
8111       if (NumElements > 2)
8112         return SplitVectorLoad(Op, DAG);
8113       return SDValue();
8114     case 16:
8115       // Same as global/flat
8116       if (NumElements > 4)
8117         return SplitVectorLoad(Op, DAG);
8118       // v3 loads not supported on SI.
8119       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8120         return WidenVectorLoad(Op, DAG);
8121       return SDValue();
8122     default:
8123       llvm_unreachable("unsupported private_element_size");
8124     }
8125   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8126     // Use ds_read_b128 or ds_read_b96 when possible.
8127     if (Subtarget->hasDS96AndDS128() &&
8128         ((Subtarget->useDS128() && MemVT.getStoreSize() == 16) ||
8129          MemVT.getStoreSize() == 12) &&
8130         allowsMisalignedMemoryAccessesImpl(MemVT.getSizeInBits(), AS,
8131                                            Load->getAlign()))
8132       return SDValue();
8133 
8134     if (NumElements > 2)
8135       return SplitVectorLoad(Op, DAG);
8136 
8137     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8138     // address is negative, then the instruction is incorrectly treated as
8139     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8140     // loads here to avoid emitting ds_read2_b32. We may re-combine the
8141     // load later in the SILoadStoreOptimizer.
8142     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
8143         NumElements == 2 && MemVT.getStoreSize() == 8 &&
8144         Load->getAlignment() < 8) {
8145       return SplitVectorLoad(Op, DAG);
8146     }
8147   }
8148 
8149   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8150                                       MemVT, *Load->getMemOperand())) {
8151     SDValue Ops[2];
8152     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
8153     return DAG.getMergeValues(Ops, DL);
8154   }
8155 
8156   return SDValue();
8157 }
8158 
8159 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
8160   EVT VT = Op.getValueType();
8161   assert(VT.getSizeInBits() == 64);
8162 
8163   SDLoc DL(Op);
8164   SDValue Cond = Op.getOperand(0);
8165 
8166   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
8167   SDValue One = DAG.getConstant(1, DL, MVT::i32);
8168 
8169   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
8170   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
8171 
8172   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
8173   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
8174 
8175   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
8176 
8177   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
8178   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
8179 
8180   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
8181 
8182   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
8183   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
8184 }
8185 
8186 // Catch division cases where we can use shortcuts with rcp and rsq
8187 // instructions.
8188 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
8189                                               SelectionDAG &DAG) const {
8190   SDLoc SL(Op);
8191   SDValue LHS = Op.getOperand(0);
8192   SDValue RHS = Op.getOperand(1);
8193   EVT VT = Op.getValueType();
8194   const SDNodeFlags Flags = Op->getFlags();
8195 
8196   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
8197                             Flags.hasApproximateFuncs();
8198 
8199   // Without !fpmath accuracy information, we can't do more because we don't
8200   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
8201   if (!AllowInaccurateRcp)
8202     return SDValue();
8203 
8204   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
8205     if (CLHS->isExactlyValue(1.0)) {
8206       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
8207       // the CI documentation has a worst case error of 1 ulp.
8208       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
8209       // use it as long as we aren't trying to use denormals.
8210       //
8211       // v_rcp_f16 and v_rsq_f16 DO support denormals.
8212 
8213       // 1.0 / sqrt(x) -> rsq(x)
8214 
8215       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
8216       // error seems really high at 2^29 ULP.
8217       if (RHS.getOpcode() == ISD::FSQRT)
8218         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
8219 
8220       // 1.0 / x -> rcp(x)
8221       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8222     }
8223 
8224     // Same as for 1.0, but expand the sign out of the constant.
8225     if (CLHS->isExactlyValue(-1.0)) {
8226       // -1.0 / x -> rcp (fneg x)
8227       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
8228       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
8229     }
8230   }
8231 
8232   // Turn into multiply by the reciprocal.
8233   // x / y -> x * (1.0 / y)
8234   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
8235   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
8236 }
8237 
8238 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8239                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
8240                           SDNodeFlags Flags) {
8241   if (GlueChain->getNumValues() <= 1) {
8242     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
8243   }
8244 
8245   assert(GlueChain->getNumValues() == 3);
8246 
8247   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8248   switch (Opcode) {
8249   default: llvm_unreachable("no chain equivalent for opcode");
8250   case ISD::FMUL:
8251     Opcode = AMDGPUISD::FMUL_W_CHAIN;
8252     break;
8253   }
8254 
8255   return DAG.getNode(Opcode, SL, VTList,
8256                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
8257                      Flags);
8258 }
8259 
8260 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
8261                            EVT VT, SDValue A, SDValue B, SDValue C,
8262                            SDValue GlueChain, SDNodeFlags Flags) {
8263   if (GlueChain->getNumValues() <= 1) {
8264     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
8265   }
8266 
8267   assert(GlueChain->getNumValues() == 3);
8268 
8269   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
8270   switch (Opcode) {
8271   default: llvm_unreachable("no chain equivalent for opcode");
8272   case ISD::FMA:
8273     Opcode = AMDGPUISD::FMA_W_CHAIN;
8274     break;
8275   }
8276 
8277   return DAG.getNode(Opcode, SL, VTList,
8278                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
8279                      Flags);
8280 }
8281 
8282 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
8283   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8284     return FastLowered;
8285 
8286   SDLoc SL(Op);
8287   SDValue Src0 = Op.getOperand(0);
8288   SDValue Src1 = Op.getOperand(1);
8289 
8290   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8291   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8292 
8293   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8294   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8295 
8296   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8297   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8298 
8299   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8300 }
8301 
8302 // Faster 2.5 ULP division that does not support denormals.
8303 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8304   SDLoc SL(Op);
8305   SDValue LHS = Op.getOperand(1);
8306   SDValue RHS = Op.getOperand(2);
8307 
8308   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8309 
8310   const APFloat K0Val(BitsToFloat(0x6f800000));
8311   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8312 
8313   const APFloat K1Val(BitsToFloat(0x2f800000));
8314   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8315 
8316   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8317 
8318   EVT SetCCVT =
8319     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8320 
8321   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8322 
8323   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8324 
8325   // TODO: Should this propagate fast-math-flags?
8326   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8327 
8328   // rcp does not support denormals.
8329   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8330 
8331   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8332 
8333   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8334 }
8335 
8336 // Returns immediate value for setting the F32 denorm mode when using the
8337 // S_DENORM_MODE instruction.
8338 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8339                                           const SDLoc &SL, const GCNSubtarget *ST) {
8340   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8341   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8342                                 ? FP_DENORM_FLUSH_NONE
8343                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8344 
8345   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8346   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8347 }
8348 
8349 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8350   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8351     return FastLowered;
8352 
8353   // The selection matcher assumes anything with a chain selecting to a
8354   // mayRaiseFPException machine instruction. Since we're introducing a chain
8355   // here, we need to explicitly report nofpexcept for the regular fdiv
8356   // lowering.
8357   SDNodeFlags Flags = Op->getFlags();
8358   Flags.setNoFPExcept(true);
8359 
8360   SDLoc SL(Op);
8361   SDValue LHS = Op.getOperand(0);
8362   SDValue RHS = Op.getOperand(1);
8363 
8364   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8365 
8366   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8367 
8368   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8369                                           {RHS, RHS, LHS}, Flags);
8370   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8371                                         {LHS, RHS, LHS}, Flags);
8372 
8373   // Denominator is scaled to not be denormal, so using rcp is ok.
8374   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8375                                   DenominatorScaled, Flags);
8376   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8377                                      DenominatorScaled, Flags);
8378 
8379   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8380                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8381                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8382   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8383 
8384   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8385 
8386   if (!HasFP32Denormals) {
8387     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8388     // lowering. The chain dependence is insufficient, and we need glue. We do
8389     // not need the glue variants in a strictfp function.
8390 
8391     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8392 
8393     SDNode *EnableDenorm;
8394     if (Subtarget->hasDenormModeInst()) {
8395       const SDValue EnableDenormValue =
8396           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8397 
8398       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8399                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8400     } else {
8401       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8402                                                         SL, MVT::i32);
8403       EnableDenorm =
8404           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8405                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8406     }
8407 
8408     SDValue Ops[3] = {
8409       NegDivScale0,
8410       SDValue(EnableDenorm, 0),
8411       SDValue(EnableDenorm, 1)
8412     };
8413 
8414     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8415   }
8416 
8417   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8418                              ApproxRcp, One, NegDivScale0, Flags);
8419 
8420   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8421                              ApproxRcp, Fma0, Flags);
8422 
8423   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8424                            Fma1, Fma1, Flags);
8425 
8426   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8427                              NumeratorScaled, Mul, Flags);
8428 
8429   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8430                              Fma2, Fma1, Mul, Fma2, Flags);
8431 
8432   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8433                              NumeratorScaled, Fma3, Flags);
8434 
8435   if (!HasFP32Denormals) {
8436     SDNode *DisableDenorm;
8437     if (Subtarget->hasDenormModeInst()) {
8438       const SDValue DisableDenormValue =
8439           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8440 
8441       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8442                                   Fma4.getValue(1), DisableDenormValue,
8443                                   Fma4.getValue(2)).getNode();
8444     } else {
8445       const SDValue DisableDenormValue =
8446           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8447 
8448       DisableDenorm = DAG.getMachineNode(
8449           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8450           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8451     }
8452 
8453     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8454                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8455     DAG.setRoot(OutputChain);
8456   }
8457 
8458   SDValue Scale = NumeratorScaled.getValue(1);
8459   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8460                              {Fma4, Fma1, Fma3, Scale}, Flags);
8461 
8462   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8463 }
8464 
8465 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8466   if (DAG.getTarget().Options.UnsafeFPMath)
8467     return lowerFastUnsafeFDIV(Op, DAG);
8468 
8469   SDLoc SL(Op);
8470   SDValue X = Op.getOperand(0);
8471   SDValue Y = Op.getOperand(1);
8472 
8473   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8474 
8475   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8476 
8477   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8478 
8479   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8480 
8481   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8482 
8483   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8484 
8485   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8486 
8487   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8488 
8489   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8490 
8491   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8492   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8493 
8494   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8495                              NegDivScale0, Mul, DivScale1);
8496 
8497   SDValue Scale;
8498 
8499   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8500     // Workaround a hardware bug on SI where the condition output from div_scale
8501     // is not usable.
8502 
8503     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8504 
8505     // Figure out if the scale to use for div_fmas.
8506     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8507     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8508     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8509     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8510 
8511     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8512     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8513 
8514     SDValue Scale0Hi
8515       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8516     SDValue Scale1Hi
8517       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8518 
8519     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8520     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8521     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8522   } else {
8523     Scale = DivScale1.getValue(1);
8524   }
8525 
8526   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8527                              Fma4, Fma3, Mul, Scale);
8528 
8529   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8530 }
8531 
8532 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8533   EVT VT = Op.getValueType();
8534 
8535   if (VT == MVT::f32)
8536     return LowerFDIV32(Op, DAG);
8537 
8538   if (VT == MVT::f64)
8539     return LowerFDIV64(Op, DAG);
8540 
8541   if (VT == MVT::f16)
8542     return LowerFDIV16(Op, DAG);
8543 
8544   llvm_unreachable("Unexpected type for fdiv");
8545 }
8546 
8547 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8548   SDLoc DL(Op);
8549   StoreSDNode *Store = cast<StoreSDNode>(Op);
8550   EVT VT = Store->getMemoryVT();
8551 
8552   if (VT == MVT::i1) {
8553     return DAG.getTruncStore(Store->getChain(), DL,
8554        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8555        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8556   }
8557 
8558   assert(VT.isVector() &&
8559          Store->getValue().getValueType().getScalarType() == MVT::i32);
8560 
8561   unsigned AS = Store->getAddressSpace();
8562   if (Subtarget->hasLDSMisalignedBug() &&
8563       AS == AMDGPUAS::FLAT_ADDRESS &&
8564       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8565     return SplitVectorStore(Op, DAG);
8566   }
8567 
8568   MachineFunction &MF = DAG.getMachineFunction();
8569   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8570   // If there is a possibilty that flat instruction access scratch memory
8571   // then we need to use the same legalization rules we use for private.
8572   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8573       !Subtarget->hasMultiDwordFlatScratchAddressing())
8574     AS = MFI->hasFlatScratchInit() ?
8575          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8576 
8577   unsigned NumElements = VT.getVectorNumElements();
8578   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8579       AS == AMDGPUAS::FLAT_ADDRESS) {
8580     if (NumElements > 4)
8581       return SplitVectorStore(Op, DAG);
8582     // v3 stores not supported on SI.
8583     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8584       return SplitVectorStore(Op, DAG);
8585 
8586     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8587                                         VT, *Store->getMemOperand()))
8588       return expandUnalignedStore(Store, DAG);
8589 
8590     return SDValue();
8591   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8592     switch (Subtarget->getMaxPrivateElementSize()) {
8593     case 4:
8594       return scalarizeVectorStore(Store, DAG);
8595     case 8:
8596       if (NumElements > 2)
8597         return SplitVectorStore(Op, DAG);
8598       return SDValue();
8599     case 16:
8600       if (NumElements > 4 || NumElements == 3)
8601         return SplitVectorStore(Op, DAG);
8602       return SDValue();
8603     default:
8604       llvm_unreachable("unsupported private_element_size");
8605     }
8606   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8607     // Use ds_write_b128 or ds_write_b96 when possible.
8608     if (Subtarget->hasDS96AndDS128() &&
8609         ((Subtarget->useDS128() && VT.getStoreSize() == 16) ||
8610          (VT.getStoreSize() == 12)) &&
8611         allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AS,
8612                                            Store->getAlign()))
8613       return SDValue();
8614 
8615     if (NumElements > 2)
8616       return SplitVectorStore(Op, DAG);
8617 
8618     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8619     // address is negative, then the instruction is incorrectly treated as
8620     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8621     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8622     // store later in the SILoadStoreOptimizer.
8623     if (!Subtarget->hasUsableDSOffset() &&
8624         NumElements == 2 && VT.getStoreSize() == 8 &&
8625         Store->getAlignment() < 8) {
8626       return SplitVectorStore(Op, DAG);
8627     }
8628 
8629     if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8630                                         VT, *Store->getMemOperand())) {
8631       if (VT.isVector())
8632         return SplitVectorStore(Op, DAG);
8633       return expandUnalignedStore(Store, DAG);
8634     }
8635 
8636     return SDValue();
8637   } else {
8638     llvm_unreachable("unhandled address space");
8639   }
8640 }
8641 
8642 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8643   SDLoc DL(Op);
8644   EVT VT = Op.getValueType();
8645   SDValue Arg = Op.getOperand(0);
8646   SDValue TrigVal;
8647 
8648   // Propagate fast-math flags so that the multiply we introduce can be folded
8649   // if Arg is already the result of a multiply by constant.
8650   auto Flags = Op->getFlags();
8651 
8652   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8653 
8654   if (Subtarget->hasTrigReducedRange()) {
8655     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8656     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8657   } else {
8658     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8659   }
8660 
8661   switch (Op.getOpcode()) {
8662   case ISD::FCOS:
8663     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8664   case ISD::FSIN:
8665     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8666   default:
8667     llvm_unreachable("Wrong trig opcode");
8668   }
8669 }
8670 
8671 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8672   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8673   assert(AtomicNode->isCompareAndSwap());
8674   unsigned AS = AtomicNode->getAddressSpace();
8675 
8676   // No custom lowering required for local address space
8677   if (!AMDGPU::isFlatGlobalAddrSpace(AS))
8678     return Op;
8679 
8680   // Non-local address space requires custom lowering for atomic compare
8681   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8682   SDLoc DL(Op);
8683   SDValue ChainIn = Op.getOperand(0);
8684   SDValue Addr = Op.getOperand(1);
8685   SDValue Old = Op.getOperand(2);
8686   SDValue New = Op.getOperand(3);
8687   EVT VT = Op.getValueType();
8688   MVT SimpleVT = VT.getSimpleVT();
8689   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8690 
8691   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8692   SDValue Ops[] = { ChainIn, Addr, NewOld };
8693 
8694   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8695                                  Ops, VT, AtomicNode->getMemOperand());
8696 }
8697 
8698 //===----------------------------------------------------------------------===//
8699 // Custom DAG optimizations
8700 //===----------------------------------------------------------------------===//
8701 
8702 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8703                                                      DAGCombinerInfo &DCI) const {
8704   EVT VT = N->getValueType(0);
8705   EVT ScalarVT = VT.getScalarType();
8706   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8707     return SDValue();
8708 
8709   SelectionDAG &DAG = DCI.DAG;
8710   SDLoc DL(N);
8711 
8712   SDValue Src = N->getOperand(0);
8713   EVT SrcVT = Src.getValueType();
8714 
8715   // TODO: We could try to match extracting the higher bytes, which would be
8716   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8717   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8718   // about in practice.
8719   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8720     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8721       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8722       DCI.AddToWorklist(Cvt.getNode());
8723 
8724       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8725       if (ScalarVT != MVT::f32) {
8726         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8727                           DAG.getTargetConstant(0, DL, MVT::i32));
8728       }
8729       return Cvt;
8730     }
8731   }
8732 
8733   return SDValue();
8734 }
8735 
8736 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8737 
8738 // This is a variant of
8739 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8740 //
8741 // The normal DAG combiner will do this, but only if the add has one use since
8742 // that would increase the number of instructions.
8743 //
8744 // This prevents us from seeing a constant offset that can be folded into a
8745 // memory instruction's addressing mode. If we know the resulting add offset of
8746 // a pointer can be folded into an addressing offset, we can replace the pointer
8747 // operand with the add of new constant offset. This eliminates one of the uses,
8748 // and may allow the remaining use to also be simplified.
8749 //
8750 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8751                                                unsigned AddrSpace,
8752                                                EVT MemVT,
8753                                                DAGCombinerInfo &DCI) const {
8754   SDValue N0 = N->getOperand(0);
8755   SDValue N1 = N->getOperand(1);
8756 
8757   // We only do this to handle cases where it's profitable when there are
8758   // multiple uses of the add, so defer to the standard combine.
8759   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8760       N0->hasOneUse())
8761     return SDValue();
8762 
8763   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8764   if (!CN1)
8765     return SDValue();
8766 
8767   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8768   if (!CAdd)
8769     return SDValue();
8770 
8771   // If the resulting offset is too large, we can't fold it into the addressing
8772   // mode offset.
8773   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8774   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8775 
8776   AddrMode AM;
8777   AM.HasBaseReg = true;
8778   AM.BaseOffs = Offset.getSExtValue();
8779   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8780     return SDValue();
8781 
8782   SelectionDAG &DAG = DCI.DAG;
8783   SDLoc SL(N);
8784   EVT VT = N->getValueType(0);
8785 
8786   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8787   SDValue COffset = DAG.getConstant(Offset, SL, VT);
8788 
8789   SDNodeFlags Flags;
8790   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8791                           (N0.getOpcode() == ISD::OR ||
8792                            N0->getFlags().hasNoUnsignedWrap()));
8793 
8794   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8795 }
8796 
8797 /// MemSDNode::getBasePtr() does not work for intrinsics, which needs to offset
8798 /// by the chain and intrinsic ID. Theoretically we would also need to check the
8799 /// specific intrinsic, but they all place the pointer operand first.
8800 static unsigned getBasePtrIndex(const MemSDNode *N) {
8801   switch (N->getOpcode()) {
8802   case ISD::STORE:
8803   case ISD::INTRINSIC_W_CHAIN:
8804   case ISD::INTRINSIC_VOID:
8805     return 2;
8806   default:
8807     return 1;
8808   }
8809 }
8810 
8811 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8812                                                   DAGCombinerInfo &DCI) const {
8813   SelectionDAG &DAG = DCI.DAG;
8814   SDLoc SL(N);
8815 
8816   unsigned PtrIdx = getBasePtrIndex(N);
8817   SDValue Ptr = N->getOperand(PtrIdx);
8818 
8819   // TODO: We could also do this for multiplies.
8820   if (Ptr.getOpcode() == ISD::SHL) {
8821     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8822                                           N->getMemoryVT(), DCI);
8823     if (NewPtr) {
8824       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8825 
8826       NewOps[PtrIdx] = NewPtr;
8827       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8828     }
8829   }
8830 
8831   return SDValue();
8832 }
8833 
8834 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8835   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8836          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8837          (Opc == ISD::XOR && Val == 0);
8838 }
8839 
8840 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8841 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8842 // integer combine opportunities since most 64-bit operations are decomposed
8843 // this way.  TODO: We won't want this for SALU especially if it is an inline
8844 // immediate.
8845 SDValue SITargetLowering::splitBinaryBitConstantOp(
8846   DAGCombinerInfo &DCI,
8847   const SDLoc &SL,
8848   unsigned Opc, SDValue LHS,
8849   const ConstantSDNode *CRHS) const {
8850   uint64_t Val = CRHS->getZExtValue();
8851   uint32_t ValLo = Lo_32(Val);
8852   uint32_t ValHi = Hi_32(Val);
8853   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8854 
8855     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8856          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8857         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8858     // If we need to materialize a 64-bit immediate, it will be split up later
8859     // anyway. Avoid creating the harder to understand 64-bit immediate
8860     // materialization.
8861     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8862   }
8863 
8864   return SDValue();
8865 }
8866 
8867 // Returns true if argument is a boolean value which is not serialized into
8868 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8869 static bool isBoolSGPR(SDValue V) {
8870   if (V.getValueType() != MVT::i1)
8871     return false;
8872   switch (V.getOpcode()) {
8873   default: break;
8874   case ISD::SETCC:
8875   case ISD::AND:
8876   case ISD::OR:
8877   case ISD::XOR:
8878   case AMDGPUISD::FP_CLASS:
8879     return true;
8880   }
8881   return false;
8882 }
8883 
8884 // If a constant has all zeroes or all ones within each byte return it.
8885 // Otherwise return 0.
8886 static uint32_t getConstantPermuteMask(uint32_t C) {
8887   // 0xff for any zero byte in the mask
8888   uint32_t ZeroByteMask = 0;
8889   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8890   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8891   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8892   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8893   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8894   if ((NonZeroByteMask & C) != NonZeroByteMask)
8895     return 0; // Partial bytes selected.
8896   return C;
8897 }
8898 
8899 // Check if a node selects whole bytes from its operand 0 starting at a byte
8900 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8901 // or -1 if not succeeded.
8902 // Note byte select encoding:
8903 // value 0-3 selects corresponding source byte;
8904 // value 0xc selects zero;
8905 // value 0xff selects 0xff.
8906 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8907   assert(V.getValueSizeInBits() == 32);
8908 
8909   if (V.getNumOperands() != 2)
8910     return ~0;
8911 
8912   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8913   if (!N1)
8914     return ~0;
8915 
8916   uint32_t C = N1->getZExtValue();
8917 
8918   switch (V.getOpcode()) {
8919   default:
8920     break;
8921   case ISD::AND:
8922     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8923       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8924     }
8925     break;
8926 
8927   case ISD::OR:
8928     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8929       return (0x03020100 & ~ConstMask) | ConstMask;
8930     }
8931     break;
8932 
8933   case ISD::SHL:
8934     if (C % 8)
8935       return ~0;
8936 
8937     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8938 
8939   case ISD::SRL:
8940     if (C % 8)
8941       return ~0;
8942 
8943     return uint32_t(0x0c0c0c0c03020100ull >> C);
8944   }
8945 
8946   return ~0;
8947 }
8948 
8949 SDValue SITargetLowering::performAndCombine(SDNode *N,
8950                                             DAGCombinerInfo &DCI) const {
8951   if (DCI.isBeforeLegalize())
8952     return SDValue();
8953 
8954   SelectionDAG &DAG = DCI.DAG;
8955   EVT VT = N->getValueType(0);
8956   SDValue LHS = N->getOperand(0);
8957   SDValue RHS = N->getOperand(1);
8958 
8959 
8960   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8961   if (VT == MVT::i64 && CRHS) {
8962     if (SDValue Split
8963         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8964       return Split;
8965   }
8966 
8967   if (CRHS && VT == MVT::i32) {
8968     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8969     // nb = number of trailing zeroes in mask
8970     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8971     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8972     uint64_t Mask = CRHS->getZExtValue();
8973     unsigned Bits = countPopulation(Mask);
8974     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8975         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8976       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8977         unsigned Shift = CShift->getZExtValue();
8978         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8979         unsigned Offset = NB + Shift;
8980         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8981           SDLoc SL(N);
8982           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8983                                     LHS->getOperand(0),
8984                                     DAG.getConstant(Offset, SL, MVT::i32),
8985                                     DAG.getConstant(Bits, SL, MVT::i32));
8986           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8987           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8988                                     DAG.getValueType(NarrowVT));
8989           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8990                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8991           return Shl;
8992         }
8993       }
8994     }
8995 
8996     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8997     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8998         isa<ConstantSDNode>(LHS.getOperand(2))) {
8999       uint32_t Sel = getConstantPermuteMask(Mask);
9000       if (!Sel)
9001         return SDValue();
9002 
9003       // Select 0xc for all zero bytes
9004       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
9005       SDLoc DL(N);
9006       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9007                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9008     }
9009   }
9010 
9011   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
9012   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
9013   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
9014     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9015     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
9016 
9017     SDValue X = LHS.getOperand(0);
9018     SDValue Y = RHS.getOperand(0);
9019     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
9020       return SDValue();
9021 
9022     if (LCC == ISD::SETO) {
9023       if (X != LHS.getOperand(1))
9024         return SDValue();
9025 
9026       if (RCC == ISD::SETUNE) {
9027         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
9028         if (!C1 || !C1->isInfinity() || C1->isNegative())
9029           return SDValue();
9030 
9031         const uint32_t Mask = SIInstrFlags::N_NORMAL |
9032                               SIInstrFlags::N_SUBNORMAL |
9033                               SIInstrFlags::N_ZERO |
9034                               SIInstrFlags::P_ZERO |
9035                               SIInstrFlags::P_SUBNORMAL |
9036                               SIInstrFlags::P_NORMAL;
9037 
9038         static_assert(((~(SIInstrFlags::S_NAN |
9039                           SIInstrFlags::Q_NAN |
9040                           SIInstrFlags::N_INFINITY |
9041                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
9042                       "mask not equal");
9043 
9044         SDLoc DL(N);
9045         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9046                            X, DAG.getConstant(Mask, DL, MVT::i32));
9047       }
9048     }
9049   }
9050 
9051   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
9052     std::swap(LHS, RHS);
9053 
9054   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9055       RHS.hasOneUse()) {
9056     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
9057     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
9058     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
9059     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9060     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
9061         (RHS.getOperand(0) == LHS.getOperand(0) &&
9062          LHS.getOperand(0) == LHS.getOperand(1))) {
9063       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
9064       unsigned NewMask = LCC == ISD::SETO ?
9065         Mask->getZExtValue() & ~OrdMask :
9066         Mask->getZExtValue() & OrdMask;
9067 
9068       SDLoc DL(N);
9069       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
9070                          DAG.getConstant(NewMask, DL, MVT::i32));
9071     }
9072   }
9073 
9074   if (VT == MVT::i32 &&
9075       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
9076     // and x, (sext cc from i1) => select cc, x, 0
9077     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
9078       std::swap(LHS, RHS);
9079     if (isBoolSGPR(RHS.getOperand(0)))
9080       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
9081                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
9082   }
9083 
9084   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9085   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9086   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9087       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9088     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9089     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9090     if (LHSMask != ~0u && RHSMask != ~0u) {
9091       // Canonicalize the expression in an attempt to have fewer unique masks
9092       // and therefore fewer registers used to hold the masks.
9093       if (LHSMask > RHSMask) {
9094         std::swap(LHSMask, RHSMask);
9095         std::swap(LHS, RHS);
9096       }
9097 
9098       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9099       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9100       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9101       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9102 
9103       // Check of we need to combine values from two sources within a byte.
9104       if (!(LHSUsedLanes & RHSUsedLanes) &&
9105           // If we select high and lower word keep it for SDWA.
9106           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9107           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9108         // Each byte in each mask is either selector mask 0-3, or has higher
9109         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
9110         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
9111         // mask which is not 0xff wins. By anding both masks we have a correct
9112         // result except that 0x0c shall be corrected to give 0x0c only.
9113         uint32_t Mask = LHSMask & RHSMask;
9114         for (unsigned I = 0; I < 32; I += 8) {
9115           uint32_t ByteSel = 0xff << I;
9116           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
9117             Mask &= (0x0c << I) & 0xffffffff;
9118         }
9119 
9120         // Add 4 to each active LHS lane. It will not affect any existing 0xff
9121         // or 0x0c.
9122         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
9123         SDLoc DL(N);
9124 
9125         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9126                            LHS.getOperand(0), RHS.getOperand(0),
9127                            DAG.getConstant(Sel, DL, MVT::i32));
9128       }
9129     }
9130   }
9131 
9132   return SDValue();
9133 }
9134 
9135 SDValue SITargetLowering::performOrCombine(SDNode *N,
9136                                            DAGCombinerInfo &DCI) const {
9137   SelectionDAG &DAG = DCI.DAG;
9138   SDValue LHS = N->getOperand(0);
9139   SDValue RHS = N->getOperand(1);
9140 
9141   EVT VT = N->getValueType(0);
9142   if (VT == MVT::i1) {
9143     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
9144     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
9145         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
9146       SDValue Src = LHS.getOperand(0);
9147       if (Src != RHS.getOperand(0))
9148         return SDValue();
9149 
9150       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
9151       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9152       if (!CLHS || !CRHS)
9153         return SDValue();
9154 
9155       // Only 10 bits are used.
9156       static const uint32_t MaxMask = 0x3ff;
9157 
9158       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
9159       SDLoc DL(N);
9160       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
9161                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
9162     }
9163 
9164     return SDValue();
9165   }
9166 
9167   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
9168   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
9169       LHS.getOpcode() == AMDGPUISD::PERM &&
9170       isa<ConstantSDNode>(LHS.getOperand(2))) {
9171     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
9172     if (!Sel)
9173       return SDValue();
9174 
9175     Sel |= LHS.getConstantOperandVal(2);
9176     SDLoc DL(N);
9177     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
9178                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
9179   }
9180 
9181   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
9182   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9183   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
9184       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
9185     uint32_t LHSMask = getPermuteMask(DAG, LHS);
9186     uint32_t RHSMask = getPermuteMask(DAG, RHS);
9187     if (LHSMask != ~0u && RHSMask != ~0u) {
9188       // Canonicalize the expression in an attempt to have fewer unique masks
9189       // and therefore fewer registers used to hold the masks.
9190       if (LHSMask > RHSMask) {
9191         std::swap(LHSMask, RHSMask);
9192         std::swap(LHS, RHS);
9193       }
9194 
9195       // Select 0xc for each lane used from source operand. Zero has 0xc mask
9196       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
9197       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9198       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
9199 
9200       // Check of we need to combine values from two sources within a byte.
9201       if (!(LHSUsedLanes & RHSUsedLanes) &&
9202           // If we select high and lower word keep it for SDWA.
9203           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
9204           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
9205         // Kill zero bytes selected by other mask. Zero value is 0xc.
9206         LHSMask &= ~RHSUsedLanes;
9207         RHSMask &= ~LHSUsedLanes;
9208         // Add 4 to each active LHS lane
9209         LHSMask |= LHSUsedLanes & 0x04040404;
9210         // Combine masks
9211         uint32_t Sel = LHSMask | RHSMask;
9212         SDLoc DL(N);
9213 
9214         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
9215                            LHS.getOperand(0), RHS.getOperand(0),
9216                            DAG.getConstant(Sel, DL, MVT::i32));
9217       }
9218     }
9219   }
9220 
9221   if (VT != MVT::i64 || DCI.isBeforeLegalizeOps())
9222     return SDValue();
9223 
9224   // TODO: This could be a generic combine with a predicate for extracting the
9225   // high half of an integer being free.
9226 
9227   // (or i64:x, (zero_extend i32:y)) ->
9228   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
9229   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
9230       RHS.getOpcode() != ISD::ZERO_EXTEND)
9231     std::swap(LHS, RHS);
9232 
9233   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
9234     SDValue ExtSrc = RHS.getOperand(0);
9235     EVT SrcVT = ExtSrc.getValueType();
9236     if (SrcVT == MVT::i32) {
9237       SDLoc SL(N);
9238       SDValue LowLHS, HiBits;
9239       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
9240       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
9241 
9242       DCI.AddToWorklist(LowOr.getNode());
9243       DCI.AddToWorklist(HiBits.getNode());
9244 
9245       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
9246                                 LowOr, HiBits);
9247       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
9248     }
9249   }
9250 
9251   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
9252   if (CRHS) {
9253     if (SDValue Split
9254           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
9255       return Split;
9256   }
9257 
9258   return SDValue();
9259 }
9260 
9261 SDValue SITargetLowering::performXorCombine(SDNode *N,
9262                                             DAGCombinerInfo &DCI) const {
9263   EVT VT = N->getValueType(0);
9264   if (VT != MVT::i64)
9265     return SDValue();
9266 
9267   SDValue LHS = N->getOperand(0);
9268   SDValue RHS = N->getOperand(1);
9269 
9270   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
9271   if (CRHS) {
9272     if (SDValue Split
9273           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
9274       return Split;
9275   }
9276 
9277   return SDValue();
9278 }
9279 
9280 // Instructions that will be lowered with a final instruction that zeros the
9281 // high result bits.
9282 // XXX - probably only need to list legal operations.
9283 static bool fp16SrcZerosHighBits(unsigned Opc) {
9284   switch (Opc) {
9285   case ISD::FADD:
9286   case ISD::FSUB:
9287   case ISD::FMUL:
9288   case ISD::FDIV:
9289   case ISD::FREM:
9290   case ISD::FMA:
9291   case ISD::FMAD:
9292   case ISD::FCANONICALIZE:
9293   case ISD::FP_ROUND:
9294   case ISD::UINT_TO_FP:
9295   case ISD::SINT_TO_FP:
9296   case ISD::FABS:
9297     // Fabs is lowered to a bit operation, but it's an and which will clear the
9298     // high bits anyway.
9299   case ISD::FSQRT:
9300   case ISD::FSIN:
9301   case ISD::FCOS:
9302   case ISD::FPOWI:
9303   case ISD::FPOW:
9304   case ISD::FLOG:
9305   case ISD::FLOG2:
9306   case ISD::FLOG10:
9307   case ISD::FEXP:
9308   case ISD::FEXP2:
9309   case ISD::FCEIL:
9310   case ISD::FTRUNC:
9311   case ISD::FRINT:
9312   case ISD::FNEARBYINT:
9313   case ISD::FROUND:
9314   case ISD::FFLOOR:
9315   case ISD::FMINNUM:
9316   case ISD::FMAXNUM:
9317   case AMDGPUISD::FRACT:
9318   case AMDGPUISD::CLAMP:
9319   case AMDGPUISD::COS_HW:
9320   case AMDGPUISD::SIN_HW:
9321   case AMDGPUISD::FMIN3:
9322   case AMDGPUISD::FMAX3:
9323   case AMDGPUISD::FMED3:
9324   case AMDGPUISD::FMAD_FTZ:
9325   case AMDGPUISD::RCP:
9326   case AMDGPUISD::RSQ:
9327   case AMDGPUISD::RCP_IFLAG:
9328   case AMDGPUISD::LDEXP:
9329     return true;
9330   default:
9331     // fcopysign, select and others may be lowered to 32-bit bit operations
9332     // which don't zero the high bits.
9333     return false;
9334   }
9335 }
9336 
9337 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9338                                                    DAGCombinerInfo &DCI) const {
9339   if (!Subtarget->has16BitInsts() ||
9340       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9341     return SDValue();
9342 
9343   EVT VT = N->getValueType(0);
9344   if (VT != MVT::i32)
9345     return SDValue();
9346 
9347   SDValue Src = N->getOperand(0);
9348   if (Src.getValueType() != MVT::i16)
9349     return SDValue();
9350 
9351   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9352   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9353   if (Src.getOpcode() == ISD::BITCAST) {
9354     SDValue BCSrc = Src.getOperand(0);
9355     if (BCSrc.getValueType() == MVT::f16 &&
9356         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9357       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9358   }
9359 
9360   return SDValue();
9361 }
9362 
9363 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9364                                                         DAGCombinerInfo &DCI)
9365                                                         const {
9366   SDValue Src = N->getOperand(0);
9367   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9368 
9369   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9370       VTSign->getVT() == MVT::i8) ||
9371       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9372       VTSign->getVT() == MVT::i16)) &&
9373       Src.hasOneUse()) {
9374     auto *M = cast<MemSDNode>(Src);
9375     SDValue Ops[] = {
9376       Src.getOperand(0), // Chain
9377       Src.getOperand(1), // rsrc
9378       Src.getOperand(2), // vindex
9379       Src.getOperand(3), // voffset
9380       Src.getOperand(4), // soffset
9381       Src.getOperand(5), // offset
9382       Src.getOperand(6),
9383       Src.getOperand(7)
9384     };
9385     // replace with BUFFER_LOAD_BYTE/SHORT
9386     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9387                                          Src.getOperand(0).getValueType());
9388     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9389                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9390     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9391                                                           ResList,
9392                                                           Ops, M->getMemoryVT(),
9393                                                           M->getMemOperand());
9394     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9395                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9396   }
9397   return SDValue();
9398 }
9399 
9400 SDValue SITargetLowering::performClassCombine(SDNode *N,
9401                                               DAGCombinerInfo &DCI) const {
9402   SelectionDAG &DAG = DCI.DAG;
9403   SDValue Mask = N->getOperand(1);
9404 
9405   // fp_class x, 0 -> false
9406   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9407     if (CMask->isNullValue())
9408       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9409   }
9410 
9411   if (N->getOperand(0).isUndef())
9412     return DAG.getUNDEF(MVT::i1);
9413 
9414   return SDValue();
9415 }
9416 
9417 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9418                                             DAGCombinerInfo &DCI) const {
9419   EVT VT = N->getValueType(0);
9420   SDValue N0 = N->getOperand(0);
9421 
9422   if (N0.isUndef())
9423     return N0;
9424 
9425   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9426                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9427     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9428                            N->getFlags());
9429   }
9430 
9431   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9432     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9433                            N0.getOperand(0), N->getFlags());
9434   }
9435 
9436   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9437 }
9438 
9439 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9440                                        unsigned MaxDepth) const {
9441   unsigned Opcode = Op.getOpcode();
9442   if (Opcode == ISD::FCANONICALIZE)
9443     return true;
9444 
9445   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9446     auto F = CFP->getValueAPF();
9447     if (F.isNaN() && F.isSignaling())
9448       return false;
9449     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9450   }
9451 
9452   // If source is a result of another standard FP operation it is already in
9453   // canonical form.
9454   if (MaxDepth == 0)
9455     return false;
9456 
9457   switch (Opcode) {
9458   // These will flush denorms if required.
9459   case ISD::FADD:
9460   case ISD::FSUB:
9461   case ISD::FMUL:
9462   case ISD::FCEIL:
9463   case ISD::FFLOOR:
9464   case ISD::FMA:
9465   case ISD::FMAD:
9466   case ISD::FSQRT:
9467   case ISD::FDIV:
9468   case ISD::FREM:
9469   case ISD::FP_ROUND:
9470   case ISD::FP_EXTEND:
9471   case AMDGPUISD::FMUL_LEGACY:
9472   case AMDGPUISD::FMAD_FTZ:
9473   case AMDGPUISD::RCP:
9474   case AMDGPUISD::RSQ:
9475   case AMDGPUISD::RSQ_CLAMP:
9476   case AMDGPUISD::RCP_LEGACY:
9477   case AMDGPUISD::RCP_IFLAG:
9478   case AMDGPUISD::DIV_SCALE:
9479   case AMDGPUISD::DIV_FMAS:
9480   case AMDGPUISD::DIV_FIXUP:
9481   case AMDGPUISD::FRACT:
9482   case AMDGPUISD::LDEXP:
9483   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9484   case AMDGPUISD::CVT_F32_UBYTE0:
9485   case AMDGPUISD::CVT_F32_UBYTE1:
9486   case AMDGPUISD::CVT_F32_UBYTE2:
9487   case AMDGPUISD::CVT_F32_UBYTE3:
9488     return true;
9489 
9490   // It can/will be lowered or combined as a bit operation.
9491   // Need to check their input recursively to handle.
9492   case ISD::FNEG:
9493   case ISD::FABS:
9494   case ISD::FCOPYSIGN:
9495     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9496 
9497   case ISD::FSIN:
9498   case ISD::FCOS:
9499   case ISD::FSINCOS:
9500     return Op.getValueType().getScalarType() != MVT::f16;
9501 
9502   case ISD::FMINNUM:
9503   case ISD::FMAXNUM:
9504   case ISD::FMINNUM_IEEE:
9505   case ISD::FMAXNUM_IEEE:
9506   case AMDGPUISD::CLAMP:
9507   case AMDGPUISD::FMED3:
9508   case AMDGPUISD::FMAX3:
9509   case AMDGPUISD::FMIN3: {
9510     // FIXME: Shouldn't treat the generic operations different based these.
9511     // However, we aren't really required to flush the result from
9512     // minnum/maxnum..
9513 
9514     // snans will be quieted, so we only need to worry about denormals.
9515     if (Subtarget->supportsMinMaxDenormModes() ||
9516         denormalsEnabledForType(DAG, Op.getValueType()))
9517       return true;
9518 
9519     // Flushing may be required.
9520     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9521     // targets need to check their input recursively.
9522 
9523     // FIXME: Does this apply with clamp? It's implemented with max.
9524     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9525       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9526         return false;
9527     }
9528 
9529     return true;
9530   }
9531   case ISD::SELECT: {
9532     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9533            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9534   }
9535   case ISD::BUILD_VECTOR: {
9536     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9537       SDValue SrcOp = Op.getOperand(i);
9538       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9539         return false;
9540     }
9541 
9542     return true;
9543   }
9544   case ISD::EXTRACT_VECTOR_ELT:
9545   case ISD::EXTRACT_SUBVECTOR: {
9546     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9547   }
9548   case ISD::INSERT_VECTOR_ELT: {
9549     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9550            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9551   }
9552   case ISD::UNDEF:
9553     // Could be anything.
9554     return false;
9555 
9556   case ISD::BITCAST: {
9557     // Hack round the mess we make when legalizing extract_vector_elt
9558     SDValue Src = Op.getOperand(0);
9559     if (Src.getValueType() == MVT::i16 &&
9560         Src.getOpcode() == ISD::TRUNCATE) {
9561       SDValue TruncSrc = Src.getOperand(0);
9562       if (TruncSrc.getValueType() == MVT::i32 &&
9563           TruncSrc.getOpcode() == ISD::BITCAST &&
9564           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9565         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9566       }
9567     }
9568 
9569     return false;
9570   }
9571   case ISD::INTRINSIC_WO_CHAIN: {
9572     unsigned IntrinsicID
9573       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9574     // TODO: Handle more intrinsics
9575     switch (IntrinsicID) {
9576     case Intrinsic::amdgcn_cvt_pkrtz:
9577     case Intrinsic::amdgcn_cubeid:
9578     case Intrinsic::amdgcn_frexp_mant:
9579     case Intrinsic::amdgcn_fdot2:
9580     case Intrinsic::amdgcn_rcp:
9581     case Intrinsic::amdgcn_rsq:
9582     case Intrinsic::amdgcn_rsq_clamp:
9583     case Intrinsic::amdgcn_rcp_legacy:
9584     case Intrinsic::amdgcn_rsq_legacy:
9585     case Intrinsic::amdgcn_trig_preop:
9586       return true;
9587     default:
9588       break;
9589     }
9590 
9591     LLVM_FALLTHROUGH;
9592   }
9593   default:
9594     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9595            DAG.isKnownNeverSNaN(Op);
9596   }
9597 
9598   llvm_unreachable("invalid operation");
9599 }
9600 
9601 // Constant fold canonicalize.
9602 SDValue SITargetLowering::getCanonicalConstantFP(
9603   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9604   // Flush denormals to 0 if not enabled.
9605   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9606     return DAG.getConstantFP(0.0, SL, VT);
9607 
9608   if (C.isNaN()) {
9609     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9610     if (C.isSignaling()) {
9611       // Quiet a signaling NaN.
9612       // FIXME: Is this supposed to preserve payload bits?
9613       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9614     }
9615 
9616     // Make sure it is the canonical NaN bitpattern.
9617     //
9618     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9619     // immediate?
9620     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9621       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9622   }
9623 
9624   // Already canonical.
9625   return DAG.getConstantFP(C, SL, VT);
9626 }
9627 
9628 static bool vectorEltWillFoldAway(SDValue Op) {
9629   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9630 }
9631 
9632 SDValue SITargetLowering::performFCanonicalizeCombine(
9633   SDNode *N,
9634   DAGCombinerInfo &DCI) const {
9635   SelectionDAG &DAG = DCI.DAG;
9636   SDValue N0 = N->getOperand(0);
9637   EVT VT = N->getValueType(0);
9638 
9639   // fcanonicalize undef -> qnan
9640   if (N0.isUndef()) {
9641     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9642     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9643   }
9644 
9645   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9646     EVT VT = N->getValueType(0);
9647     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9648   }
9649 
9650   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9651   //                                                   (fcanonicalize k)
9652   //
9653   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9654 
9655   // TODO: This could be better with wider vectors that will be split to v2f16,
9656   // and to consider uses since there aren't that many packed operations.
9657   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9658       isTypeLegal(MVT::v2f16)) {
9659     SDLoc SL(N);
9660     SDValue NewElts[2];
9661     SDValue Lo = N0.getOperand(0);
9662     SDValue Hi = N0.getOperand(1);
9663     EVT EltVT = Lo.getValueType();
9664 
9665     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9666       for (unsigned I = 0; I != 2; ++I) {
9667         SDValue Op = N0.getOperand(I);
9668         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9669           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9670                                               CFP->getValueAPF());
9671         } else if (Op.isUndef()) {
9672           // Handled below based on what the other operand is.
9673           NewElts[I] = Op;
9674         } else {
9675           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9676         }
9677       }
9678 
9679       // If one half is undef, and one is constant, perfer a splat vector rather
9680       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9681       // cheaper to use and may be free with a packed operation.
9682       if (NewElts[0].isUndef()) {
9683         if (isa<ConstantFPSDNode>(NewElts[1]))
9684           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9685             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9686       }
9687 
9688       if (NewElts[1].isUndef()) {
9689         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9690           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9691       }
9692 
9693       return DAG.getBuildVector(VT, SL, NewElts);
9694     }
9695   }
9696 
9697   unsigned SrcOpc = N0.getOpcode();
9698 
9699   // If it's free to do so, push canonicalizes further up the source, which may
9700   // find a canonical source.
9701   //
9702   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9703   // sNaNs.
9704   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9705     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9706     if (CRHS && N0.hasOneUse()) {
9707       SDLoc SL(N);
9708       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9709                                    N0.getOperand(0));
9710       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9711       DCI.AddToWorklist(Canon0.getNode());
9712 
9713       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9714     }
9715   }
9716 
9717   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9718 }
9719 
9720 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9721   switch (Opc) {
9722   case ISD::FMAXNUM:
9723   case ISD::FMAXNUM_IEEE:
9724     return AMDGPUISD::FMAX3;
9725   case ISD::SMAX:
9726     return AMDGPUISD::SMAX3;
9727   case ISD::UMAX:
9728     return AMDGPUISD::UMAX3;
9729   case ISD::FMINNUM:
9730   case ISD::FMINNUM_IEEE:
9731     return AMDGPUISD::FMIN3;
9732   case ISD::SMIN:
9733     return AMDGPUISD::SMIN3;
9734   case ISD::UMIN:
9735     return AMDGPUISD::UMIN3;
9736   default:
9737     llvm_unreachable("Not a min/max opcode");
9738   }
9739 }
9740 
9741 SDValue SITargetLowering::performIntMed3ImmCombine(
9742   SelectionDAG &DAG, const SDLoc &SL,
9743   SDValue Op0, SDValue Op1, bool Signed) const {
9744   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9745   if (!K1)
9746     return SDValue();
9747 
9748   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9749   if (!K0)
9750     return SDValue();
9751 
9752   if (Signed) {
9753     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9754       return SDValue();
9755   } else {
9756     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9757       return SDValue();
9758   }
9759 
9760   EVT VT = K0->getValueType(0);
9761   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9762   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9763     return DAG.getNode(Med3Opc, SL, VT,
9764                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9765   }
9766 
9767   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9768   MVT NVT = MVT::i32;
9769   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9770 
9771   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9772   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9773   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9774 
9775   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9776   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9777 }
9778 
9779 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9780   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9781     return C;
9782 
9783   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9784     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9785       return C;
9786   }
9787 
9788   return nullptr;
9789 }
9790 
9791 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9792                                                   const SDLoc &SL,
9793                                                   SDValue Op0,
9794                                                   SDValue Op1) const {
9795   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9796   if (!K1)
9797     return SDValue();
9798 
9799   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9800   if (!K0)
9801     return SDValue();
9802 
9803   // Ordered >= (although NaN inputs should have folded away by now).
9804   if (K0->getValueAPF() > K1->getValueAPF())
9805     return SDValue();
9806 
9807   const MachineFunction &MF = DAG.getMachineFunction();
9808   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9809 
9810   // TODO: Check IEEE bit enabled?
9811   EVT VT = Op0.getValueType();
9812   if (Info->getMode().DX10Clamp) {
9813     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9814     // hardware fmed3 behavior converting to a min.
9815     // FIXME: Should this be allowing -0.0?
9816     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9817       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9818   }
9819 
9820   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9821   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9822     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9823     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9824     // then give the other result, which is different from med3 with a NaN
9825     // input.
9826     SDValue Var = Op0.getOperand(0);
9827     if (!DAG.isKnownNeverSNaN(Var))
9828       return SDValue();
9829 
9830     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9831 
9832     if ((!K0->hasOneUse() ||
9833          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9834         (!K1->hasOneUse() ||
9835          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9836       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9837                          Var, SDValue(K0, 0), SDValue(K1, 0));
9838     }
9839   }
9840 
9841   return SDValue();
9842 }
9843 
9844 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9845                                                DAGCombinerInfo &DCI) const {
9846   SelectionDAG &DAG = DCI.DAG;
9847 
9848   EVT VT = N->getValueType(0);
9849   unsigned Opc = N->getOpcode();
9850   SDValue Op0 = N->getOperand(0);
9851   SDValue Op1 = N->getOperand(1);
9852 
9853   // Only do this if the inner op has one use since this will just increases
9854   // register pressure for no benefit.
9855 
9856   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9857       !VT.isVector() &&
9858       (VT == MVT::i32 || VT == MVT::f32 ||
9859        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9860     // max(max(a, b), c) -> max3(a, b, c)
9861     // min(min(a, b), c) -> min3(a, b, c)
9862     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9863       SDLoc DL(N);
9864       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9865                          DL,
9866                          N->getValueType(0),
9867                          Op0.getOperand(0),
9868                          Op0.getOperand(1),
9869                          Op1);
9870     }
9871 
9872     // Try commuted.
9873     // max(a, max(b, c)) -> max3(a, b, c)
9874     // min(a, min(b, c)) -> min3(a, b, c)
9875     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9876       SDLoc DL(N);
9877       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9878                          DL,
9879                          N->getValueType(0),
9880                          Op0,
9881                          Op1.getOperand(0),
9882                          Op1.getOperand(1));
9883     }
9884   }
9885 
9886   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9887   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9888     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9889       return Med3;
9890   }
9891 
9892   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9893     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9894       return Med3;
9895   }
9896 
9897   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9898   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9899        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9900        (Opc == AMDGPUISD::FMIN_LEGACY &&
9901         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9902       (VT == MVT::f32 || VT == MVT::f64 ||
9903        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9904        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9905       Op0.hasOneUse()) {
9906     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9907       return Res;
9908   }
9909 
9910   return SDValue();
9911 }
9912 
9913 static bool isClampZeroToOne(SDValue A, SDValue B) {
9914   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9915     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9916       // FIXME: Should this be allowing -0.0?
9917       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9918              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9919     }
9920   }
9921 
9922   return false;
9923 }
9924 
9925 // FIXME: Should only worry about snans for version with chain.
9926 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9927                                               DAGCombinerInfo &DCI) const {
9928   EVT VT = N->getValueType(0);
9929   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9930   // NaNs. With a NaN input, the order of the operands may change the result.
9931 
9932   SelectionDAG &DAG = DCI.DAG;
9933   SDLoc SL(N);
9934 
9935   SDValue Src0 = N->getOperand(0);
9936   SDValue Src1 = N->getOperand(1);
9937   SDValue Src2 = N->getOperand(2);
9938 
9939   if (isClampZeroToOne(Src0, Src1)) {
9940     // const_a, const_b, x -> clamp is safe in all cases including signaling
9941     // nans.
9942     // FIXME: Should this be allowing -0.0?
9943     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9944   }
9945 
9946   const MachineFunction &MF = DAG.getMachineFunction();
9947   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9948 
9949   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9950   // handling no dx10-clamp?
9951   if (Info->getMode().DX10Clamp) {
9952     // If NaNs is clamped to 0, we are free to reorder the inputs.
9953 
9954     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9955       std::swap(Src0, Src1);
9956 
9957     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9958       std::swap(Src1, Src2);
9959 
9960     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9961       std::swap(Src0, Src1);
9962 
9963     if (isClampZeroToOne(Src1, Src2))
9964       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9965   }
9966 
9967   return SDValue();
9968 }
9969 
9970 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9971                                                  DAGCombinerInfo &DCI) const {
9972   SDValue Src0 = N->getOperand(0);
9973   SDValue Src1 = N->getOperand(1);
9974   if (Src0.isUndef() && Src1.isUndef())
9975     return DCI.DAG.getUNDEF(N->getValueType(0));
9976   return SDValue();
9977 }
9978 
9979 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9980 // expanded into a set of cmp/select instructions.
9981 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9982                                                 unsigned NumElem,
9983                                                 bool IsDivergentIdx) {
9984   if (UseDivergentRegisterIndexing)
9985     return false;
9986 
9987   unsigned VecSize = EltSize * NumElem;
9988 
9989   // Sub-dword vectors of size 2 dword or less have better implementation.
9990   if (VecSize <= 64 && EltSize < 32)
9991     return false;
9992 
9993   // Always expand the rest of sub-dword instructions, otherwise it will be
9994   // lowered via memory.
9995   if (EltSize < 32)
9996     return true;
9997 
9998   // Always do this if var-idx is divergent, otherwise it will become a loop.
9999   if (IsDivergentIdx)
10000     return true;
10001 
10002   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
10003   unsigned NumInsts = NumElem /* Number of compares */ +
10004                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
10005   return NumInsts <= 16;
10006 }
10007 
10008 static bool shouldExpandVectorDynExt(SDNode *N) {
10009   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
10010   if (isa<ConstantSDNode>(Idx))
10011     return false;
10012 
10013   SDValue Vec = N->getOperand(0);
10014   EVT VecVT = Vec.getValueType();
10015   EVT EltVT = VecVT.getVectorElementType();
10016   unsigned EltSize = EltVT.getSizeInBits();
10017   unsigned NumElem = VecVT.getVectorNumElements();
10018 
10019   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
10020                                                     Idx->isDivergent());
10021 }
10022 
10023 SDValue SITargetLowering::performExtractVectorEltCombine(
10024   SDNode *N, DAGCombinerInfo &DCI) const {
10025   SDValue Vec = N->getOperand(0);
10026   SelectionDAG &DAG = DCI.DAG;
10027 
10028   EVT VecVT = Vec.getValueType();
10029   EVT EltVT = VecVT.getVectorElementType();
10030 
10031   if ((Vec.getOpcode() == ISD::FNEG ||
10032        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
10033     SDLoc SL(N);
10034     EVT EltVT = N->getValueType(0);
10035     SDValue Idx = N->getOperand(1);
10036     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10037                               Vec.getOperand(0), Idx);
10038     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
10039   }
10040 
10041   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
10042   //    =>
10043   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
10044   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
10045   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
10046   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
10047     SDLoc SL(N);
10048     EVT EltVT = N->getValueType(0);
10049     SDValue Idx = N->getOperand(1);
10050     unsigned Opc = Vec.getOpcode();
10051 
10052     switch(Opc) {
10053     default:
10054       break;
10055       // TODO: Support other binary operations.
10056     case ISD::FADD:
10057     case ISD::FSUB:
10058     case ISD::FMUL:
10059     case ISD::ADD:
10060     case ISD::UMIN:
10061     case ISD::UMAX:
10062     case ISD::SMIN:
10063     case ISD::SMAX:
10064     case ISD::FMAXNUM:
10065     case ISD::FMINNUM:
10066     case ISD::FMAXNUM_IEEE:
10067     case ISD::FMINNUM_IEEE: {
10068       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10069                                  Vec.getOperand(0), Idx);
10070       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
10071                                  Vec.getOperand(1), Idx);
10072 
10073       DCI.AddToWorklist(Elt0.getNode());
10074       DCI.AddToWorklist(Elt1.getNode());
10075       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
10076     }
10077     }
10078   }
10079 
10080   unsigned VecSize = VecVT.getSizeInBits();
10081   unsigned EltSize = EltVT.getSizeInBits();
10082 
10083   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
10084   if (::shouldExpandVectorDynExt(N)) {
10085     SDLoc SL(N);
10086     SDValue Idx = N->getOperand(1);
10087     SDValue V;
10088     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10089       SDValue IC = DAG.getVectorIdxConstant(I, SL);
10090       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10091       if (I == 0)
10092         V = Elt;
10093       else
10094         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
10095     }
10096     return V;
10097   }
10098 
10099   if (!DCI.isBeforeLegalize())
10100     return SDValue();
10101 
10102   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
10103   // elements. This exposes more load reduction opportunities by replacing
10104   // multiple small extract_vector_elements with a single 32-bit extract.
10105   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10106   if (isa<MemSDNode>(Vec) &&
10107       EltSize <= 16 &&
10108       EltVT.isByteSized() &&
10109       VecSize > 32 &&
10110       VecSize % 32 == 0 &&
10111       Idx) {
10112     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
10113 
10114     unsigned BitIndex = Idx->getZExtValue() * EltSize;
10115     unsigned EltIdx = BitIndex / 32;
10116     unsigned LeftoverBitIdx = BitIndex % 32;
10117     SDLoc SL(N);
10118 
10119     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
10120     DCI.AddToWorklist(Cast.getNode());
10121 
10122     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
10123                               DAG.getConstant(EltIdx, SL, MVT::i32));
10124     DCI.AddToWorklist(Elt.getNode());
10125     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
10126                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
10127     DCI.AddToWorklist(Srl.getNode());
10128 
10129     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
10130     DCI.AddToWorklist(Trunc.getNode());
10131     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
10132   }
10133 
10134   return SDValue();
10135 }
10136 
10137 SDValue
10138 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
10139                                                 DAGCombinerInfo &DCI) const {
10140   SDValue Vec = N->getOperand(0);
10141   SDValue Idx = N->getOperand(2);
10142   EVT VecVT = Vec.getValueType();
10143   EVT EltVT = VecVT.getVectorElementType();
10144 
10145   // INSERT_VECTOR_ELT (<n x e>, var-idx)
10146   // => BUILD_VECTOR n x select (e, const-idx)
10147   if (!::shouldExpandVectorDynExt(N))
10148     return SDValue();
10149 
10150   SelectionDAG &DAG = DCI.DAG;
10151   SDLoc SL(N);
10152   SDValue Ins = N->getOperand(1);
10153   EVT IdxVT = Idx.getValueType();
10154 
10155   SmallVector<SDValue, 16> Ops;
10156   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
10157     SDValue IC = DAG.getConstant(I, SL, IdxVT);
10158     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
10159     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
10160     Ops.push_back(V);
10161   }
10162 
10163   return DAG.getBuildVector(VecVT, SL, Ops);
10164 }
10165 
10166 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
10167                                           const SDNode *N0,
10168                                           const SDNode *N1) const {
10169   EVT VT = N0->getValueType(0);
10170 
10171   // Only do this if we are not trying to support denormals. v_mad_f32 does not
10172   // support denormals ever.
10173   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
10174        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
10175         getSubtarget()->hasMadF16())) &&
10176        isOperationLegal(ISD::FMAD, VT))
10177     return ISD::FMAD;
10178 
10179   const TargetOptions &Options = DAG.getTarget().Options;
10180   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10181        (N0->getFlags().hasAllowContract() &&
10182         N1->getFlags().hasAllowContract())) &&
10183       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
10184     return ISD::FMA;
10185   }
10186 
10187   return 0;
10188 }
10189 
10190 // For a reassociatable opcode perform:
10191 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
10192 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
10193                                                SelectionDAG &DAG) const {
10194   EVT VT = N->getValueType(0);
10195   if (VT != MVT::i32 && VT != MVT::i64)
10196     return SDValue();
10197 
10198   unsigned Opc = N->getOpcode();
10199   SDValue Op0 = N->getOperand(0);
10200   SDValue Op1 = N->getOperand(1);
10201 
10202   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
10203     return SDValue();
10204 
10205   if (Op0->isDivergent())
10206     std::swap(Op0, Op1);
10207 
10208   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
10209     return SDValue();
10210 
10211   SDValue Op2 = Op1.getOperand(1);
10212   Op1 = Op1.getOperand(0);
10213   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
10214     return SDValue();
10215 
10216   if (Op1->isDivergent())
10217     std::swap(Op1, Op2);
10218 
10219   // If either operand is constant this will conflict with
10220   // DAGCombiner::ReassociateOps().
10221   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
10222       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
10223     return SDValue();
10224 
10225   SDLoc SL(N);
10226   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
10227   return DAG.getNode(Opc, SL, VT, Add1, Op2);
10228 }
10229 
10230 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
10231                            EVT VT,
10232                            SDValue N0, SDValue N1, SDValue N2,
10233                            bool Signed) {
10234   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
10235   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
10236   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
10237   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
10238 }
10239 
10240 SDValue SITargetLowering::performAddCombine(SDNode *N,
10241                                             DAGCombinerInfo &DCI) const {
10242   SelectionDAG &DAG = DCI.DAG;
10243   EVT VT = N->getValueType(0);
10244   SDLoc SL(N);
10245   SDValue LHS = N->getOperand(0);
10246   SDValue RHS = N->getOperand(1);
10247 
10248   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
10249       && Subtarget->hasMad64_32() &&
10250       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
10251       VT.getScalarSizeInBits() <= 64) {
10252     if (LHS.getOpcode() != ISD::MUL)
10253       std::swap(LHS, RHS);
10254 
10255     SDValue MulLHS = LHS.getOperand(0);
10256     SDValue MulRHS = LHS.getOperand(1);
10257     SDValue AddRHS = RHS;
10258 
10259     // TODO: Maybe restrict if SGPR inputs.
10260     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
10261         numBitsUnsigned(MulRHS, DAG) <= 32) {
10262       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
10263       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
10264       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
10265       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
10266     }
10267 
10268     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
10269       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
10270       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
10271       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
10272       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
10273     }
10274 
10275     return SDValue();
10276   }
10277 
10278   if (SDValue V = reassociateScalarOps(N, DAG)) {
10279     return V;
10280   }
10281 
10282   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
10283     return SDValue();
10284 
10285   // add x, zext (setcc) => addcarry x, 0, setcc
10286   // add x, sext (setcc) => subcarry x, 0, setcc
10287   unsigned Opc = LHS.getOpcode();
10288   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
10289       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
10290     std::swap(RHS, LHS);
10291 
10292   Opc = RHS.getOpcode();
10293   switch (Opc) {
10294   default: break;
10295   case ISD::ZERO_EXTEND:
10296   case ISD::SIGN_EXTEND:
10297   case ISD::ANY_EXTEND: {
10298     auto Cond = RHS.getOperand(0);
10299     // If this won't be a real VOPC output, we would still need to insert an
10300     // extra instruction anyway.
10301     if (!isBoolSGPR(Cond))
10302       break;
10303     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10304     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10305     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
10306     return DAG.getNode(Opc, SL, VTList, Args);
10307   }
10308   case ISD::ADDCARRY: {
10309     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
10310     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
10311     if (!C || C->getZExtValue() != 0) break;
10312     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10313     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10314   }
10315   }
10316   return SDValue();
10317 }
10318 
10319 SDValue SITargetLowering::performSubCombine(SDNode *N,
10320                                             DAGCombinerInfo &DCI) const {
10321   SelectionDAG &DAG = DCI.DAG;
10322   EVT VT = N->getValueType(0);
10323 
10324   if (VT != MVT::i32)
10325     return SDValue();
10326 
10327   SDLoc SL(N);
10328   SDValue LHS = N->getOperand(0);
10329   SDValue RHS = N->getOperand(1);
10330 
10331   // sub x, zext (setcc) => subcarry x, 0, setcc
10332   // sub x, sext (setcc) => addcarry x, 0, setcc
10333   unsigned Opc = RHS.getOpcode();
10334   switch (Opc) {
10335   default: break;
10336   case ISD::ZERO_EXTEND:
10337   case ISD::SIGN_EXTEND:
10338   case ISD::ANY_EXTEND: {
10339     auto Cond = RHS.getOperand(0);
10340     // If this won't be a real VOPC output, we would still need to insert an
10341     // extra instruction anyway.
10342     if (!isBoolSGPR(Cond))
10343       break;
10344     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10345     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10346     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10347     return DAG.getNode(Opc, SL, VTList, Args);
10348   }
10349   }
10350 
10351   if (LHS.getOpcode() == ISD::SUBCARRY) {
10352     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10353     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10354     if (!C || !C->isNullValue())
10355       return SDValue();
10356     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10357     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10358   }
10359   return SDValue();
10360 }
10361 
10362 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10363   DAGCombinerInfo &DCI) const {
10364 
10365   if (N->getValueType(0) != MVT::i32)
10366     return SDValue();
10367 
10368   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10369   if (!C || C->getZExtValue() != 0)
10370     return SDValue();
10371 
10372   SelectionDAG &DAG = DCI.DAG;
10373   SDValue LHS = N->getOperand(0);
10374 
10375   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10376   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10377   unsigned LHSOpc = LHS.getOpcode();
10378   unsigned Opc = N->getOpcode();
10379   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10380       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10381     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10382     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10383   }
10384   return SDValue();
10385 }
10386 
10387 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10388                                              DAGCombinerInfo &DCI) const {
10389   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10390     return SDValue();
10391 
10392   SelectionDAG &DAG = DCI.DAG;
10393   EVT VT = N->getValueType(0);
10394 
10395   SDLoc SL(N);
10396   SDValue LHS = N->getOperand(0);
10397   SDValue RHS = N->getOperand(1);
10398 
10399   // These should really be instruction patterns, but writing patterns with
10400   // source modiifiers is a pain.
10401 
10402   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10403   if (LHS.getOpcode() == ISD::FADD) {
10404     SDValue A = LHS.getOperand(0);
10405     if (A == LHS.getOperand(1)) {
10406       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10407       if (FusedOp != 0) {
10408         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10409         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10410       }
10411     }
10412   }
10413 
10414   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10415   if (RHS.getOpcode() == ISD::FADD) {
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 Two = DAG.getConstantFP(2.0, SL, VT);
10421         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10422       }
10423     }
10424   }
10425 
10426   return SDValue();
10427 }
10428 
10429 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10430                                              DAGCombinerInfo &DCI) const {
10431   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10432     return SDValue();
10433 
10434   SelectionDAG &DAG = DCI.DAG;
10435   SDLoc SL(N);
10436   EVT VT = N->getValueType(0);
10437   assert(!VT.isVector());
10438 
10439   // Try to get the fneg to fold into the source modifier. This undoes generic
10440   // DAG combines and folds them into the mad.
10441   //
10442   // Only do this if we are not trying to support denormals. v_mad_f32 does
10443   // not support denormals ever.
10444   SDValue LHS = N->getOperand(0);
10445   SDValue RHS = N->getOperand(1);
10446   if (LHS.getOpcode() == ISD::FADD) {
10447     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10448     SDValue A = LHS.getOperand(0);
10449     if (A == LHS.getOperand(1)) {
10450       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10451       if (FusedOp != 0){
10452         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10453         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10454 
10455         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10456       }
10457     }
10458   }
10459 
10460   if (RHS.getOpcode() == ISD::FADD) {
10461     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10462 
10463     SDValue A = RHS.getOperand(0);
10464     if (A == RHS.getOperand(1)) {
10465       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10466       if (FusedOp != 0){
10467         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10468         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10469       }
10470     }
10471   }
10472 
10473   return SDValue();
10474 }
10475 
10476 SDValue SITargetLowering::performFMACombine(SDNode *N,
10477                                             DAGCombinerInfo &DCI) const {
10478   SelectionDAG &DAG = DCI.DAG;
10479   EVT VT = N->getValueType(0);
10480   SDLoc SL(N);
10481 
10482   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10483     return SDValue();
10484 
10485   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10486   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10487   SDValue Op1 = N->getOperand(0);
10488   SDValue Op2 = N->getOperand(1);
10489   SDValue FMA = N->getOperand(2);
10490 
10491   if (FMA.getOpcode() != ISD::FMA ||
10492       Op1.getOpcode() != ISD::FP_EXTEND ||
10493       Op2.getOpcode() != ISD::FP_EXTEND)
10494     return SDValue();
10495 
10496   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10497   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10498   // is sufficient to allow generaing fdot2.
10499   const TargetOptions &Options = DAG.getTarget().Options;
10500   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10501       (N->getFlags().hasAllowContract() &&
10502        FMA->getFlags().hasAllowContract())) {
10503     Op1 = Op1.getOperand(0);
10504     Op2 = Op2.getOperand(0);
10505     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10506         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10507       return SDValue();
10508 
10509     SDValue Vec1 = Op1.getOperand(0);
10510     SDValue Idx1 = Op1.getOperand(1);
10511     SDValue Vec2 = Op2.getOperand(0);
10512 
10513     SDValue FMAOp1 = FMA.getOperand(0);
10514     SDValue FMAOp2 = FMA.getOperand(1);
10515     SDValue FMAAcc = FMA.getOperand(2);
10516 
10517     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10518         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10519       return SDValue();
10520 
10521     FMAOp1 = FMAOp1.getOperand(0);
10522     FMAOp2 = FMAOp2.getOperand(0);
10523     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10524         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10525       return SDValue();
10526 
10527     SDValue Vec3 = FMAOp1.getOperand(0);
10528     SDValue Vec4 = FMAOp2.getOperand(0);
10529     SDValue Idx2 = FMAOp1.getOperand(1);
10530 
10531     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10532         // Idx1 and Idx2 cannot be the same.
10533         Idx1 == Idx2)
10534       return SDValue();
10535 
10536     if (Vec1 == Vec2 || Vec3 == Vec4)
10537       return SDValue();
10538 
10539     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10540       return SDValue();
10541 
10542     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10543         (Vec1 == Vec4 && Vec2 == Vec3)) {
10544       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10545                          DAG.getTargetConstant(0, SL, MVT::i1));
10546     }
10547   }
10548   return SDValue();
10549 }
10550 
10551 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10552                                               DAGCombinerInfo &DCI) const {
10553   SelectionDAG &DAG = DCI.DAG;
10554   SDLoc SL(N);
10555 
10556   SDValue LHS = N->getOperand(0);
10557   SDValue RHS = N->getOperand(1);
10558   EVT VT = LHS.getValueType();
10559   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10560 
10561   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10562   if (!CRHS) {
10563     CRHS = dyn_cast<ConstantSDNode>(LHS);
10564     if (CRHS) {
10565       std::swap(LHS, RHS);
10566       CC = getSetCCSwappedOperands(CC);
10567     }
10568   }
10569 
10570   if (CRHS) {
10571     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10572         isBoolSGPR(LHS.getOperand(0))) {
10573       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10574       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10575       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10576       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10577       if ((CRHS->isAllOnesValue() &&
10578            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10579           (CRHS->isNullValue() &&
10580            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10581         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10582                            DAG.getConstant(-1, SL, MVT::i1));
10583       if ((CRHS->isAllOnesValue() &&
10584            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10585           (CRHS->isNullValue() &&
10586            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10587         return LHS.getOperand(0);
10588     }
10589 
10590     uint64_t CRHSVal = CRHS->getZExtValue();
10591     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10592         LHS.getOpcode() == ISD::SELECT &&
10593         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10594         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10595         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10596         isBoolSGPR(LHS.getOperand(0))) {
10597       // Given CT != FT:
10598       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10599       // setcc (select cc, CT, CF), CF, ne => cc
10600       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10601       // setcc (select cc, CT, CF), CT, eq => cc
10602       uint64_t CT = LHS.getConstantOperandVal(1);
10603       uint64_t CF = LHS.getConstantOperandVal(2);
10604 
10605       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10606           (CT == CRHSVal && CC == ISD::SETNE))
10607         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10608                            DAG.getConstant(-1, SL, MVT::i1));
10609       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10610           (CT == CRHSVal && CC == ISD::SETEQ))
10611         return LHS.getOperand(0);
10612     }
10613   }
10614 
10615   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10616                                            VT != MVT::f16))
10617     return SDValue();
10618 
10619   // Match isinf/isfinite pattern
10620   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10621   // (fcmp one (fabs x), inf) -> (fp_class x,
10622   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10623   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10624     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10625     if (!CRHS)
10626       return SDValue();
10627 
10628     const APFloat &APF = CRHS->getValueAPF();
10629     if (APF.isInfinity() && !APF.isNegative()) {
10630       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10631                                  SIInstrFlags::N_INFINITY;
10632       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10633                                     SIInstrFlags::P_ZERO |
10634                                     SIInstrFlags::N_NORMAL |
10635                                     SIInstrFlags::P_NORMAL |
10636                                     SIInstrFlags::N_SUBNORMAL |
10637                                     SIInstrFlags::P_SUBNORMAL;
10638       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10639       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10640                          DAG.getConstant(Mask, SL, MVT::i32));
10641     }
10642   }
10643 
10644   return SDValue();
10645 }
10646 
10647 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10648                                                      DAGCombinerInfo &DCI) const {
10649   SelectionDAG &DAG = DCI.DAG;
10650   SDLoc SL(N);
10651   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10652 
10653   SDValue Src = N->getOperand(0);
10654   SDValue Shift = N->getOperand(0);
10655 
10656   // TODO: Extend type shouldn't matter (assuming legal types).
10657   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10658     Shift = Shift.getOperand(0);
10659 
10660   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10661     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10662     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10663     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10664     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10665     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10666     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10667       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10668                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10669 
10670       unsigned ShiftOffset = 8 * Offset;
10671       if (Shift.getOpcode() == ISD::SHL)
10672         ShiftOffset -= C->getZExtValue();
10673       else
10674         ShiftOffset += C->getZExtValue();
10675 
10676       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10677         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10678                            MVT::f32, Shift);
10679       }
10680     }
10681   }
10682 
10683   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10684   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10685   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10686     // We simplified Src. If this node is not dead, visit it again so it is
10687     // folded properly.
10688     if (N->getOpcode() != ISD::DELETED_NODE)
10689       DCI.AddToWorklist(N);
10690     return SDValue(N, 0);
10691   }
10692 
10693   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10694   if (SDValue DemandedSrc =
10695           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10696     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10697 
10698   return SDValue();
10699 }
10700 
10701 SDValue SITargetLowering::performClampCombine(SDNode *N,
10702                                               DAGCombinerInfo &DCI) const {
10703   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10704   if (!CSrc)
10705     return SDValue();
10706 
10707   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10708   const APFloat &F = CSrc->getValueAPF();
10709   APFloat Zero = APFloat::getZero(F.getSemantics());
10710   if (F < Zero ||
10711       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10712     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10713   }
10714 
10715   APFloat One(F.getSemantics(), "1.0");
10716   if (F > One)
10717     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10718 
10719   return SDValue(CSrc, 0);
10720 }
10721 
10722 
10723 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10724                                             DAGCombinerInfo &DCI) const {
10725   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10726     return SDValue();
10727   switch (N->getOpcode()) {
10728   case ISD::ADD:
10729     return performAddCombine(N, DCI);
10730   case ISD::SUB:
10731     return performSubCombine(N, DCI);
10732   case ISD::ADDCARRY:
10733   case ISD::SUBCARRY:
10734     return performAddCarrySubCarryCombine(N, DCI);
10735   case ISD::FADD:
10736     return performFAddCombine(N, DCI);
10737   case ISD::FSUB:
10738     return performFSubCombine(N, DCI);
10739   case ISD::SETCC:
10740     return performSetCCCombine(N, DCI);
10741   case ISD::FMAXNUM:
10742   case ISD::FMINNUM:
10743   case ISD::FMAXNUM_IEEE:
10744   case ISD::FMINNUM_IEEE:
10745   case ISD::SMAX:
10746   case ISD::SMIN:
10747   case ISD::UMAX:
10748   case ISD::UMIN:
10749   case AMDGPUISD::FMIN_LEGACY:
10750   case AMDGPUISD::FMAX_LEGACY:
10751     return performMinMaxCombine(N, DCI);
10752   case ISD::FMA:
10753     return performFMACombine(N, DCI);
10754   case ISD::AND:
10755     return performAndCombine(N, DCI);
10756   case ISD::OR:
10757     return performOrCombine(N, DCI);
10758   case ISD::XOR:
10759     return performXorCombine(N, DCI);
10760   case ISD::ZERO_EXTEND:
10761     return performZeroExtendCombine(N, DCI);
10762   case ISD::SIGN_EXTEND_INREG:
10763     return performSignExtendInRegCombine(N , DCI);
10764   case AMDGPUISD::FP_CLASS:
10765     return performClassCombine(N, DCI);
10766   case ISD::FCANONICALIZE:
10767     return performFCanonicalizeCombine(N, DCI);
10768   case AMDGPUISD::RCP:
10769     return performRcpCombine(N, DCI);
10770   case AMDGPUISD::FRACT:
10771   case AMDGPUISD::RSQ:
10772   case AMDGPUISD::RCP_LEGACY:
10773   case AMDGPUISD::RCP_IFLAG:
10774   case AMDGPUISD::RSQ_CLAMP:
10775   case AMDGPUISD::LDEXP: {
10776     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10777     SDValue Src = N->getOperand(0);
10778     if (Src.isUndef())
10779       return Src;
10780     break;
10781   }
10782   case ISD::SINT_TO_FP:
10783   case ISD::UINT_TO_FP:
10784     return performUCharToFloatCombine(N, DCI);
10785   case AMDGPUISD::CVT_F32_UBYTE0:
10786   case AMDGPUISD::CVT_F32_UBYTE1:
10787   case AMDGPUISD::CVT_F32_UBYTE2:
10788   case AMDGPUISD::CVT_F32_UBYTE3:
10789     return performCvtF32UByteNCombine(N, DCI);
10790   case AMDGPUISD::FMED3:
10791     return performFMed3Combine(N, DCI);
10792   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10793     return performCvtPkRTZCombine(N, DCI);
10794   case AMDGPUISD::CLAMP:
10795     return performClampCombine(N, DCI);
10796   case ISD::SCALAR_TO_VECTOR: {
10797     SelectionDAG &DAG = DCI.DAG;
10798     EVT VT = N->getValueType(0);
10799 
10800     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10801     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10802       SDLoc SL(N);
10803       SDValue Src = N->getOperand(0);
10804       EVT EltVT = Src.getValueType();
10805       if (EltVT == MVT::f16)
10806         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10807 
10808       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10809       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10810     }
10811 
10812     break;
10813   }
10814   case ISD::EXTRACT_VECTOR_ELT:
10815     return performExtractVectorEltCombine(N, DCI);
10816   case ISD::INSERT_VECTOR_ELT:
10817     return performInsertVectorEltCombine(N, DCI);
10818   case ISD::LOAD: {
10819     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10820       return Widended;
10821     LLVM_FALLTHROUGH;
10822   }
10823   default: {
10824     if (!DCI.isBeforeLegalize()) {
10825       if (MemSDNode *MemNode = dyn_cast<MemSDNode>(N))
10826         return performMemSDNodeCombine(MemNode, DCI);
10827     }
10828 
10829     break;
10830   }
10831   }
10832 
10833   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10834 }
10835 
10836 /// Helper function for adjustWritemask
10837 static unsigned SubIdx2Lane(unsigned Idx) {
10838   switch (Idx) {
10839   default: return 0;
10840   case AMDGPU::sub0: return 0;
10841   case AMDGPU::sub1: return 1;
10842   case AMDGPU::sub2: return 2;
10843   case AMDGPU::sub3: return 3;
10844   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10845   }
10846 }
10847 
10848 /// Adjust the writemask of MIMG instructions
10849 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10850                                           SelectionDAG &DAG) const {
10851   unsigned Opcode = Node->getMachineOpcode();
10852 
10853   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10854   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10855   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10856     return Node; // not implemented for D16
10857 
10858   SDNode *Users[5] = { nullptr };
10859   unsigned Lane = 0;
10860   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10861   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10862   unsigned NewDmask = 0;
10863   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10864   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10865   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10866                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10867   unsigned TFCLane = 0;
10868   bool HasChain = Node->getNumValues() > 1;
10869 
10870   if (OldDmask == 0) {
10871     // These are folded out, but on the chance it happens don't assert.
10872     return Node;
10873   }
10874 
10875   unsigned OldBitsSet = countPopulation(OldDmask);
10876   // Work out which is the TFE/LWE lane if that is enabled.
10877   if (UsesTFC) {
10878     TFCLane = OldBitsSet;
10879   }
10880 
10881   // Try to figure out the used register components
10882   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10883        I != E; ++I) {
10884 
10885     // Don't look at users of the chain.
10886     if (I.getUse().getResNo() != 0)
10887       continue;
10888 
10889     // Abort if we can't understand the usage
10890     if (!I->isMachineOpcode() ||
10891         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10892       return Node;
10893 
10894     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10895     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10896     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10897     // set, etc.
10898     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10899 
10900     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10901     if (UsesTFC && Lane == TFCLane) {
10902       Users[Lane] = *I;
10903     } else {
10904       // Set which texture component corresponds to the lane.
10905       unsigned Comp;
10906       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10907         Comp = countTrailingZeros(Dmask);
10908         Dmask &= ~(1 << Comp);
10909       }
10910 
10911       // Abort if we have more than one user per component.
10912       if (Users[Lane])
10913         return Node;
10914 
10915       Users[Lane] = *I;
10916       NewDmask |= 1 << Comp;
10917     }
10918   }
10919 
10920   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10921   bool NoChannels = !NewDmask;
10922   if (NoChannels) {
10923     if (!UsesTFC) {
10924       // No uses of the result and not using TFC. Then do nothing.
10925       return Node;
10926     }
10927     // If the original dmask has one channel - then nothing to do
10928     if (OldBitsSet == 1)
10929       return Node;
10930     // Use an arbitrary dmask - required for the instruction to work
10931     NewDmask = 1;
10932   }
10933   // Abort if there's no change
10934   if (NewDmask == OldDmask)
10935     return Node;
10936 
10937   unsigned BitsSet = countPopulation(NewDmask);
10938 
10939   // Check for TFE or LWE - increase the number of channels by one to account
10940   // for the extra return value
10941   // This will need adjustment for D16 if this is also included in
10942   // adjustWriteMask (this function) but at present D16 are excluded.
10943   unsigned NewChannels = BitsSet + UsesTFC;
10944 
10945   int NewOpcode =
10946       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10947   assert(NewOpcode != -1 &&
10948          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10949          "failed to find equivalent MIMG op");
10950 
10951   // Adjust the writemask in the node
10952   SmallVector<SDValue, 12> Ops;
10953   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10954   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10955   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10956 
10957   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10958 
10959   MVT ResultVT = NewChannels == 1 ?
10960     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10961                            NewChannels == 5 ? 8 : NewChannels);
10962   SDVTList NewVTList = HasChain ?
10963     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10964 
10965 
10966   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10967                                               NewVTList, Ops);
10968 
10969   if (HasChain) {
10970     // Update chain.
10971     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10972     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10973   }
10974 
10975   if (NewChannels == 1) {
10976     assert(Node->hasNUsesOfValue(1, 0));
10977     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10978                                       SDLoc(Node), Users[Lane]->getValueType(0),
10979                                       SDValue(NewNode, 0));
10980     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10981     return nullptr;
10982   }
10983 
10984   // Update the users of the node with the new indices
10985   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10986     SDNode *User = Users[i];
10987     if (!User) {
10988       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10989       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10990       if (i || !NoChannels)
10991         continue;
10992     } else {
10993       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10994       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10995     }
10996 
10997     switch (Idx) {
10998     default: break;
10999     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
11000     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
11001     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
11002     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
11003     }
11004   }
11005 
11006   DAG.RemoveDeadNode(Node);
11007   return nullptr;
11008 }
11009 
11010 static bool isFrameIndexOp(SDValue Op) {
11011   if (Op.getOpcode() == ISD::AssertZext)
11012     Op = Op.getOperand(0);
11013 
11014   return isa<FrameIndexSDNode>(Op);
11015 }
11016 
11017 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
11018 /// with frame index operands.
11019 /// LLVM assumes that inputs are to these instructions are registers.
11020 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
11021                                                         SelectionDAG &DAG) const {
11022   if (Node->getOpcode() == ISD::CopyToReg) {
11023     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
11024     SDValue SrcVal = Node->getOperand(2);
11025 
11026     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
11027     // to try understanding copies to physical registers.
11028     if (SrcVal.getValueType() == MVT::i1 && DestReg->getReg().isPhysical()) {
11029       SDLoc SL(Node);
11030       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11031       SDValue VReg = DAG.getRegister(
11032         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
11033 
11034       SDNode *Glued = Node->getGluedNode();
11035       SDValue ToVReg
11036         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
11037                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
11038       SDValue ToResultReg
11039         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
11040                            VReg, ToVReg.getValue(1));
11041       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
11042       DAG.RemoveDeadNode(Node);
11043       return ToResultReg.getNode();
11044     }
11045   }
11046 
11047   SmallVector<SDValue, 8> Ops;
11048   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
11049     if (!isFrameIndexOp(Node->getOperand(i))) {
11050       Ops.push_back(Node->getOperand(i));
11051       continue;
11052     }
11053 
11054     SDLoc DL(Node);
11055     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
11056                                      Node->getOperand(i).getValueType(),
11057                                      Node->getOperand(i)), 0));
11058   }
11059 
11060   return DAG.UpdateNodeOperands(Node, Ops);
11061 }
11062 
11063 /// Fold the instructions after selecting them.
11064 /// Returns null if users were already updated.
11065 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
11066                                           SelectionDAG &DAG) const {
11067   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11068   unsigned Opcode = Node->getMachineOpcode();
11069 
11070   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
11071       !TII->isGather4(Opcode) &&
11072       AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) != -1) {
11073     return adjustWritemask(Node, DAG);
11074   }
11075 
11076   if (Opcode == AMDGPU::INSERT_SUBREG ||
11077       Opcode == AMDGPU::REG_SEQUENCE) {
11078     legalizeTargetIndependentNode(Node, DAG);
11079     return Node;
11080   }
11081 
11082   switch (Opcode) {
11083   case AMDGPU::V_DIV_SCALE_F32:
11084   case AMDGPU::V_DIV_SCALE_F64: {
11085     // Satisfy the operand register constraint when one of the inputs is
11086     // undefined. Ordinarily each undef value will have its own implicit_def of
11087     // a vreg, so force these to use a single register.
11088     SDValue Src0 = Node->getOperand(0);
11089     SDValue Src1 = Node->getOperand(1);
11090     SDValue Src2 = Node->getOperand(2);
11091 
11092     if ((Src0.isMachineOpcode() &&
11093          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
11094         (Src0 == Src1 || Src0 == Src2))
11095       break;
11096 
11097     MVT VT = Src0.getValueType().getSimpleVT();
11098     const TargetRegisterClass *RC =
11099         getRegClassFor(VT, Src0.getNode()->isDivergent());
11100 
11101     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
11102     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
11103 
11104     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
11105                                       UndefReg, Src0, SDValue());
11106 
11107     // src0 must be the same register as src1 or src2, even if the value is
11108     // undefined, so make sure we don't violate this constraint.
11109     if (Src0.isMachineOpcode() &&
11110         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
11111       if (Src1.isMachineOpcode() &&
11112           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11113         Src0 = Src1;
11114       else if (Src2.isMachineOpcode() &&
11115                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
11116         Src0 = Src2;
11117       else {
11118         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
11119         Src0 = UndefReg;
11120         Src1 = UndefReg;
11121       }
11122     } else
11123       break;
11124 
11125     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
11126     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
11127       Ops.push_back(Node->getOperand(I));
11128 
11129     Ops.push_back(ImpDef.getValue(1));
11130     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
11131   }
11132   default:
11133     break;
11134   }
11135 
11136   return Node;
11137 }
11138 
11139 /// Assign the register class depending on the number of
11140 /// bits set in the writemask
11141 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
11142                                                      SDNode *Node) const {
11143   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11144 
11145   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
11146 
11147   if (TII->isVOP3(MI.getOpcode())) {
11148     // Make sure constant bus requirements are respected.
11149     TII->legalizeOperandsVOP3(MRI, MI);
11150 
11151     // Prefer VGPRs over AGPRs in mAI instructions where possible.
11152     // This saves a chain-copy of registers and better ballance register
11153     // use between vgpr and agpr as agpr tuples tend to be big.
11154     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
11155       unsigned Opc = MI.getOpcode();
11156       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11157       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
11158                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
11159         if (I == -1)
11160           break;
11161         MachineOperand &Op = MI.getOperand(I);
11162         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
11163              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
11164             !Op.getReg().isVirtual() || !TRI->isAGPR(MRI, Op.getReg()))
11165           continue;
11166         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
11167         if (!Src || !Src->isCopy() ||
11168             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
11169           continue;
11170         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
11171         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
11172         // All uses of agpr64 and agpr32 can also accept vgpr except for
11173         // v_accvgpr_read, but we do not produce agpr reads during selection,
11174         // so no use checks are needed.
11175         MRI.setRegClass(Op.getReg(), NewRC);
11176       }
11177     }
11178 
11179     return;
11180   }
11181 
11182   // Replace unused atomics with the no return version.
11183   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
11184   if (NoRetAtomicOp != -1) {
11185     if (!Node->hasAnyUseOfValue(0)) {
11186       MI.setDesc(TII->get(NoRetAtomicOp));
11187       MI.RemoveOperand(0);
11188       return;
11189     }
11190 
11191     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
11192     // instruction, because the return type of these instructions is a vec2 of
11193     // the memory type, so it can be tied to the input operand.
11194     // This means these instructions always have a use, so we need to add a
11195     // special case to check if the atomic has only one extract_subreg use,
11196     // which itself has no uses.
11197     if ((Node->hasNUsesOfValue(1, 0) &&
11198          Node->use_begin()->isMachineOpcode() &&
11199          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
11200          !Node->use_begin()->hasAnyUseOfValue(0))) {
11201       Register Def = MI.getOperand(0).getReg();
11202 
11203       // Change this into a noret atomic.
11204       MI.setDesc(TII->get(NoRetAtomicOp));
11205       MI.RemoveOperand(0);
11206 
11207       // If we only remove the def operand from the atomic instruction, the
11208       // extract_subreg will be left with a use of a vreg without a def.
11209       // So we need to insert an implicit_def to avoid machine verifier
11210       // errors.
11211       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
11212               TII->get(AMDGPU::IMPLICIT_DEF), Def);
11213     }
11214     return;
11215   }
11216 }
11217 
11218 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
11219                               uint64_t Val) {
11220   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
11221   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
11222 }
11223 
11224 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
11225                                                 const SDLoc &DL,
11226                                                 SDValue Ptr) const {
11227   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11228 
11229   // Build the half of the subregister with the constants before building the
11230   // full 128-bit register. If we are building multiple resource descriptors,
11231   // this will allow CSEing of the 2-component register.
11232   const SDValue Ops0[] = {
11233     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
11234     buildSMovImm32(DAG, DL, 0),
11235     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11236     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
11237     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
11238   };
11239 
11240   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
11241                                                 MVT::v2i32, Ops0), 0);
11242 
11243   // Combine the constants and the pointer.
11244   const SDValue Ops1[] = {
11245     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11246     Ptr,
11247     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
11248     SubRegHi,
11249     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
11250   };
11251 
11252   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
11253 }
11254 
11255 /// Return a resource descriptor with the 'Add TID' bit enabled
11256 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
11257 ///        of the resource descriptor) to create an offset, which is added to
11258 ///        the resource pointer.
11259 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
11260                                            SDValue Ptr, uint32_t RsrcDword1,
11261                                            uint64_t RsrcDword2And3) const {
11262   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
11263   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
11264   if (RsrcDword1) {
11265     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
11266                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
11267                     0);
11268   }
11269 
11270   SDValue DataLo = buildSMovImm32(DAG, DL,
11271                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
11272   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
11273 
11274   const SDValue Ops[] = {
11275     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
11276     PtrLo,
11277     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
11278     PtrHi,
11279     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
11280     DataLo,
11281     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
11282     DataHi,
11283     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
11284   };
11285 
11286   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
11287 }
11288 
11289 //===----------------------------------------------------------------------===//
11290 //                         SI Inline Assembly Support
11291 //===----------------------------------------------------------------------===//
11292 
11293 std::pair<unsigned, const TargetRegisterClass *>
11294 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11295                                                StringRef Constraint,
11296                                                MVT VT) const {
11297   const TargetRegisterClass *RC = nullptr;
11298   if (Constraint.size() == 1) {
11299     const unsigned BitWidth = VT.getSizeInBits();
11300     switch (Constraint[0]) {
11301     default:
11302       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11303     case 's':
11304     case 'r':
11305       switch (BitWidth) {
11306       case 16:
11307         RC = &AMDGPU::SReg_32RegClass;
11308         break;
11309       case 64:
11310         RC = &AMDGPU::SGPR_64RegClass;
11311         break;
11312       default:
11313         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11314         if (!RC)
11315           return std::make_pair(0U, nullptr);
11316         break;
11317       }
11318       break;
11319     case 'v':
11320       switch (BitWidth) {
11321       case 16:
11322         RC = &AMDGPU::VGPR_32RegClass;
11323         break;
11324       default:
11325         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11326         if (!RC)
11327           return std::make_pair(0U, nullptr);
11328         break;
11329       }
11330       break;
11331     case 'a':
11332       if (!Subtarget->hasMAIInsts())
11333         break;
11334       switch (BitWidth) {
11335       case 16:
11336         RC = &AMDGPU::AGPR_32RegClass;
11337         break;
11338       default:
11339         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11340         if (!RC)
11341           return std::make_pair(0U, nullptr);
11342         break;
11343       }
11344       break;
11345     }
11346     // We actually support i128, i16 and f16 as inline parameters
11347     // even if they are not reported as legal
11348     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11349                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11350       return std::make_pair(0U, RC);
11351   }
11352 
11353   if (Constraint.size() > 1) {
11354     if (Constraint[1] == 'v') {
11355       RC = &AMDGPU::VGPR_32RegClass;
11356     } else if (Constraint[1] == 's') {
11357       RC = &AMDGPU::SGPR_32RegClass;
11358     } else if (Constraint[1] == 'a') {
11359       RC = &AMDGPU::AGPR_32RegClass;
11360     }
11361 
11362     if (RC) {
11363       uint32_t Idx;
11364       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11365       if (!Failed && Idx < RC->getNumRegs())
11366         return std::make_pair(RC->getRegister(Idx), RC);
11367     }
11368   }
11369 
11370   // FIXME: Returns VS_32 for physical SGPR constraints
11371   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11372 }
11373 
11374 static bool isImmConstraint(StringRef Constraint) {
11375   if (Constraint.size() == 1) {
11376     switch (Constraint[0]) {
11377     default: break;
11378     case 'I':
11379     case 'J':
11380     case 'A':
11381     case 'B':
11382     case 'C':
11383       return true;
11384     }
11385   } else if (Constraint == "DA" ||
11386              Constraint == "DB") {
11387     return true;
11388   }
11389   return false;
11390 }
11391 
11392 SITargetLowering::ConstraintType
11393 SITargetLowering::getConstraintType(StringRef Constraint) const {
11394   if (Constraint.size() == 1) {
11395     switch (Constraint[0]) {
11396     default: break;
11397     case 's':
11398     case 'v':
11399     case 'a':
11400       return C_RegisterClass;
11401     }
11402   }
11403   if (isImmConstraint(Constraint)) {
11404     return C_Other;
11405   }
11406   return TargetLowering::getConstraintType(Constraint);
11407 }
11408 
11409 static uint64_t clearUnusedBits(uint64_t Val, unsigned Size) {
11410   if (!AMDGPU::isInlinableIntLiteral(Val)) {
11411     Val = Val & maskTrailingOnes<uint64_t>(Size);
11412   }
11413   return Val;
11414 }
11415 
11416 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11417                                                     std::string &Constraint,
11418                                                     std::vector<SDValue> &Ops,
11419                                                     SelectionDAG &DAG) const {
11420   if (isImmConstraint(Constraint)) {
11421     uint64_t Val;
11422     if (getAsmOperandConstVal(Op, Val) &&
11423         checkAsmConstraintVal(Op, Constraint, Val)) {
11424       Val = clearUnusedBits(Val, Op.getScalarValueSizeInBits());
11425       Ops.push_back(DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64));
11426     }
11427   } else {
11428     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11429   }
11430 }
11431 
11432 bool SITargetLowering::getAsmOperandConstVal(SDValue Op, uint64_t &Val) const {
11433   unsigned Size = Op.getScalarValueSizeInBits();
11434   if (Size > 64)
11435     return false;
11436 
11437   if (Size == 16 && !Subtarget->has16BitInsts())
11438     return false;
11439 
11440   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11441     Val = C->getSExtValue();
11442     return true;
11443   }
11444   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11445     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11446     return true;
11447   }
11448   if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11449     if (Size != 16 || Op.getNumOperands() != 2)
11450       return false;
11451     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11452       return false;
11453     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11454       Val = C->getSExtValue();
11455       return true;
11456     }
11457     if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11458       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11459       return true;
11460     }
11461   }
11462 
11463   return false;
11464 }
11465 
11466 bool SITargetLowering::checkAsmConstraintVal(SDValue Op,
11467                                              const std::string &Constraint,
11468                                              uint64_t Val) const {
11469   if (Constraint.size() == 1) {
11470     switch (Constraint[0]) {
11471     case 'I':
11472       return AMDGPU::isInlinableIntLiteral(Val);
11473     case 'J':
11474       return isInt<16>(Val);
11475     case 'A':
11476       return checkAsmConstraintValA(Op, Val);
11477     case 'B':
11478       return isInt<32>(Val);
11479     case 'C':
11480       return isUInt<32>(clearUnusedBits(Val, Op.getScalarValueSizeInBits())) ||
11481              AMDGPU::isInlinableIntLiteral(Val);
11482     default:
11483       break;
11484     }
11485   } else if (Constraint.size() == 2) {
11486     if (Constraint == "DA") {
11487       int64_t HiBits = static_cast<int32_t>(Val >> 32);
11488       int64_t LoBits = static_cast<int32_t>(Val);
11489       return checkAsmConstraintValA(Op, HiBits, 32) &&
11490              checkAsmConstraintValA(Op, LoBits, 32);
11491     }
11492     if (Constraint == "DB") {
11493       return true;
11494     }
11495   }
11496   llvm_unreachable("Invalid asm constraint");
11497 }
11498 
11499 bool SITargetLowering::checkAsmConstraintValA(SDValue Op,
11500                                               uint64_t Val,
11501                                               unsigned MaxSize) const {
11502   unsigned Size = std::min<unsigned>(Op.getScalarValueSizeInBits(), MaxSize);
11503   bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11504   if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11505       (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11506       (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11507     return true;
11508   }
11509   return false;
11510 }
11511 
11512 // Figure out which registers should be reserved for stack access. Only after
11513 // the function is legalized do we know all of the non-spill stack objects or if
11514 // calls are present.
11515 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11516   MachineRegisterInfo &MRI = MF.getRegInfo();
11517   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11518   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11519   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11520 
11521   if (Info->isEntryFunction()) {
11522     // Callable functions have fixed registers used for stack access.
11523     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11524   }
11525 
11526   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11527                              Info->getStackPtrOffsetReg()));
11528   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11529     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11530 
11531   // We need to worry about replacing the default register with itself in case
11532   // of MIR testcases missing the MFI.
11533   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11534     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11535 
11536   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11537     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11538 
11539   Info->limitOccupancy(MF);
11540 
11541   if (ST.isWave32() && !MF.empty()) {
11542     // Add VCC_HI def because many instructions marked as imp-use VCC where
11543     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11544     // having a use of undef.
11545 
11546     const SIInstrInfo *TII = ST.getInstrInfo();
11547     DebugLoc DL;
11548 
11549     MachineBasicBlock &MBB = MF.front();
11550     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11551     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11552 
11553     for (auto &MBB : MF) {
11554       for (auto &MI : MBB) {
11555         TII->fixImplicitOperands(MI);
11556       }
11557     }
11558   }
11559 
11560   TargetLoweringBase::finalizeLowering(MF);
11561 
11562   // Allocate a VGPR for future SGPR Spill if
11563   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11564   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11565   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11566       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11567     Info->reserveVGPRforSGPRSpills(MF);
11568 }
11569 
11570 void SITargetLowering::computeKnownBitsForFrameIndex(
11571   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11572   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11573 
11574   // Set the high bits to zero based on the maximum allowed scratch size per
11575   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11576   // calculation won't overflow, so assume the sign bit is never set.
11577   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11578 }
11579 
11580 static void knownBitsForWorkitemID(const GCNSubtarget &ST, GISelKnownBits &KB,
11581                                    KnownBits &Known, unsigned Dim) {
11582   unsigned MaxValue =
11583       ST.getMaxWorkitemID(KB.getMachineFunction().getFunction(), Dim);
11584   Known.Zero.setHighBits(countLeadingZeros(MaxValue));
11585 }
11586 
11587 void SITargetLowering::computeKnownBitsForTargetInstr(
11588     GISelKnownBits &KB, Register R, KnownBits &Known, const APInt &DemandedElts,
11589     const MachineRegisterInfo &MRI, unsigned Depth) const {
11590   const MachineInstr *MI = MRI.getVRegDef(R);
11591   switch (MI->getOpcode()) {
11592   case AMDGPU::G_INTRINSIC: {
11593     switch (MI->getIntrinsicID()) {
11594     case Intrinsic::amdgcn_workitem_id_x:
11595       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 0);
11596       break;
11597     case Intrinsic::amdgcn_workitem_id_y:
11598       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 1);
11599       break;
11600     case Intrinsic::amdgcn_workitem_id_z:
11601       knownBitsForWorkitemID(*getSubtarget(), KB, Known, 2);
11602       break;
11603     case Intrinsic::amdgcn_mbcnt_lo:
11604     case Intrinsic::amdgcn_mbcnt_hi: {
11605       // These return at most the wavefront size - 1.
11606       unsigned Size = MRI.getType(R).getSizeInBits();
11607       Known.Zero.setHighBits(Size - getSubtarget()->getWavefrontSizeLog2());
11608       break;
11609     }
11610     case Intrinsic::amdgcn_groupstaticsize: {
11611       // We can report everything over the maximum size as 0. We can't report
11612       // based on the actual size because we don't know if it's accurate or not
11613       // at any given point.
11614       Known.Zero.setHighBits(countLeadingZeros(getSubtarget()->getLocalMemorySize()));
11615       break;
11616     }
11617     }
11618     break;
11619   }
11620   case AMDGPU::G_AMDGPU_BUFFER_LOAD_UBYTE:
11621     Known.Zero.setHighBits(24);
11622     break;
11623   case AMDGPU::G_AMDGPU_BUFFER_LOAD_USHORT:
11624     Known.Zero.setHighBits(16);
11625     break;
11626   }
11627 }
11628 
11629 Align SITargetLowering::computeKnownAlignForTargetInstr(
11630   GISelKnownBits &KB, Register R, const MachineRegisterInfo &MRI,
11631   unsigned Depth) const {
11632   const MachineInstr *MI = MRI.getVRegDef(R);
11633   switch (MI->getOpcode()) {
11634   case AMDGPU::G_INTRINSIC:
11635   case AMDGPU::G_INTRINSIC_W_SIDE_EFFECTS: {
11636     // FIXME: Can this move to generic code? What about the case where the call
11637     // site specifies a lower alignment?
11638     Intrinsic::ID IID = MI->getIntrinsicID();
11639     LLVMContext &Ctx = KB.getMachineFunction().getFunction().getContext();
11640     AttributeList Attrs = Intrinsic::getAttributes(Ctx, IID);
11641     if (MaybeAlign RetAlign = Attrs.getRetAlignment())
11642       return *RetAlign;
11643     return Align(1);
11644   }
11645   default:
11646     return Align(1);
11647   }
11648 }
11649 
11650 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11651   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11652   const Align CacheLineAlign = Align(64);
11653 
11654   // Pre-GFX10 target did not benefit from loop alignment
11655   if (!ML || DisableLoopAlignment ||
11656       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11657       getSubtarget()->hasInstFwdPrefetchBug())
11658     return PrefAlign;
11659 
11660   // On GFX10 I$ is 4 x 64 bytes cache lines.
11661   // By default prefetcher keeps one cache line behind and reads two ahead.
11662   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11663   // behind and one ahead.
11664   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11665   // If loop fits 64 bytes it always spans no more than two cache lines and
11666   // does not need an alignment.
11667   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11668   // Else if loop is less or equal 192 bytes we need two lines behind.
11669 
11670   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11671   const MachineBasicBlock *Header = ML->getHeader();
11672   if (Header->getAlignment() != PrefAlign)
11673     return Header->getAlignment(); // Already processed.
11674 
11675   unsigned LoopSize = 0;
11676   for (const MachineBasicBlock *MBB : ML->blocks()) {
11677     // If inner loop block is aligned assume in average half of the alignment
11678     // size to be added as nops.
11679     if (MBB != Header)
11680       LoopSize += MBB->getAlignment().value() / 2;
11681 
11682     for (const MachineInstr &MI : *MBB) {
11683       LoopSize += TII->getInstSizeInBytes(MI);
11684       if (LoopSize > 192)
11685         return PrefAlign;
11686     }
11687   }
11688 
11689   if (LoopSize <= 64)
11690     return PrefAlign;
11691 
11692   if (LoopSize <= 128)
11693     return CacheLineAlign;
11694 
11695   // If any of parent loops is surrounded by prefetch instructions do not
11696   // insert new for inner loop, which would reset parent's settings.
11697   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11698     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11699       auto I = Exit->getFirstNonDebugInstr();
11700       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11701         return CacheLineAlign;
11702     }
11703   }
11704 
11705   MachineBasicBlock *Pre = ML->getLoopPreheader();
11706   MachineBasicBlock *Exit = ML->getExitBlock();
11707 
11708   if (Pre && Exit) {
11709     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11710             TII->get(AMDGPU::S_INST_PREFETCH))
11711       .addImm(1); // prefetch 2 lines behind PC
11712 
11713     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11714             TII->get(AMDGPU::S_INST_PREFETCH))
11715       .addImm(2); // prefetch 1 line behind PC
11716   }
11717 
11718   return CacheLineAlign;
11719 }
11720 
11721 LLVM_ATTRIBUTE_UNUSED
11722 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11723   assert(N->getOpcode() == ISD::CopyFromReg);
11724   do {
11725     // Follow the chain until we find an INLINEASM node.
11726     N = N->getOperand(0).getNode();
11727     if (N->getOpcode() == ISD::INLINEASM ||
11728         N->getOpcode() == ISD::INLINEASM_BR)
11729       return true;
11730   } while (N->getOpcode() == ISD::CopyFromReg);
11731   return false;
11732 }
11733 
11734 bool SITargetLowering::isSDNodeSourceOfDivergence(
11735     const SDNode *N, FunctionLoweringInfo *FLI,
11736     LegacyDivergenceAnalysis *KDA) const {
11737   switch (N->getOpcode()) {
11738   case ISD::CopyFromReg: {
11739     const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11740     const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11741     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11742     Register Reg = R->getReg();
11743 
11744     // FIXME: Why does this need to consider isLiveIn?
11745     if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11746       return !TRI->isSGPRReg(MRI, Reg);
11747 
11748     if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11749       return KDA->isDivergent(V);
11750 
11751     assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11752     return !TRI->isSGPRReg(MRI, Reg);
11753   }
11754   case ISD::LOAD: {
11755     const LoadSDNode *L = cast<LoadSDNode>(N);
11756     unsigned AS = L->getAddressSpace();
11757     // A flat load may access private memory.
11758     return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11759   }
11760   case ISD::CALLSEQ_END:
11761     return true;
11762   case ISD::INTRINSIC_WO_CHAIN:
11763     return AMDGPU::isIntrinsicSourceOfDivergence(
11764         cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11765   case ISD::INTRINSIC_W_CHAIN:
11766     return AMDGPU::isIntrinsicSourceOfDivergence(
11767         cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11768   }
11769   return false;
11770 }
11771 
11772 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11773                                                EVT VT) const {
11774   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11775   case MVT::f32:
11776     return hasFP32Denormals(DAG.getMachineFunction());
11777   case MVT::f64:
11778   case MVT::f16:
11779     return hasFP64FP16Denormals(DAG.getMachineFunction());
11780   default:
11781     return false;
11782   }
11783 }
11784 
11785 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11786                                                     const SelectionDAG &DAG,
11787                                                     bool SNaN,
11788                                                     unsigned Depth) const {
11789   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11790     const MachineFunction &MF = DAG.getMachineFunction();
11791     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11792 
11793     if (Info->getMode().DX10Clamp)
11794       return true; // Clamped to 0.
11795     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11796   }
11797 
11798   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11799                                                             SNaN, Depth);
11800 }
11801 
11802 // Global FP atomic instructions have a hardcoded FP mode and do not support
11803 // FP32 denormals, and only support v2f16 denormals.
11804 static bool fpModeMatchesGlobalFPAtomicMode(const AtomicRMWInst *RMW) {
11805   const fltSemantics &Flt = RMW->getType()->getScalarType()->getFltSemantics();
11806   auto DenormMode = RMW->getParent()->getParent()->getDenormalMode(Flt);
11807   if (&Flt == &APFloat::IEEEsingle())
11808     return DenormMode == DenormalMode::getPreserveSign();
11809   return DenormMode == DenormalMode::getIEEE();
11810 }
11811 
11812 TargetLowering::AtomicExpansionKind
11813 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11814   switch (RMW->getOperation()) {
11815   case AtomicRMWInst::FAdd: {
11816     Type *Ty = RMW->getType();
11817 
11818     // We don't have a way to support 16-bit atomics now, so just leave them
11819     // as-is.
11820     if (Ty->isHalfTy())
11821       return AtomicExpansionKind::None;
11822 
11823     if (!Ty->isFloatTy())
11824       return AtomicExpansionKind::CmpXChg;
11825 
11826     // TODO: Do have these for flat. Older targets also had them for buffers.
11827     unsigned AS = RMW->getPointerAddressSpace();
11828 
11829     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11830       if (!fpModeMatchesGlobalFPAtomicMode(RMW))
11831         return AtomicExpansionKind::CmpXChg;
11832 
11833       return RMW->use_empty() ? AtomicExpansionKind::None :
11834                                 AtomicExpansionKind::CmpXChg;
11835     }
11836 
11837     // DS FP atomics do repect the denormal mode, but the rounding mode is fixed
11838     // to round-to-nearest-even.
11839     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11840       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11841   }
11842   default:
11843     break;
11844   }
11845 
11846   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11847 }
11848 
11849 const TargetRegisterClass *
11850 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11851   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11852   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11853   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11854     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11855                                                : &AMDGPU::SReg_32RegClass;
11856   if (!TRI->isSGPRClass(RC) && !isDivergent)
11857     return TRI->getEquivalentSGPRClass(RC);
11858   else if (TRI->isSGPRClass(RC) && isDivergent)
11859     return TRI->getEquivalentVGPRClass(RC);
11860 
11861   return RC;
11862 }
11863 
11864 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11865 // uniform values (as produced by the mask results of control flow intrinsics)
11866 // used outside of divergent blocks. The phi users need to also be treated as
11867 // always uniform.
11868 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11869                       unsigned WaveSize) {
11870   // FIXME: We asssume we never cast the mask results of a control flow
11871   // intrinsic.
11872   // Early exit if the type won't be consistent as a compile time hack.
11873   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11874   if (!IT || IT->getBitWidth() != WaveSize)
11875     return false;
11876 
11877   if (!isa<Instruction>(V))
11878     return false;
11879   if (!Visited.insert(V).second)
11880     return false;
11881   bool Result = false;
11882   for (auto U : V->users()) {
11883     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11884       if (V == U->getOperand(1)) {
11885         switch (Intrinsic->getIntrinsicID()) {
11886         default:
11887           Result = false;
11888           break;
11889         case Intrinsic::amdgcn_if_break:
11890         case Intrinsic::amdgcn_if:
11891         case Intrinsic::amdgcn_else:
11892           Result = true;
11893           break;
11894         }
11895       }
11896       if (V == U->getOperand(0)) {
11897         switch (Intrinsic->getIntrinsicID()) {
11898         default:
11899           Result = false;
11900           break;
11901         case Intrinsic::amdgcn_end_cf:
11902         case Intrinsic::amdgcn_loop:
11903           Result = true;
11904           break;
11905         }
11906       }
11907     } else {
11908       Result = hasCFUser(U, Visited, WaveSize);
11909     }
11910     if (Result)
11911       break;
11912   }
11913   return Result;
11914 }
11915 
11916 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11917                                                const Value *V) const {
11918   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11919     if (CI->isInlineAsm()) {
11920       // FIXME: This cannot give a correct answer. This should only trigger in
11921       // the case where inline asm returns mixed SGPR and VGPR results, used
11922       // outside the defining block. We don't have a specific result to
11923       // consider, so this assumes if any value is SGPR, the overall register
11924       // also needs to be SGPR.
11925       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11926       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11927           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11928       for (auto &TC : TargetConstraints) {
11929         if (TC.Type == InlineAsm::isOutput) {
11930           ComputeConstraintToUse(TC, SDValue());
11931           unsigned AssignedReg;
11932           const TargetRegisterClass *RC;
11933           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11934               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11935           if (RC) {
11936             MachineRegisterInfo &MRI = MF.getRegInfo();
11937             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11938               return true;
11939             else if (SIRI->isSGPRClass(RC))
11940               return true;
11941           }
11942         }
11943       }
11944     }
11945   }
11946   SmallPtrSet<const Value *, 16> Visited;
11947   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11948 }
11949 
11950 std::pair<int, MVT>
11951 SITargetLowering::getTypeLegalizationCost(const DataLayout &DL,
11952                                           Type *Ty) const {
11953   auto Cost = TargetLoweringBase::getTypeLegalizationCost(DL, Ty);
11954   auto Size = DL.getTypeSizeInBits(Ty);
11955   // Maximum load or store can handle 8 dwords for scalar and 4 for
11956   // vector ALU. Let's assume anything above 8 dwords is expensive
11957   // even if legal.
11958   if (Size <= 256)
11959     return Cost;
11960 
11961   Cost.first = (Size + 255) / 256;
11962   return Cost;
11963 }
11964