1 //===-- SIISelLowering.cpp - SI DAG Lowering Implementation ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file
10 /// Custom DAG lowering for SI
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "SIISelLowering.h"
15 #include "AMDGPU.h"
16 #include "AMDGPUSubtarget.h"
17 #include "AMDGPUTargetMachine.h"
18 #include "MCTargetDesc/AMDGPUMCTargetDesc.h"
19 #include "SIDefines.h"
20 #include "SIInstrInfo.h"
21 #include "SIMachineFunctionInfo.h"
22 #include "SIRegisterInfo.h"
23 #include "Utils/AMDGPUBaseInfo.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/BitVector.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringRef.h"
31 #include "llvm/ADT/StringSwitch.h"
32 #include "llvm/ADT/Twine.h"
33 #include "llvm/Analysis/LegacyDivergenceAnalysis.h"
34 #include "llvm/CodeGen/Analysis.h"
35 #include "llvm/CodeGen/CallingConvLower.h"
36 #include "llvm/CodeGen/DAGCombine.h"
37 #include "llvm/CodeGen/ISDOpcodes.h"
38 #include "llvm/CodeGen/MachineBasicBlock.h"
39 #include "llvm/CodeGen/MachineFrameInfo.h"
40 #include "llvm/CodeGen/MachineFunction.h"
41 #include "llvm/CodeGen/MachineInstr.h"
42 #include "llvm/CodeGen/MachineInstrBuilder.h"
43 #include "llvm/CodeGen/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachineMemOperand.h"
45 #include "llvm/CodeGen/MachineModuleInfo.h"
46 #include "llvm/CodeGen/MachineOperand.h"
47 #include "llvm/CodeGen/MachineRegisterInfo.h"
48 #include "llvm/CodeGen/SelectionDAG.h"
49 #include "llvm/CodeGen/SelectionDAGNodes.h"
50 #include "llvm/CodeGen/TargetCallingConv.h"
51 #include "llvm/CodeGen/TargetRegisterInfo.h"
52 #include "llvm/CodeGen/ValueTypes.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/DebugLoc.h"
56 #include "llvm/IR/DerivedTypes.h"
57 #include "llvm/IR/DiagnosticInfo.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/GlobalValue.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Type.h"
65 #include "llvm/Support/Casting.h"
66 #include "llvm/Support/CodeGen.h"
67 #include "llvm/Support/CommandLine.h"
68 #include "llvm/Support/Compiler.h"
69 #include "llvm/Support/ErrorHandling.h"
70 #include "llvm/Support/KnownBits.h"
71 #include "llvm/Support/MachineValueType.h"
72 #include "llvm/Support/MathExtras.h"
73 #include "llvm/Target/TargetOptions.h"
74 #include <cassert>
75 #include <cmath>
76 #include <cstdint>
77 #include <iterator>
78 #include <tuple>
79 #include <utility>
80 #include <vector>
81 
82 using namespace llvm;
83 
84 #define DEBUG_TYPE "si-lower"
85 
86 STATISTIC(NumTailCalls, "Number of tail calls");
87 
88 static cl::opt<bool> DisableLoopAlignment(
89   "amdgpu-disable-loop-alignment",
90   cl::desc("Do not align and prefetch loops"),
91   cl::init(false));
92 
93 static cl::opt<bool> VGPRReserveforSGPRSpill(
94     "amdgpu-reserve-vgpr-for-sgpr-spill",
95     cl::desc("Allocates one VGPR for future SGPR Spill"), cl::init(true));
96 
97 static cl::opt<bool> UseDivergentRegisterIndexing(
98   "amdgpu-use-divergent-register-indexing",
99   cl::Hidden,
100   cl::desc("Use indirect register addressing for divergent indexes"),
101   cl::init(false));
102 
103 static bool hasFP32Denormals(const MachineFunction &MF) {
104   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
105   return Info->getMode().allFP32Denormals();
106 }
107 
108 static bool hasFP64FP16Denormals(const MachineFunction &MF) {
109   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
110   return Info->getMode().allFP64FP16Denormals();
111 }
112 
113 static unsigned findFirstFreeSGPR(CCState &CCInfo) {
114   unsigned NumSGPRs = AMDGPU::SGPR_32RegClass.getNumRegs();
115   for (unsigned Reg = 0; Reg < NumSGPRs; ++Reg) {
116     if (!CCInfo.isAllocated(AMDGPU::SGPR0 + Reg)) {
117       return AMDGPU::SGPR0 + Reg;
118     }
119   }
120   llvm_unreachable("Cannot allocate sgpr");
121 }
122 
123 SITargetLowering::SITargetLowering(const TargetMachine &TM,
124                                    const GCNSubtarget &STI)
125     : AMDGPUTargetLowering(TM, STI),
126       Subtarget(&STI) {
127   addRegisterClass(MVT::i1, &AMDGPU::VReg_1RegClass);
128   addRegisterClass(MVT::i64, &AMDGPU::SReg_64RegClass);
129 
130   addRegisterClass(MVT::i32, &AMDGPU::SReg_32RegClass);
131   addRegisterClass(MVT::f32, &AMDGPU::VGPR_32RegClass);
132 
133   addRegisterClass(MVT::f64, &AMDGPU::VReg_64RegClass);
134   addRegisterClass(MVT::v2i32, &AMDGPU::SReg_64RegClass);
135   addRegisterClass(MVT::v2f32, &AMDGPU::VReg_64RegClass);
136 
137   addRegisterClass(MVT::v3i32, &AMDGPU::SGPR_96RegClass);
138   addRegisterClass(MVT::v3f32, &AMDGPU::VReg_96RegClass);
139 
140   addRegisterClass(MVT::v2i64, &AMDGPU::SGPR_128RegClass);
141   addRegisterClass(MVT::v2f64, &AMDGPU::SGPR_128RegClass);
142 
143   addRegisterClass(MVT::v4i32, &AMDGPU::SGPR_128RegClass);
144   addRegisterClass(MVT::v4f32, &AMDGPU::VReg_128RegClass);
145 
146   addRegisterClass(MVT::v5i32, &AMDGPU::SGPR_160RegClass);
147   addRegisterClass(MVT::v5f32, &AMDGPU::VReg_160RegClass);
148 
149   addRegisterClass(MVT::v8i32, &AMDGPU::SGPR_256RegClass);
150   addRegisterClass(MVT::v8f32, &AMDGPU::VReg_256RegClass);
151 
152   addRegisterClass(MVT::v4i64, &AMDGPU::SGPR_256RegClass);
153   addRegisterClass(MVT::v4f64, &AMDGPU::VReg_256RegClass);
154 
155   addRegisterClass(MVT::v16i32, &AMDGPU::SGPR_512RegClass);
156   addRegisterClass(MVT::v16f32, &AMDGPU::VReg_512RegClass);
157 
158   addRegisterClass(MVT::v8i64, &AMDGPU::SGPR_512RegClass);
159   addRegisterClass(MVT::v8f64, &AMDGPU::VReg_512RegClass);
160 
161   addRegisterClass(MVT::v16i64, &AMDGPU::SGPR_1024RegClass);
162   addRegisterClass(MVT::v16f64, &AMDGPU::VReg_1024RegClass);
163 
164   if (Subtarget->has16BitInsts()) {
165     addRegisterClass(MVT::i16, &AMDGPU::SReg_32RegClass);
166     addRegisterClass(MVT::f16, &AMDGPU::SReg_32RegClass);
167 
168     // Unless there are also VOP3P operations, not operations are really legal.
169     addRegisterClass(MVT::v2i16, &AMDGPU::SReg_32RegClass);
170     addRegisterClass(MVT::v2f16, &AMDGPU::SReg_32RegClass);
171     addRegisterClass(MVT::v4i16, &AMDGPU::SReg_64RegClass);
172     addRegisterClass(MVT::v4f16, &AMDGPU::SReg_64RegClass);
173   }
174 
175   addRegisterClass(MVT::v32i32, &AMDGPU::VReg_1024RegClass);
176   addRegisterClass(MVT::v32f32, &AMDGPU::VReg_1024RegClass);
177 
178   computeRegisterProperties(Subtarget->getRegisterInfo());
179 
180   // The boolean content concept here is too inflexible. Compares only ever
181   // really produce a 1-bit result. Any copy/extend from these will turn into a
182   // select, and zext/1 or sext/-1 are equally cheap. Arbitrarily choose 0/1, as
183   // it's what most targets use.
184   setBooleanContents(ZeroOrOneBooleanContent);
185   setBooleanVectorContents(ZeroOrOneBooleanContent);
186 
187   // We need to custom lower vector stores from local memory
188   setOperationAction(ISD::LOAD, MVT::v2i32, Custom);
189   setOperationAction(ISD::LOAD, MVT::v3i32, Custom);
190   setOperationAction(ISD::LOAD, MVT::v4i32, Custom);
191   setOperationAction(ISD::LOAD, MVT::v5i32, Custom);
192   setOperationAction(ISD::LOAD, MVT::v8i32, Custom);
193   setOperationAction(ISD::LOAD, MVT::v16i32, Custom);
194   setOperationAction(ISD::LOAD, MVT::i1, Custom);
195   setOperationAction(ISD::LOAD, MVT::v32i32, Custom);
196 
197   setOperationAction(ISD::STORE, MVT::v2i32, Custom);
198   setOperationAction(ISD::STORE, MVT::v3i32, Custom);
199   setOperationAction(ISD::STORE, MVT::v4i32, Custom);
200   setOperationAction(ISD::STORE, MVT::v5i32, Custom);
201   setOperationAction(ISD::STORE, MVT::v8i32, Custom);
202   setOperationAction(ISD::STORE, MVT::v16i32, Custom);
203   setOperationAction(ISD::STORE, MVT::i1, Custom);
204   setOperationAction(ISD::STORE, MVT::v32i32, Custom);
205 
206   setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
207   setTruncStoreAction(MVT::v3i32, MVT::v3i16, Expand);
208   setTruncStoreAction(MVT::v4i32, MVT::v4i16, Expand);
209   setTruncStoreAction(MVT::v8i32, MVT::v8i16, Expand);
210   setTruncStoreAction(MVT::v16i32, MVT::v16i16, Expand);
211   setTruncStoreAction(MVT::v32i32, MVT::v32i16, Expand);
212   setTruncStoreAction(MVT::v2i32, MVT::v2i8, Expand);
213   setTruncStoreAction(MVT::v4i32, MVT::v4i8, Expand);
214   setTruncStoreAction(MVT::v8i32, MVT::v8i8, Expand);
215   setTruncStoreAction(MVT::v16i32, MVT::v16i8, Expand);
216   setTruncStoreAction(MVT::v32i32, MVT::v32i8, Expand);
217   setTruncStoreAction(MVT::v2i16, MVT::v2i8, Expand);
218   setTruncStoreAction(MVT::v4i16, MVT::v4i8, Expand);
219   setTruncStoreAction(MVT::v8i16, MVT::v8i8, Expand);
220   setTruncStoreAction(MVT::v16i16, MVT::v16i8, Expand);
221   setTruncStoreAction(MVT::v32i16, MVT::v32i8, Expand);
222 
223   setTruncStoreAction(MVT::v4i64, MVT::v4i8, Expand);
224   setTruncStoreAction(MVT::v8i64, MVT::v8i8, Expand);
225   setTruncStoreAction(MVT::v8i64, MVT::v8i16, Expand);
226   setTruncStoreAction(MVT::v8i64, MVT::v8i32, Expand);
227   setTruncStoreAction(MVT::v16i64, MVT::v16i32, Expand);
228 
229   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
230   setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
231 
232   setOperationAction(ISD::SELECT, MVT::i1, Promote);
233   setOperationAction(ISD::SELECT, MVT::i64, Custom);
234   setOperationAction(ISD::SELECT, MVT::f64, Promote);
235   AddPromotedToType(ISD::SELECT, MVT::f64, MVT::i64);
236 
237   setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
238   setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
239   setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
240   setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
241   setOperationAction(ISD::SELECT_CC, MVT::i1, Expand);
242 
243   setOperationAction(ISD::SETCC, MVT::i1, Promote);
244   setOperationAction(ISD::SETCC, MVT::v2i1, Expand);
245   setOperationAction(ISD::SETCC, MVT::v4i1, Expand);
246   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
247 
248   setOperationAction(ISD::TRUNCATE, MVT::v2i32, Expand);
249   setOperationAction(ISD::FP_ROUND, MVT::v2f32, Expand);
250   setOperationAction(ISD::TRUNCATE, MVT::v4i32, Expand);
251   setOperationAction(ISD::FP_ROUND, MVT::v4f32, Expand);
252   setOperationAction(ISD::TRUNCATE, MVT::v8i32, Expand);
253   setOperationAction(ISD::FP_ROUND, MVT::v8f32, Expand);
254   setOperationAction(ISD::TRUNCATE, MVT::v16i32, Expand);
255   setOperationAction(ISD::FP_ROUND, MVT::v16f32, Expand);
256 
257   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i1, Custom);
258   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i1, Custom);
259   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i8, Custom);
260   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i8, Custom);
261   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v2i16, Custom);
262   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v3i16, Custom);
263   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::v4i16, Custom);
264   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::Other, Custom);
265 
266   setOperationAction(ISD::BRCOND, MVT::Other, Custom);
267   setOperationAction(ISD::BR_CC, MVT::i1, Expand);
268   setOperationAction(ISD::BR_CC, MVT::i32, Expand);
269   setOperationAction(ISD::BR_CC, MVT::i64, Expand);
270   setOperationAction(ISD::BR_CC, MVT::f32, Expand);
271   setOperationAction(ISD::BR_CC, MVT::f64, Expand);
272 
273   setOperationAction(ISD::UADDO, MVT::i32, Legal);
274   setOperationAction(ISD::USUBO, MVT::i32, Legal);
275 
276   setOperationAction(ISD::ADDCARRY, MVT::i32, Legal);
277   setOperationAction(ISD::SUBCARRY, MVT::i32, Legal);
278 
279   setOperationAction(ISD::SHL_PARTS, MVT::i64, Expand);
280   setOperationAction(ISD::SRA_PARTS, MVT::i64, Expand);
281   setOperationAction(ISD::SRL_PARTS, MVT::i64, Expand);
282 
283 #if 0
284   setOperationAction(ISD::ADDCARRY, MVT::i64, Legal);
285   setOperationAction(ISD::SUBCARRY, MVT::i64, Legal);
286 #endif
287 
288   // We only support LOAD/STORE and vector manipulation ops for vectors
289   // with > 4 elements.
290   for (MVT VT : { MVT::v8i32, MVT::v8f32, MVT::v16i32, MVT::v16f32,
291                   MVT::v2i64, MVT::v2f64, MVT::v4i16, MVT::v4f16,
292                   MVT::v4i64, MVT::v4f64, MVT::v8i64, MVT::v8f64,
293                   MVT::v16i64, MVT::v16f64, MVT::v32i32, MVT::v32f32 }) {
294     for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
295       switch (Op) {
296       case ISD::LOAD:
297       case ISD::STORE:
298       case ISD::BUILD_VECTOR:
299       case ISD::BITCAST:
300       case ISD::EXTRACT_VECTOR_ELT:
301       case ISD::INSERT_VECTOR_ELT:
302       case ISD::INSERT_SUBVECTOR:
303       case ISD::EXTRACT_SUBVECTOR:
304       case ISD::SCALAR_TO_VECTOR:
305         break;
306       case ISD::CONCAT_VECTORS:
307         setOperationAction(Op, VT, Custom);
308         break;
309       default:
310         setOperationAction(Op, VT, Expand);
311         break;
312       }
313     }
314   }
315 
316   setOperationAction(ISD::FP_EXTEND, MVT::v4f32, Expand);
317 
318   // TODO: For dynamic 64-bit vector inserts/extracts, should emit a pseudo that
319   // is expanded to avoid having two separate loops in case the index is a VGPR.
320 
321   // Most operations are naturally 32-bit vector operations. We only support
322   // load and store of i64 vectors, so promote v2i64 vector operations to v4i32.
323   for (MVT Vec64 : { MVT::v2i64, MVT::v2f64 }) {
324     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
325     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v4i32);
326 
327     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
328     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v4i32);
329 
330     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
331     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v4i32);
332 
333     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
334     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v4i32);
335   }
336 
337   for (MVT Vec64 : { MVT::v4i64, MVT::v4f64 }) {
338     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
339     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v8i32);
340 
341     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
342     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v8i32);
343 
344     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
345     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v8i32);
346 
347     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
348     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v8i32);
349   }
350 
351   for (MVT Vec64 : { MVT::v8i64, MVT::v8f64 }) {
352     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
353     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v16i32);
354 
355     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
356     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v16i32);
357 
358     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
359     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v16i32);
360 
361     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
362     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v16i32);
363   }
364 
365   for (MVT Vec64 : { MVT::v16i64, MVT::v16f64 }) {
366     setOperationAction(ISD::BUILD_VECTOR, Vec64, Promote);
367     AddPromotedToType(ISD::BUILD_VECTOR, Vec64, MVT::v32i32);
368 
369     setOperationAction(ISD::EXTRACT_VECTOR_ELT, Vec64, Promote);
370     AddPromotedToType(ISD::EXTRACT_VECTOR_ELT, Vec64, MVT::v32i32);
371 
372     setOperationAction(ISD::INSERT_VECTOR_ELT, Vec64, Promote);
373     AddPromotedToType(ISD::INSERT_VECTOR_ELT, Vec64, MVT::v32i32);
374 
375     setOperationAction(ISD::SCALAR_TO_VECTOR, Vec64, Promote);
376     AddPromotedToType(ISD::SCALAR_TO_VECTOR, Vec64, MVT::v32i32);
377   }
378 
379   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8i32, Expand);
380   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v8f32, Expand);
381   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16i32, Expand);
382   setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v16f32, Expand);
383 
384   setOperationAction(ISD::BUILD_VECTOR, MVT::v4f16, Custom);
385   setOperationAction(ISD::BUILD_VECTOR, MVT::v4i16, Custom);
386 
387   // Avoid stack access for these.
388   // TODO: Generalize to more vector types.
389   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i16, Custom);
390   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2f16, Custom);
391   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
392   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
393 
394   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
395   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
396   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i8, Custom);
397   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i8, Custom);
398   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i8, Custom);
399 
400   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v2i8, Custom);
401   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i8, Custom);
402   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v8i8, Custom);
403 
404   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i16, Custom);
405   setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f16, Custom);
406   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4i16, Custom);
407   setOperationAction(ISD::INSERT_VECTOR_ELT, MVT::v4f16, Custom);
408 
409   // Deal with vec3 vector operations when widened to vec4.
410   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3i32, Custom);
411   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v3f32, Custom);
412   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4i32, Custom);
413   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v4f32, Custom);
414 
415   // Deal with vec5 vector operations when widened to vec8.
416   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5i32, Custom);
417   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v5f32, Custom);
418   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8i32, Custom);
419   setOperationAction(ISD::INSERT_SUBVECTOR, MVT::v8f32, Custom);
420 
421   // BUFFER/FLAT_ATOMIC_CMP_SWAP on GCN GPUs needs input marshalling,
422   // and output demarshalling
423   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Custom);
424   setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, Custom);
425 
426   // We can't return success/failure, only the old value,
427   // let LLVM add the comparison
428   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i32, Expand);
429   setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i64, Expand);
430 
431   if (Subtarget->hasFlatAddressSpace()) {
432     setOperationAction(ISD::ADDRSPACECAST, MVT::i32, Custom);
433     setOperationAction(ISD::ADDRSPACECAST, MVT::i64, Custom);
434   }
435 
436   setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
437 
438   // FIXME: This should be narrowed to i32, but that only happens if i64 is
439   // illegal.
440   // FIXME: Should lower sub-i32 bswaps to bit-ops without v_perm_b32.
441   setOperationAction(ISD::BSWAP, MVT::i64, Legal);
442   setOperationAction(ISD::BSWAP, MVT::i32, Legal);
443 
444   // On SI this is s_memtime and s_memrealtime on VI.
445   setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
446   setOperationAction(ISD::TRAP, MVT::Other, Custom);
447   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Custom);
448 
449   if (Subtarget->has16BitInsts()) {
450     setOperationAction(ISD::FPOW, MVT::f16, Promote);
451     setOperationAction(ISD::FLOG, MVT::f16, Custom);
452     setOperationAction(ISD::FEXP, MVT::f16, Custom);
453     setOperationAction(ISD::FLOG10, MVT::f16, Custom);
454   }
455 
456   // v_mad_f32 does not support denormals. We report it as unconditionally
457   // legal, and the context where it is formed will disallow it when fp32
458   // denormals are enabled.
459   setOperationAction(ISD::FMAD, MVT::f32, Legal);
460 
461   if (!Subtarget->hasBFI()) {
462     // fcopysign can be done in a single instruction with BFI.
463     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
464     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
465   }
466 
467   if (!Subtarget->hasBCNT(32))
468     setOperationAction(ISD::CTPOP, MVT::i32, Expand);
469 
470   if (!Subtarget->hasBCNT(64))
471     setOperationAction(ISD::CTPOP, MVT::i64, Expand);
472 
473   if (Subtarget->hasFFBH())
474     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Custom);
475 
476   if (Subtarget->hasFFBL())
477     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Custom);
478 
479   // We only really have 32-bit BFE instructions (and 16-bit on VI).
480   //
481   // On SI+ there are 64-bit BFEs, but they are scalar only and there isn't any
482   // effort to match them now. We want this to be false for i64 cases when the
483   // extraction isn't restricted to the upper or lower half. Ideally we would
484   // have some pass reduce 64-bit extracts to 32-bit if possible. Extracts that
485   // span the midpoint are probably relatively rare, so don't worry about them
486   // for now.
487   if (Subtarget->hasBFE())
488     setHasExtractBitsInsn(true);
489 
490   setOperationAction(ISD::FMINNUM, MVT::f32, Custom);
491   setOperationAction(ISD::FMAXNUM, MVT::f32, Custom);
492   setOperationAction(ISD::FMINNUM, MVT::f64, Custom);
493   setOperationAction(ISD::FMAXNUM, MVT::f64, Custom);
494 
495 
496   // These are really only legal for ieee_mode functions. We should be avoiding
497   // them for functions that don't have ieee_mode enabled, so just say they are
498   // legal.
499   setOperationAction(ISD::FMINNUM_IEEE, MVT::f32, Legal);
500   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f32, Legal);
501   setOperationAction(ISD::FMINNUM_IEEE, MVT::f64, Legal);
502   setOperationAction(ISD::FMAXNUM_IEEE, MVT::f64, Legal);
503 
504 
505   if (Subtarget->haveRoundOpsF64()) {
506     setOperationAction(ISD::FTRUNC, MVT::f64, Legal);
507     setOperationAction(ISD::FCEIL, MVT::f64, Legal);
508     setOperationAction(ISD::FRINT, MVT::f64, Legal);
509   } else {
510     setOperationAction(ISD::FCEIL, MVT::f64, Custom);
511     setOperationAction(ISD::FTRUNC, MVT::f64, Custom);
512     setOperationAction(ISD::FRINT, MVT::f64, Custom);
513     setOperationAction(ISD::FFLOOR, MVT::f64, Custom);
514   }
515 
516   setOperationAction(ISD::FFLOOR, MVT::f64, Legal);
517 
518   setOperationAction(ISD::FSIN, MVT::f32, Custom);
519   setOperationAction(ISD::FCOS, MVT::f32, Custom);
520   setOperationAction(ISD::FDIV, MVT::f32, Custom);
521   setOperationAction(ISD::FDIV, MVT::f64, Custom);
522 
523   if (Subtarget->has16BitInsts()) {
524     setOperationAction(ISD::Constant, MVT::i16, Legal);
525 
526     setOperationAction(ISD::SMIN, MVT::i16, Legal);
527     setOperationAction(ISD::SMAX, MVT::i16, Legal);
528 
529     setOperationAction(ISD::UMIN, MVT::i16, Legal);
530     setOperationAction(ISD::UMAX, MVT::i16, Legal);
531 
532     setOperationAction(ISD::SIGN_EXTEND, MVT::i16, Promote);
533     AddPromotedToType(ISD::SIGN_EXTEND, MVT::i16, MVT::i32);
534 
535     setOperationAction(ISD::ROTR, MVT::i16, Promote);
536     setOperationAction(ISD::ROTL, MVT::i16, Promote);
537 
538     setOperationAction(ISD::SDIV, MVT::i16, Promote);
539     setOperationAction(ISD::UDIV, MVT::i16, Promote);
540     setOperationAction(ISD::SREM, MVT::i16, Promote);
541     setOperationAction(ISD::UREM, MVT::i16, Promote);
542 
543     setOperationAction(ISD::BITREVERSE, MVT::i16, Promote);
544 
545     setOperationAction(ISD::CTTZ, MVT::i16, Promote);
546     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16, Promote);
547     setOperationAction(ISD::CTLZ, MVT::i16, Promote);
548     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16, Promote);
549     setOperationAction(ISD::CTPOP, MVT::i16, Promote);
550 
551     setOperationAction(ISD::SELECT_CC, MVT::i16, Expand);
552 
553     setOperationAction(ISD::BR_CC, MVT::i16, Expand);
554 
555     setOperationAction(ISD::LOAD, MVT::i16, Custom);
556 
557     setTruncStoreAction(MVT::i64, MVT::i16, Expand);
558 
559     setOperationAction(ISD::FP16_TO_FP, MVT::i16, Promote);
560     AddPromotedToType(ISD::FP16_TO_FP, MVT::i16, MVT::i32);
561     setOperationAction(ISD::FP_TO_FP16, MVT::i16, Promote);
562     AddPromotedToType(ISD::FP_TO_FP16, MVT::i16, MVT::i32);
563 
564     setOperationAction(ISD::FP_TO_SINT, MVT::i16, Promote);
565     setOperationAction(ISD::FP_TO_UINT, MVT::i16, Promote);
566 
567     // F16 - Constant Actions.
568     setOperationAction(ISD::ConstantFP, MVT::f16, Legal);
569 
570     // F16 - Load/Store Actions.
571     setOperationAction(ISD::LOAD, MVT::f16, Promote);
572     AddPromotedToType(ISD::LOAD, MVT::f16, MVT::i16);
573     setOperationAction(ISD::STORE, MVT::f16, Promote);
574     AddPromotedToType(ISD::STORE, MVT::f16, MVT::i16);
575 
576     // F16 - VOP1 Actions.
577     setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
578     setOperationAction(ISD::FCOS, MVT::f16, Custom);
579     setOperationAction(ISD::FSIN, MVT::f16, Custom);
580 
581     setOperationAction(ISD::SINT_TO_FP, MVT::i16, Custom);
582     setOperationAction(ISD::UINT_TO_FP, MVT::i16, Custom);
583 
584     setOperationAction(ISD::FP_TO_SINT, MVT::f16, Promote);
585     setOperationAction(ISD::FP_TO_UINT, MVT::f16, Promote);
586     setOperationAction(ISD::SINT_TO_FP, MVT::f16, Promote);
587     setOperationAction(ISD::UINT_TO_FP, MVT::f16, Promote);
588     setOperationAction(ISD::FROUND, MVT::f16, Custom);
589 
590     // F16 - VOP2 Actions.
591     setOperationAction(ISD::BR_CC, MVT::f16, Expand);
592     setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
593 
594     setOperationAction(ISD::FDIV, MVT::f16, Custom);
595 
596     // F16 - VOP3 Actions.
597     setOperationAction(ISD::FMA, MVT::f16, Legal);
598     if (STI.hasMadF16())
599       setOperationAction(ISD::FMAD, MVT::f16, Legal);
600 
601     for (MVT VT : {MVT::v2i16, MVT::v2f16, MVT::v4i16, MVT::v4f16}) {
602       for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op) {
603         switch (Op) {
604         case ISD::LOAD:
605         case ISD::STORE:
606         case ISD::BUILD_VECTOR:
607         case ISD::BITCAST:
608         case ISD::EXTRACT_VECTOR_ELT:
609         case ISD::INSERT_VECTOR_ELT:
610         case ISD::INSERT_SUBVECTOR:
611         case ISD::EXTRACT_SUBVECTOR:
612         case ISD::SCALAR_TO_VECTOR:
613           break;
614         case ISD::CONCAT_VECTORS:
615           setOperationAction(Op, VT, Custom);
616           break;
617         default:
618           setOperationAction(Op, VT, Expand);
619           break;
620         }
621       }
622     }
623 
624     // v_perm_b32 can handle either of these.
625     setOperationAction(ISD::BSWAP, MVT::i16, Legal);
626     setOperationAction(ISD::BSWAP, MVT::v2i16, Legal);
627     setOperationAction(ISD::BSWAP, MVT::v4i16, Custom);
628 
629     // XXX - Do these do anything? Vector constants turn into build_vector.
630     setOperationAction(ISD::Constant, MVT::v2i16, Legal);
631     setOperationAction(ISD::ConstantFP, MVT::v2f16, Legal);
632 
633     setOperationAction(ISD::UNDEF, MVT::v2i16, Legal);
634     setOperationAction(ISD::UNDEF, MVT::v2f16, Legal);
635 
636     setOperationAction(ISD::STORE, MVT::v2i16, Promote);
637     AddPromotedToType(ISD::STORE, MVT::v2i16, MVT::i32);
638     setOperationAction(ISD::STORE, MVT::v2f16, Promote);
639     AddPromotedToType(ISD::STORE, MVT::v2f16, MVT::i32);
640 
641     setOperationAction(ISD::LOAD, MVT::v2i16, Promote);
642     AddPromotedToType(ISD::LOAD, MVT::v2i16, MVT::i32);
643     setOperationAction(ISD::LOAD, MVT::v2f16, Promote);
644     AddPromotedToType(ISD::LOAD, MVT::v2f16, MVT::i32);
645 
646     setOperationAction(ISD::AND, MVT::v2i16, Promote);
647     AddPromotedToType(ISD::AND, MVT::v2i16, MVT::i32);
648     setOperationAction(ISD::OR, MVT::v2i16, Promote);
649     AddPromotedToType(ISD::OR, MVT::v2i16, MVT::i32);
650     setOperationAction(ISD::XOR, MVT::v2i16, Promote);
651     AddPromotedToType(ISD::XOR, MVT::v2i16, MVT::i32);
652 
653     setOperationAction(ISD::LOAD, MVT::v4i16, Promote);
654     AddPromotedToType(ISD::LOAD, MVT::v4i16, MVT::v2i32);
655     setOperationAction(ISD::LOAD, MVT::v4f16, Promote);
656     AddPromotedToType(ISD::LOAD, MVT::v4f16, MVT::v2i32);
657 
658     setOperationAction(ISD::STORE, MVT::v4i16, Promote);
659     AddPromotedToType(ISD::STORE, MVT::v4i16, MVT::v2i32);
660     setOperationAction(ISD::STORE, MVT::v4f16, Promote);
661     AddPromotedToType(ISD::STORE, MVT::v4f16, MVT::v2i32);
662 
663     setOperationAction(ISD::ANY_EXTEND, MVT::v2i32, Expand);
664     setOperationAction(ISD::ZERO_EXTEND, MVT::v2i32, Expand);
665     setOperationAction(ISD::SIGN_EXTEND, MVT::v2i32, Expand);
666     setOperationAction(ISD::FP_EXTEND, MVT::v2f32, Expand);
667 
668     setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Expand);
669     setOperationAction(ISD::ZERO_EXTEND, MVT::v4i32, Expand);
670     setOperationAction(ISD::SIGN_EXTEND, MVT::v4i32, Expand);
671 
672     if (!Subtarget->hasVOP3PInsts()) {
673       setOperationAction(ISD::BUILD_VECTOR, MVT::v2i16, Custom);
674       setOperationAction(ISD::BUILD_VECTOR, MVT::v2f16, Custom);
675     }
676 
677     setOperationAction(ISD::FNEG, MVT::v2f16, Legal);
678     // This isn't really legal, but this avoids the legalizer unrolling it (and
679     // allows matching fneg (fabs x) patterns)
680     setOperationAction(ISD::FABS, MVT::v2f16, Legal);
681 
682     setOperationAction(ISD::FMAXNUM, MVT::f16, Custom);
683     setOperationAction(ISD::FMINNUM, MVT::f16, Custom);
684     setOperationAction(ISD::FMAXNUM_IEEE, MVT::f16, Legal);
685     setOperationAction(ISD::FMINNUM_IEEE, MVT::f16, Legal);
686 
687     setOperationAction(ISD::FMINNUM_IEEE, MVT::v4f16, Custom);
688     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v4f16, Custom);
689 
690     setOperationAction(ISD::FMINNUM, MVT::v4f16, Expand);
691     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Expand);
692   }
693 
694   if (Subtarget->hasVOP3PInsts()) {
695     setOperationAction(ISD::ADD, MVT::v2i16, Legal);
696     setOperationAction(ISD::SUB, MVT::v2i16, Legal);
697     setOperationAction(ISD::MUL, MVT::v2i16, Legal);
698     setOperationAction(ISD::SHL, MVT::v2i16, Legal);
699     setOperationAction(ISD::SRL, MVT::v2i16, Legal);
700     setOperationAction(ISD::SRA, MVT::v2i16, Legal);
701     setOperationAction(ISD::SMIN, MVT::v2i16, Legal);
702     setOperationAction(ISD::UMIN, MVT::v2i16, Legal);
703     setOperationAction(ISD::SMAX, MVT::v2i16, Legal);
704     setOperationAction(ISD::UMAX, MVT::v2i16, Legal);
705 
706     setOperationAction(ISD::FADD, MVT::v2f16, Legal);
707     setOperationAction(ISD::FMUL, MVT::v2f16, Legal);
708     setOperationAction(ISD::FMA, MVT::v2f16, Legal);
709 
710     setOperationAction(ISD::FMINNUM_IEEE, MVT::v2f16, Legal);
711     setOperationAction(ISD::FMAXNUM_IEEE, MVT::v2f16, Legal);
712 
713     setOperationAction(ISD::FCANONICALIZE, MVT::v2f16, Legal);
714 
715     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i16, Custom);
716     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f16, Custom);
717 
718     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4f16, Custom);
719     setOperationAction(ISD::VECTOR_SHUFFLE, MVT::v4i16, Custom);
720 
721     setOperationAction(ISD::SHL, MVT::v4i16, Custom);
722     setOperationAction(ISD::SRA, MVT::v4i16, Custom);
723     setOperationAction(ISD::SRL, MVT::v4i16, Custom);
724     setOperationAction(ISD::ADD, MVT::v4i16, Custom);
725     setOperationAction(ISD::SUB, MVT::v4i16, Custom);
726     setOperationAction(ISD::MUL, MVT::v4i16, Custom);
727 
728     setOperationAction(ISD::SMIN, MVT::v4i16, Custom);
729     setOperationAction(ISD::SMAX, MVT::v4i16, Custom);
730     setOperationAction(ISD::UMIN, MVT::v4i16, Custom);
731     setOperationAction(ISD::UMAX, MVT::v4i16, Custom);
732 
733     setOperationAction(ISD::FADD, MVT::v4f16, Custom);
734     setOperationAction(ISD::FMUL, MVT::v4f16, Custom);
735     setOperationAction(ISD::FMA, MVT::v4f16, Custom);
736 
737     setOperationAction(ISD::FMAXNUM, MVT::v2f16, Custom);
738     setOperationAction(ISD::FMINNUM, MVT::v2f16, Custom);
739 
740     setOperationAction(ISD::FMINNUM, MVT::v4f16, Custom);
741     setOperationAction(ISD::FMAXNUM, MVT::v4f16, Custom);
742     setOperationAction(ISD::FCANONICALIZE, MVT::v4f16, Custom);
743 
744     setOperationAction(ISD::FEXP, MVT::v2f16, Custom);
745     setOperationAction(ISD::SELECT, MVT::v4i16, Custom);
746     setOperationAction(ISD::SELECT, MVT::v4f16, Custom);
747   }
748 
749   setOperationAction(ISD::FNEG, MVT::v4f16, Custom);
750   setOperationAction(ISD::FABS, MVT::v4f16, Custom);
751 
752   if (Subtarget->has16BitInsts()) {
753     setOperationAction(ISD::SELECT, MVT::v2i16, Promote);
754     AddPromotedToType(ISD::SELECT, MVT::v2i16, MVT::i32);
755     setOperationAction(ISD::SELECT, MVT::v2f16, Promote);
756     AddPromotedToType(ISD::SELECT, MVT::v2f16, MVT::i32);
757   } else {
758     // Legalization hack.
759     setOperationAction(ISD::SELECT, MVT::v2i16, Custom);
760     setOperationAction(ISD::SELECT, MVT::v2f16, Custom);
761 
762     setOperationAction(ISD::FNEG, MVT::v2f16, Custom);
763     setOperationAction(ISD::FABS, MVT::v2f16, Custom);
764   }
765 
766   for (MVT VT : { MVT::v4i16, MVT::v4f16, MVT::v2i8, MVT::v4i8, MVT::v8i8 }) {
767     setOperationAction(ISD::SELECT, VT, Custom);
768   }
769 
770   setOperationAction(ISD::SMULO, MVT::i64, Custom);
771   setOperationAction(ISD::UMULO, MVT::i64, Custom);
772 
773   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
774   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f32, Custom);
775   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v4f32, Custom);
776   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
777   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::f16, Custom);
778   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2i16, Custom);
779   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::v2f16, Custom);
780 
781   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2f16, Custom);
782   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v2i16, Custom);
783   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4f16, Custom);
784   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v4i16, Custom);
785   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::v8f16, Custom);
786   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
787   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::f16, Custom);
788   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i16, Custom);
789   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
790 
791   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
792   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2i16, Custom);
793   setOperationAction(ISD::INTRINSIC_VOID, MVT::v2f16, Custom);
794   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4f16, Custom);
795   setOperationAction(ISD::INTRINSIC_VOID, MVT::v4i16, Custom);
796   setOperationAction(ISD::INTRINSIC_VOID, MVT::f16, Custom);
797   setOperationAction(ISD::INTRINSIC_VOID, MVT::i16, Custom);
798   setOperationAction(ISD::INTRINSIC_VOID, MVT::i8, Custom);
799 
800   setTargetDAGCombine(ISD::ADD);
801   setTargetDAGCombine(ISD::ADDCARRY);
802   setTargetDAGCombine(ISD::SUB);
803   setTargetDAGCombine(ISD::SUBCARRY);
804   setTargetDAGCombine(ISD::FADD);
805   setTargetDAGCombine(ISD::FSUB);
806   setTargetDAGCombine(ISD::FMINNUM);
807   setTargetDAGCombine(ISD::FMAXNUM);
808   setTargetDAGCombine(ISD::FMINNUM_IEEE);
809   setTargetDAGCombine(ISD::FMAXNUM_IEEE);
810   setTargetDAGCombine(ISD::FMA);
811   setTargetDAGCombine(ISD::SMIN);
812   setTargetDAGCombine(ISD::SMAX);
813   setTargetDAGCombine(ISD::UMIN);
814   setTargetDAGCombine(ISD::UMAX);
815   setTargetDAGCombine(ISD::SETCC);
816   setTargetDAGCombine(ISD::AND);
817   setTargetDAGCombine(ISD::OR);
818   setTargetDAGCombine(ISD::XOR);
819   setTargetDAGCombine(ISD::SINT_TO_FP);
820   setTargetDAGCombine(ISD::UINT_TO_FP);
821   setTargetDAGCombine(ISD::FCANONICALIZE);
822   setTargetDAGCombine(ISD::SCALAR_TO_VECTOR);
823   setTargetDAGCombine(ISD::ZERO_EXTEND);
824   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
825   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
826   setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
827 
828   // All memory operations. Some folding on the pointer operand is done to help
829   // matching the constant offsets in the addressing modes.
830   setTargetDAGCombine(ISD::LOAD);
831   setTargetDAGCombine(ISD::STORE);
832   setTargetDAGCombine(ISD::ATOMIC_LOAD);
833   setTargetDAGCombine(ISD::ATOMIC_STORE);
834   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP);
835   setTargetDAGCombine(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
836   setTargetDAGCombine(ISD::ATOMIC_SWAP);
837   setTargetDAGCombine(ISD::ATOMIC_LOAD_ADD);
838   setTargetDAGCombine(ISD::ATOMIC_LOAD_SUB);
839   setTargetDAGCombine(ISD::ATOMIC_LOAD_AND);
840   setTargetDAGCombine(ISD::ATOMIC_LOAD_OR);
841   setTargetDAGCombine(ISD::ATOMIC_LOAD_XOR);
842   setTargetDAGCombine(ISD::ATOMIC_LOAD_NAND);
843   setTargetDAGCombine(ISD::ATOMIC_LOAD_MIN);
844   setTargetDAGCombine(ISD::ATOMIC_LOAD_MAX);
845   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMIN);
846   setTargetDAGCombine(ISD::ATOMIC_LOAD_UMAX);
847   setTargetDAGCombine(ISD::ATOMIC_LOAD_FADD);
848 
849   // FIXME: In other contexts we pretend this is a per-function property.
850   setStackPointerRegisterToSaveRestore(AMDGPU::SGPR32);
851 
852   setSchedulingPreference(Sched::RegPressure);
853 }
854 
855 const GCNSubtarget *SITargetLowering::getSubtarget() const {
856   return Subtarget;
857 }
858 
859 //===----------------------------------------------------------------------===//
860 // TargetLowering queries
861 //===----------------------------------------------------------------------===//
862 
863 // v_mad_mix* support a conversion from f16 to f32.
864 //
865 // There is only one special case when denormals are enabled we don't currently,
866 // where this is OK to use.
867 bool SITargetLowering::isFPExtFoldable(const SelectionDAG &DAG, unsigned Opcode,
868                                        EVT DestVT, EVT SrcVT) const {
869   return ((Opcode == ISD::FMAD && Subtarget->hasMadMixInsts()) ||
870           (Opcode == ISD::FMA && Subtarget->hasFmaMixInsts())) &&
871     DestVT.getScalarType() == MVT::f32 &&
872     SrcVT.getScalarType() == MVT::f16 &&
873     // TODO: This probably only requires no input flushing?
874     !hasFP32Denormals(DAG.getMachineFunction());
875 }
876 
877 bool SITargetLowering::isShuffleMaskLegal(ArrayRef<int>, EVT) const {
878   // SI has some legal vector types, but no legal vector operations. Say no
879   // shuffles are legal in order to prefer scalarizing some vector operations.
880   return false;
881 }
882 
883 MVT SITargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
884                                                     CallingConv::ID CC,
885                                                     EVT VT) const {
886   if (CC == CallingConv::AMDGPU_KERNEL)
887     return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
888 
889   if (VT.isVector()) {
890     EVT ScalarVT = VT.getScalarType();
891     unsigned Size = ScalarVT.getSizeInBits();
892     if (Size == 32)
893       return ScalarVT.getSimpleVT();
894 
895     if (Size > 32)
896       return MVT::i32;
897 
898     if (Size == 16 && Subtarget->has16BitInsts())
899       return VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
900   } else if (VT.getSizeInBits() > 32)
901     return MVT::i32;
902 
903   return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
904 }
905 
906 unsigned SITargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
907                                                          CallingConv::ID CC,
908                                                          EVT VT) const {
909   if (CC == CallingConv::AMDGPU_KERNEL)
910     return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
911 
912   if (VT.isVector()) {
913     unsigned NumElts = VT.getVectorNumElements();
914     EVT ScalarVT = VT.getScalarType();
915     unsigned Size = ScalarVT.getSizeInBits();
916 
917     if (Size == 32)
918       return NumElts;
919 
920     if (Size > 32)
921       return NumElts * ((Size + 31) / 32);
922 
923     if (Size == 16 && Subtarget->has16BitInsts())
924       return (NumElts + 1) / 2;
925   } else if (VT.getSizeInBits() > 32)
926     return (VT.getSizeInBits() + 31) / 32;
927 
928   return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
929 }
930 
931 unsigned SITargetLowering::getVectorTypeBreakdownForCallingConv(
932   LLVMContext &Context, CallingConv::ID CC,
933   EVT VT, EVT &IntermediateVT,
934   unsigned &NumIntermediates, MVT &RegisterVT) const {
935   if (CC != CallingConv::AMDGPU_KERNEL && VT.isVector()) {
936     unsigned NumElts = VT.getVectorNumElements();
937     EVT ScalarVT = VT.getScalarType();
938     unsigned Size = ScalarVT.getSizeInBits();
939     if (Size == 32) {
940       RegisterVT = ScalarVT.getSimpleVT();
941       IntermediateVT = RegisterVT;
942       NumIntermediates = NumElts;
943       return NumIntermediates;
944     }
945 
946     if (Size > 32) {
947       RegisterVT = MVT::i32;
948       IntermediateVT = RegisterVT;
949       NumIntermediates = NumElts * ((Size + 31) / 32);
950       return NumIntermediates;
951     }
952 
953     // FIXME: We should fix the ABI to be the same on targets without 16-bit
954     // support, but unless we can properly handle 3-vectors, it will be still be
955     // inconsistent.
956     if (Size == 16 && Subtarget->has16BitInsts()) {
957       RegisterVT = VT.isInteger() ? MVT::v2i16 : MVT::v2f16;
958       IntermediateVT = RegisterVT;
959       NumIntermediates = (NumElts + 1) / 2;
960       return NumIntermediates;
961     }
962   }
963 
964   return TargetLowering::getVectorTypeBreakdownForCallingConv(
965     Context, CC, VT, IntermediateVT, NumIntermediates, RegisterVT);
966 }
967 
968 static EVT memVTFromImageData(Type *Ty, unsigned DMaskLanes) {
969   assert(DMaskLanes != 0);
970 
971   if (auto *VT = dyn_cast<FixedVectorType>(Ty)) {
972     unsigned NumElts = std::min(DMaskLanes, VT->getNumElements());
973     return EVT::getVectorVT(Ty->getContext(),
974                             EVT::getEVT(VT->getElementType()),
975                             NumElts);
976   }
977 
978   return EVT::getEVT(Ty);
979 }
980 
981 // Peek through TFE struct returns to only use the data size.
982 static EVT memVTFromImageReturn(Type *Ty, unsigned DMaskLanes) {
983   auto *ST = dyn_cast<StructType>(Ty);
984   if (!ST)
985     return memVTFromImageData(Ty, DMaskLanes);
986 
987   // Some intrinsics return an aggregate type - special case to work out the
988   // correct memVT.
989   //
990   // Only limited forms of aggregate type currently expected.
991   if (ST->getNumContainedTypes() != 2 ||
992       !ST->getContainedType(1)->isIntegerTy(32))
993     return EVT();
994   return memVTFromImageData(ST->getContainedType(0), DMaskLanes);
995 }
996 
997 bool SITargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
998                                           const CallInst &CI,
999                                           MachineFunction &MF,
1000                                           unsigned IntrID) const {
1001   if (const AMDGPU::RsrcIntrinsic *RsrcIntr =
1002           AMDGPU::lookupRsrcIntrinsic(IntrID)) {
1003     AttributeList Attr = Intrinsic::getAttributes(CI.getContext(),
1004                                                   (Intrinsic::ID)IntrID);
1005     if (Attr.hasFnAttribute(Attribute::ReadNone))
1006       return false;
1007 
1008     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1009 
1010     if (RsrcIntr->IsImage) {
1011       Info.ptrVal = MFI->getImagePSV(
1012         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1013         CI.getArgOperand(RsrcIntr->RsrcArg));
1014       Info.align.reset();
1015     } else {
1016       Info.ptrVal = MFI->getBufferPSV(
1017         *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1018         CI.getArgOperand(RsrcIntr->RsrcArg));
1019     }
1020 
1021     Info.flags = MachineMemOperand::MODereferenceable;
1022     if (Attr.hasFnAttribute(Attribute::ReadOnly)) {
1023       unsigned DMaskLanes = 4;
1024 
1025       if (RsrcIntr->IsImage) {
1026         const AMDGPU::ImageDimIntrinsicInfo *Intr
1027           = AMDGPU::getImageDimIntrinsicInfo(IntrID);
1028         const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
1029           AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
1030 
1031         if (!BaseOpcode->Gather4) {
1032           // If this isn't a gather, we may have excess loaded elements in the
1033           // IR type. Check the dmask for the real number of elements loaded.
1034           unsigned DMask
1035             = cast<ConstantInt>(CI.getArgOperand(0))->getZExtValue();
1036           DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1037         }
1038 
1039         Info.memVT = memVTFromImageReturn(CI.getType(), DMaskLanes);
1040       } else
1041         Info.memVT = EVT::getEVT(CI.getType());
1042 
1043       // FIXME: What does alignment mean for an image?
1044       Info.opc = ISD::INTRINSIC_W_CHAIN;
1045       Info.flags |= MachineMemOperand::MOLoad;
1046     } else if (Attr.hasFnAttribute(Attribute::WriteOnly)) {
1047       Info.opc = ISD::INTRINSIC_VOID;
1048 
1049       Type *DataTy = CI.getArgOperand(0)->getType();
1050       if (RsrcIntr->IsImage) {
1051         unsigned DMask = cast<ConstantInt>(CI.getArgOperand(1))->getZExtValue();
1052         unsigned DMaskLanes = DMask == 0 ? 1 : countPopulation(DMask);
1053         Info.memVT = memVTFromImageData(DataTy, DMaskLanes);
1054       } else
1055         Info.memVT = EVT::getEVT(DataTy);
1056 
1057       Info.flags |= MachineMemOperand::MOStore;
1058     } else {
1059       // Atomic
1060       Info.opc = ISD::INTRINSIC_W_CHAIN;
1061       Info.memVT = MVT::getVT(CI.getType());
1062       Info.flags = MachineMemOperand::MOLoad |
1063                    MachineMemOperand::MOStore |
1064                    MachineMemOperand::MODereferenceable;
1065 
1066       // XXX - Should this be volatile without known ordering?
1067       Info.flags |= MachineMemOperand::MOVolatile;
1068     }
1069     return true;
1070   }
1071 
1072   switch (IntrID) {
1073   case Intrinsic::amdgcn_atomic_inc:
1074   case Intrinsic::amdgcn_atomic_dec:
1075   case Intrinsic::amdgcn_ds_ordered_add:
1076   case Intrinsic::amdgcn_ds_ordered_swap:
1077   case Intrinsic::amdgcn_ds_fadd:
1078   case Intrinsic::amdgcn_ds_fmin:
1079   case Intrinsic::amdgcn_ds_fmax: {
1080     Info.opc = ISD::INTRINSIC_W_CHAIN;
1081     Info.memVT = MVT::getVT(CI.getType());
1082     Info.ptrVal = CI.getOperand(0);
1083     Info.align.reset();
1084     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1085 
1086     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(4));
1087     if (!Vol->isZero())
1088       Info.flags |= MachineMemOperand::MOVolatile;
1089 
1090     return true;
1091   }
1092   case Intrinsic::amdgcn_buffer_atomic_fadd: {
1093     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1094 
1095     Info.opc = ISD::INTRINSIC_VOID;
1096     Info.memVT = MVT::getVT(CI.getOperand(0)->getType());
1097     Info.ptrVal = MFI->getBufferPSV(
1098       *MF.getSubtarget<GCNSubtarget>().getInstrInfo(),
1099       CI.getArgOperand(1));
1100     Info.align.reset();
1101     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1102 
1103     const ConstantInt *Vol = dyn_cast<ConstantInt>(CI.getOperand(4));
1104     if (!Vol || !Vol->isZero())
1105       Info.flags |= MachineMemOperand::MOVolatile;
1106 
1107     return true;
1108   }
1109   case Intrinsic::amdgcn_global_atomic_fadd: {
1110     Info.opc = ISD::INTRINSIC_VOID;
1111     Info.memVT = MVT::getVT(CI.getOperand(0)->getType()
1112                             ->getPointerElementType());
1113     Info.ptrVal = CI.getOperand(0);
1114     Info.align.reset();
1115     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1116 
1117     return true;
1118   }
1119   case Intrinsic::amdgcn_ds_append:
1120   case Intrinsic::amdgcn_ds_consume: {
1121     Info.opc = ISD::INTRINSIC_W_CHAIN;
1122     Info.memVT = MVT::getVT(CI.getType());
1123     Info.ptrVal = CI.getOperand(0);
1124     Info.align.reset();
1125     Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
1126 
1127     const ConstantInt *Vol = cast<ConstantInt>(CI.getOperand(1));
1128     if (!Vol->isZero())
1129       Info.flags |= MachineMemOperand::MOVolatile;
1130 
1131     return true;
1132   }
1133   case Intrinsic::amdgcn_ds_gws_init:
1134   case Intrinsic::amdgcn_ds_gws_barrier:
1135   case Intrinsic::amdgcn_ds_gws_sema_v:
1136   case Intrinsic::amdgcn_ds_gws_sema_br:
1137   case Intrinsic::amdgcn_ds_gws_sema_p:
1138   case Intrinsic::amdgcn_ds_gws_sema_release_all: {
1139     Info.opc = ISD::INTRINSIC_VOID;
1140 
1141     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
1142     Info.ptrVal =
1143         MFI->getGWSPSV(*MF.getSubtarget<GCNSubtarget>().getInstrInfo());
1144 
1145     // This is an abstract access, but we need to specify a type and size.
1146     Info.memVT = MVT::i32;
1147     Info.size = 4;
1148     Info.align = Align(4);
1149 
1150     Info.flags = MachineMemOperand::MOStore;
1151     if (IntrID == Intrinsic::amdgcn_ds_gws_barrier)
1152       Info.flags = MachineMemOperand::MOLoad;
1153     return true;
1154   }
1155   default:
1156     return false;
1157   }
1158 }
1159 
1160 bool SITargetLowering::getAddrModeArguments(IntrinsicInst *II,
1161                                             SmallVectorImpl<Value*> &Ops,
1162                                             Type *&AccessTy) const {
1163   switch (II->getIntrinsicID()) {
1164   case Intrinsic::amdgcn_atomic_inc:
1165   case Intrinsic::amdgcn_atomic_dec:
1166   case Intrinsic::amdgcn_ds_ordered_add:
1167   case Intrinsic::amdgcn_ds_ordered_swap:
1168   case Intrinsic::amdgcn_ds_fadd:
1169   case Intrinsic::amdgcn_ds_fmin:
1170   case Intrinsic::amdgcn_ds_fmax: {
1171     Value *Ptr = II->getArgOperand(0);
1172     AccessTy = II->getType();
1173     Ops.push_back(Ptr);
1174     return true;
1175   }
1176   default:
1177     return false;
1178   }
1179 }
1180 
1181 bool SITargetLowering::isLegalFlatAddressingMode(const AddrMode &AM) const {
1182   if (!Subtarget->hasFlatInstOffsets()) {
1183     // Flat instructions do not have offsets, and only have the register
1184     // address.
1185     return AM.BaseOffs == 0 && AM.Scale == 0;
1186   }
1187 
1188   return AM.Scale == 0 &&
1189          (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1190                                   AM.BaseOffs, AMDGPUAS::FLAT_ADDRESS,
1191                                   /*Signed=*/false));
1192 }
1193 
1194 bool SITargetLowering::isLegalGlobalAddressingMode(const AddrMode &AM) const {
1195   if (Subtarget->hasFlatGlobalInsts())
1196     return AM.Scale == 0 &&
1197            (AM.BaseOffs == 0 || Subtarget->getInstrInfo()->isLegalFLATOffset(
1198                                     AM.BaseOffs, AMDGPUAS::GLOBAL_ADDRESS,
1199                                     /*Signed=*/true));
1200 
1201   if (!Subtarget->hasAddr64() || Subtarget->useFlatForGlobal()) {
1202       // Assume the we will use FLAT for all global memory accesses
1203       // on VI.
1204       // FIXME: This assumption is currently wrong.  On VI we still use
1205       // MUBUF instructions for the r + i addressing mode.  As currently
1206       // implemented, the MUBUF instructions only work on buffer < 4GB.
1207       // It may be possible to support > 4GB buffers with MUBUF instructions,
1208       // by setting the stride value in the resource descriptor which would
1209       // increase the size limit to (stride * 4GB).  However, this is risky,
1210       // because it has never been validated.
1211     return isLegalFlatAddressingMode(AM);
1212   }
1213 
1214   return isLegalMUBUFAddressingMode(AM);
1215 }
1216 
1217 bool SITargetLowering::isLegalMUBUFAddressingMode(const AddrMode &AM) const {
1218   // MUBUF / MTBUF instructions have a 12-bit unsigned byte offset, and
1219   // additionally can do r + r + i with addr64. 32-bit has more addressing
1220   // mode options. Depending on the resource constant, it can also do
1221   // (i64 r0) + (i32 r1) * (i14 i).
1222   //
1223   // Private arrays end up using a scratch buffer most of the time, so also
1224   // assume those use MUBUF instructions. Scratch loads / stores are currently
1225   // implemented as mubuf instructions with offen bit set, so slightly
1226   // different than the normal addr64.
1227   if (!isUInt<12>(AM.BaseOffs))
1228     return false;
1229 
1230   // FIXME: Since we can split immediate into soffset and immediate offset,
1231   // would it make sense to allow any immediate?
1232 
1233   switch (AM.Scale) {
1234   case 0: // r + i or just i, depending on HasBaseReg.
1235     return true;
1236   case 1:
1237     return true; // We have r + r or r + i.
1238   case 2:
1239     if (AM.HasBaseReg) {
1240       // Reject 2 * r + r.
1241       return false;
1242     }
1243 
1244     // Allow 2 * r as r + r
1245     // Or  2 * r + i is allowed as r + r + i.
1246     return true;
1247   default: // Don't allow n * r
1248     return false;
1249   }
1250 }
1251 
1252 bool SITargetLowering::isLegalAddressingMode(const DataLayout &DL,
1253                                              const AddrMode &AM, Type *Ty,
1254                                              unsigned AS, Instruction *I) const {
1255   // No global is ever allowed as a base.
1256   if (AM.BaseGV)
1257     return false;
1258 
1259   if (AS == AMDGPUAS::GLOBAL_ADDRESS)
1260     return isLegalGlobalAddressingMode(AM);
1261 
1262   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
1263       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
1264       AS == AMDGPUAS::BUFFER_FAT_POINTER) {
1265     // If the offset isn't a multiple of 4, it probably isn't going to be
1266     // correctly aligned.
1267     // FIXME: Can we get the real alignment here?
1268     if (AM.BaseOffs % 4 != 0)
1269       return isLegalMUBUFAddressingMode(AM);
1270 
1271     // There are no SMRD extloads, so if we have to do a small type access we
1272     // will use a MUBUF load.
1273     // FIXME?: We also need to do this if unaligned, but we don't know the
1274     // alignment here.
1275     if (Ty->isSized() && DL.getTypeStoreSize(Ty) < 4)
1276       return isLegalGlobalAddressingMode(AM);
1277 
1278     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS) {
1279       // SMRD instructions have an 8-bit, dword offset on SI.
1280       if (!isUInt<8>(AM.BaseOffs / 4))
1281         return false;
1282     } else if (Subtarget->getGeneration() == AMDGPUSubtarget::SEA_ISLANDS) {
1283       // On CI+, this can also be a 32-bit literal constant offset. If it fits
1284       // in 8-bits, it can use a smaller encoding.
1285       if (!isUInt<32>(AM.BaseOffs / 4))
1286         return false;
1287     } else if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS) {
1288       // On VI, these use the SMEM format and the offset is 20-bit in bytes.
1289       if (!isUInt<20>(AM.BaseOffs))
1290         return false;
1291     } else
1292       llvm_unreachable("unhandled generation");
1293 
1294     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1295       return true;
1296 
1297     if (AM.Scale == 1 && AM.HasBaseReg)
1298       return true;
1299 
1300     return false;
1301 
1302   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1303     return isLegalMUBUFAddressingMode(AM);
1304   } else if (AS == AMDGPUAS::LOCAL_ADDRESS ||
1305              AS == AMDGPUAS::REGION_ADDRESS) {
1306     // Basic, single offset DS instructions allow a 16-bit unsigned immediate
1307     // field.
1308     // XXX - If doing a 4-byte aligned 8-byte type access, we effectively have
1309     // an 8-bit dword offset but we don't know the alignment here.
1310     if (!isUInt<16>(AM.BaseOffs))
1311       return false;
1312 
1313     if (AM.Scale == 0) // r + i or just i, depending on HasBaseReg.
1314       return true;
1315 
1316     if (AM.Scale == 1 && AM.HasBaseReg)
1317       return true;
1318 
1319     return false;
1320   } else if (AS == AMDGPUAS::FLAT_ADDRESS ||
1321              AS == AMDGPUAS::UNKNOWN_ADDRESS_SPACE) {
1322     // For an unknown address space, this usually means that this is for some
1323     // reason being used for pure arithmetic, and not based on some addressing
1324     // computation. We don't have instructions that compute pointers with any
1325     // addressing modes, so treat them as having no offset like flat
1326     // instructions.
1327     return isLegalFlatAddressingMode(AM);
1328   }
1329 
1330   // Assume a user alias of global for unknown address spaces.
1331   return isLegalGlobalAddressingMode(AM);
1332 }
1333 
1334 bool SITargetLowering::canMergeStoresTo(unsigned AS, EVT MemVT,
1335                                         const SelectionDAG &DAG) const {
1336   if (AS == AMDGPUAS::GLOBAL_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS) {
1337     return (MemVT.getSizeInBits() <= 4 * 32);
1338   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
1339     unsigned MaxPrivateBits = 8 * getSubtarget()->getMaxPrivateElementSize();
1340     return (MemVT.getSizeInBits() <= MaxPrivateBits);
1341   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
1342     return (MemVT.getSizeInBits() <= 2 * 32);
1343   }
1344   return true;
1345 }
1346 
1347 bool SITargetLowering::allowsMisalignedMemoryAccessesImpl(
1348     unsigned Size, unsigned AddrSpace, unsigned Align,
1349     MachineMemOperand::Flags Flags, bool *IsFast) const {
1350   if (IsFast)
1351     *IsFast = false;
1352 
1353   if (AddrSpace == AMDGPUAS::LOCAL_ADDRESS ||
1354       AddrSpace == AMDGPUAS::REGION_ADDRESS) {
1355     // ds_read/write_b64 require 8-byte alignment, but we can do a 4 byte
1356     // aligned, 8 byte access in a single operation using ds_read2/write2_b32
1357     // with adjacent offsets.
1358     bool AlignedBy4 = (Align % 4 == 0);
1359     if (IsFast)
1360       *IsFast = AlignedBy4;
1361 
1362     return AlignedBy4;
1363   }
1364 
1365   // FIXME: We have to be conservative here and assume that flat operations
1366   // will access scratch.  If we had access to the IR function, then we
1367   // could determine if any private memory was used in the function.
1368   if (!Subtarget->hasUnalignedScratchAccess() &&
1369       (AddrSpace == AMDGPUAS::PRIVATE_ADDRESS ||
1370        AddrSpace == AMDGPUAS::FLAT_ADDRESS)) {
1371     bool AlignedBy4 = Align >= 4;
1372     if (IsFast)
1373       *IsFast = AlignedBy4;
1374 
1375     return AlignedBy4;
1376   }
1377 
1378   if (Subtarget->hasUnalignedBufferAccess()) {
1379     // If we have an uniform constant load, it still requires using a slow
1380     // buffer instruction if unaligned.
1381     if (IsFast) {
1382       // Accesses can really be issued as 1-byte aligned or 4-byte aligned, so
1383       // 2-byte alignment is worse than 1 unless doing a 2-byte accesss.
1384       *IsFast = (AddrSpace == AMDGPUAS::CONSTANT_ADDRESS ||
1385                  AddrSpace == AMDGPUAS::CONSTANT_ADDRESS_32BIT) ?
1386         Align >= 4 : Align != 2;
1387     }
1388 
1389     return true;
1390   }
1391 
1392   // Smaller than dword value must be aligned.
1393   if (Size < 32)
1394     return false;
1395 
1396   // 8.1.6 - For Dword or larger reads or writes, the two LSBs of the
1397   // byte-address are ignored, thus forcing Dword alignment.
1398   // This applies to private, global, and constant memory.
1399   if (IsFast)
1400     *IsFast = true;
1401 
1402   return Size >= 32 && Align >= 4;
1403 }
1404 
1405 bool SITargetLowering::allowsMisalignedMemoryAccesses(
1406     EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
1407     bool *IsFast) const {
1408   if (IsFast)
1409     *IsFast = false;
1410 
1411   // TODO: I think v3i32 should allow unaligned accesses on CI with DS_READ_B96,
1412   // which isn't a simple VT.
1413   // Until MVT is extended to handle this, simply check for the size and
1414   // rely on the condition below: allow accesses if the size is a multiple of 4.
1415   if (VT == MVT::Other || (VT != MVT::Other && VT.getSizeInBits() > 1024 &&
1416                            VT.getStoreSize() > 16)) {
1417     return false;
1418   }
1419 
1420   return allowsMisalignedMemoryAccessesImpl(VT.getSizeInBits(), AddrSpace,
1421                                             Align, Flags, IsFast);
1422 }
1423 
1424 EVT SITargetLowering::getOptimalMemOpType(
1425     const MemOp &Op, const AttributeList &FuncAttributes) const {
1426   // FIXME: Should account for address space here.
1427 
1428   // The default fallback uses the private pointer size as a guess for a type to
1429   // use. Make sure we switch these to 64-bit accesses.
1430 
1431   if (Op.size() >= 16 &&
1432       Op.isDstAligned(Align(4))) // XXX: Should only do for global
1433     return MVT::v4i32;
1434 
1435   if (Op.size() >= 8 && Op.isDstAligned(Align(4)))
1436     return MVT::v2i32;
1437 
1438   // Use the default.
1439   return MVT::Other;
1440 }
1441 
1442 bool SITargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1443                                            unsigned DestAS) const {
1444   return isFlatGlobalAddrSpace(SrcAS) && isFlatGlobalAddrSpace(DestAS);
1445 }
1446 
1447 bool SITargetLowering::isMemOpHasNoClobberedMemOperand(const SDNode *N) const {
1448   const MemSDNode *MemNode = cast<MemSDNode>(N);
1449   const Value *Ptr = MemNode->getMemOperand()->getValue();
1450   const Instruction *I = dyn_cast_or_null<Instruction>(Ptr);
1451   return I && I->getMetadata("amdgpu.noclobber");
1452 }
1453 
1454 bool SITargetLowering::isFreeAddrSpaceCast(unsigned SrcAS,
1455                                            unsigned DestAS) const {
1456   // Flat -> private/local is a simple truncate.
1457   // Flat -> global is no-op
1458   if (SrcAS == AMDGPUAS::FLAT_ADDRESS)
1459     return true;
1460 
1461   return isNoopAddrSpaceCast(SrcAS, DestAS);
1462 }
1463 
1464 bool SITargetLowering::isMemOpUniform(const SDNode *N) const {
1465   const MemSDNode *MemNode = cast<MemSDNode>(N);
1466 
1467   return AMDGPUInstrInfo::isUniformMMO(MemNode->getMemOperand());
1468 }
1469 
1470 TargetLoweringBase::LegalizeTypeAction
1471 SITargetLowering::getPreferredVectorAction(MVT VT) const {
1472   int NumElts = VT.getVectorNumElements();
1473   if (NumElts != 1 && VT.getScalarType().bitsLE(MVT::i16))
1474     return VT.isPow2VectorType() ? TypeSplitVector : TypeWidenVector;
1475   return TargetLoweringBase::getPreferredVectorAction(VT);
1476 }
1477 
1478 bool SITargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
1479                                                          Type *Ty) const {
1480   // FIXME: Could be smarter if called for vector constants.
1481   return true;
1482 }
1483 
1484 bool SITargetLowering::isTypeDesirableForOp(unsigned Op, EVT VT) const {
1485   if (Subtarget->has16BitInsts() && VT == MVT::i16) {
1486     switch (Op) {
1487     case ISD::LOAD:
1488     case ISD::STORE:
1489 
1490     // These operations are done with 32-bit instructions anyway.
1491     case ISD::AND:
1492     case ISD::OR:
1493     case ISD::XOR:
1494     case ISD::SELECT:
1495       // TODO: Extensions?
1496       return true;
1497     default:
1498       return false;
1499     }
1500   }
1501 
1502   // SimplifySetCC uses this function to determine whether or not it should
1503   // create setcc with i1 operands.  We don't have instructions for i1 setcc.
1504   if (VT == MVT::i1 && Op == ISD::SETCC)
1505     return false;
1506 
1507   return TargetLowering::isTypeDesirableForOp(Op, VT);
1508 }
1509 
1510 SDValue SITargetLowering::lowerKernArgParameterPtr(SelectionDAG &DAG,
1511                                                    const SDLoc &SL,
1512                                                    SDValue Chain,
1513                                                    uint64_t Offset) const {
1514   const DataLayout &DL = DAG.getDataLayout();
1515   MachineFunction &MF = DAG.getMachineFunction();
1516   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
1517 
1518   const ArgDescriptor *InputPtrReg;
1519   const TargetRegisterClass *RC;
1520 
1521   std::tie(InputPtrReg, RC)
1522     = Info->getPreloadedValue(AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
1523 
1524   MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
1525   MVT PtrVT = getPointerTy(DL, AMDGPUAS::CONSTANT_ADDRESS);
1526   SDValue BasePtr = DAG.getCopyFromReg(Chain, SL,
1527     MRI.getLiveInVirtReg(InputPtrReg->getRegister()), PtrVT);
1528 
1529   return DAG.getObjectPtrOffset(SL, BasePtr, Offset);
1530 }
1531 
1532 SDValue SITargetLowering::getImplicitArgPtr(SelectionDAG &DAG,
1533                                             const SDLoc &SL) const {
1534   uint64_t Offset = getImplicitParameterOffset(DAG.getMachineFunction(),
1535                                                FIRST_IMPLICIT);
1536   return lowerKernArgParameterPtr(DAG, SL, DAG.getEntryNode(), Offset);
1537 }
1538 
1539 SDValue SITargetLowering::convertArgType(SelectionDAG &DAG, EVT VT, EVT MemVT,
1540                                          const SDLoc &SL, SDValue Val,
1541                                          bool Signed,
1542                                          const ISD::InputArg *Arg) const {
1543   // First, if it is a widened vector, narrow it.
1544   if (VT.isVector() &&
1545       VT.getVectorNumElements() != MemVT.getVectorNumElements()) {
1546     EVT NarrowedVT =
1547         EVT::getVectorVT(*DAG.getContext(), MemVT.getVectorElementType(),
1548                          VT.getVectorNumElements());
1549     Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL, NarrowedVT, Val,
1550                       DAG.getConstant(0, SL, MVT::i32));
1551   }
1552 
1553   // Then convert the vector elements or scalar value.
1554   if (Arg && (Arg->Flags.isSExt() || Arg->Flags.isZExt()) &&
1555       VT.bitsLT(MemVT)) {
1556     unsigned Opc = Arg->Flags.isZExt() ? ISD::AssertZext : ISD::AssertSext;
1557     Val = DAG.getNode(Opc, SL, MemVT, Val, DAG.getValueType(VT));
1558   }
1559 
1560   if (MemVT.isFloatingPoint())
1561     Val = getFPExtOrFPRound(DAG, Val, SL, VT);
1562   else if (Signed)
1563     Val = DAG.getSExtOrTrunc(Val, SL, VT);
1564   else
1565     Val = DAG.getZExtOrTrunc(Val, SL, VT);
1566 
1567   return Val;
1568 }
1569 
1570 SDValue SITargetLowering::lowerKernargMemParameter(
1571   SelectionDAG &DAG, EVT VT, EVT MemVT,
1572   const SDLoc &SL, SDValue Chain,
1573   uint64_t Offset, unsigned Align, bool Signed,
1574   const ISD::InputArg *Arg) const {
1575   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
1576 
1577   // Try to avoid using an extload by loading earlier than the argument address,
1578   // and extracting the relevant bits. The load should hopefully be merged with
1579   // the previous argument.
1580   if (MemVT.getStoreSize() < 4 && Align < 4) {
1581     // TODO: Handle align < 4 and size >= 4 (can happen with packed structs).
1582     int64_t AlignDownOffset = alignDown(Offset, 4);
1583     int64_t OffsetDiff = Offset - AlignDownOffset;
1584 
1585     EVT IntVT = MemVT.changeTypeToInteger();
1586 
1587     // TODO: If we passed in the base kernel offset we could have a better
1588     // alignment than 4, but we don't really need it.
1589     SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, AlignDownOffset);
1590     SDValue Load = DAG.getLoad(MVT::i32, SL, Chain, Ptr, PtrInfo, 4,
1591                                MachineMemOperand::MODereferenceable |
1592                                MachineMemOperand::MOInvariant);
1593 
1594     SDValue ShiftAmt = DAG.getConstant(OffsetDiff * 8, SL, MVT::i32);
1595     SDValue Extract = DAG.getNode(ISD::SRL, SL, MVT::i32, Load, ShiftAmt);
1596 
1597     SDValue ArgVal = DAG.getNode(ISD::TRUNCATE, SL, IntVT, Extract);
1598     ArgVal = DAG.getNode(ISD::BITCAST, SL, MemVT, ArgVal);
1599     ArgVal = convertArgType(DAG, VT, MemVT, SL, ArgVal, Signed, Arg);
1600 
1601 
1602     return DAG.getMergeValues({ ArgVal, Load.getValue(1) }, SL);
1603   }
1604 
1605   SDValue Ptr = lowerKernArgParameterPtr(DAG, SL, Chain, Offset);
1606   SDValue Load = DAG.getLoad(MemVT, SL, Chain, Ptr, PtrInfo, Align,
1607                              MachineMemOperand::MODereferenceable |
1608                              MachineMemOperand::MOInvariant);
1609 
1610   SDValue Val = convertArgType(DAG, VT, MemVT, SL, Load, Signed, Arg);
1611   return DAG.getMergeValues({ Val, Load.getValue(1) }, SL);
1612 }
1613 
1614 SDValue SITargetLowering::lowerStackParameter(SelectionDAG &DAG, CCValAssign &VA,
1615                                               const SDLoc &SL, SDValue Chain,
1616                                               const ISD::InputArg &Arg) const {
1617   MachineFunction &MF = DAG.getMachineFunction();
1618   MachineFrameInfo &MFI = MF.getFrameInfo();
1619 
1620   if (Arg.Flags.isByVal()) {
1621     unsigned Size = Arg.Flags.getByValSize();
1622     int FrameIdx = MFI.CreateFixedObject(Size, VA.getLocMemOffset(), false);
1623     return DAG.getFrameIndex(FrameIdx, MVT::i32);
1624   }
1625 
1626   unsigned ArgOffset = VA.getLocMemOffset();
1627   unsigned ArgSize = VA.getValVT().getStoreSize();
1628 
1629   int FI = MFI.CreateFixedObject(ArgSize, ArgOffset, true);
1630 
1631   // Create load nodes to retrieve arguments from the stack.
1632   SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
1633   SDValue ArgValue;
1634 
1635   // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
1636   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
1637   MVT MemVT = VA.getValVT();
1638 
1639   switch (VA.getLocInfo()) {
1640   default:
1641     break;
1642   case CCValAssign::BCvt:
1643     MemVT = VA.getLocVT();
1644     break;
1645   case CCValAssign::SExt:
1646     ExtType = ISD::SEXTLOAD;
1647     break;
1648   case CCValAssign::ZExt:
1649     ExtType = ISD::ZEXTLOAD;
1650     break;
1651   case CCValAssign::AExt:
1652     ExtType = ISD::EXTLOAD;
1653     break;
1654   }
1655 
1656   ArgValue = DAG.getExtLoad(
1657     ExtType, SL, VA.getLocVT(), Chain, FIN,
1658     MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
1659     MemVT);
1660   return ArgValue;
1661 }
1662 
1663 SDValue SITargetLowering::getPreloadedValue(SelectionDAG &DAG,
1664   const SIMachineFunctionInfo &MFI,
1665   EVT VT,
1666   AMDGPUFunctionArgInfo::PreloadedValue PVID) const {
1667   const ArgDescriptor *Reg;
1668   const TargetRegisterClass *RC;
1669 
1670   std::tie(Reg, RC) = MFI.getPreloadedValue(PVID);
1671   return CreateLiveInRegister(DAG, RC, Reg->getRegister(), VT);
1672 }
1673 
1674 static void processShaderInputArgs(SmallVectorImpl<ISD::InputArg> &Splits,
1675                                    CallingConv::ID CallConv,
1676                                    ArrayRef<ISD::InputArg> Ins,
1677                                    BitVector &Skipped,
1678                                    FunctionType *FType,
1679                                    SIMachineFunctionInfo *Info) {
1680   for (unsigned I = 0, E = Ins.size(), PSInputNum = 0; I != E; ++I) {
1681     const ISD::InputArg *Arg = &Ins[I];
1682 
1683     assert((!Arg->VT.isVector() || Arg->VT.getScalarSizeInBits() == 16) &&
1684            "vector type argument should have been split");
1685 
1686     // First check if it's a PS input addr.
1687     if (CallConv == CallingConv::AMDGPU_PS &&
1688         !Arg->Flags.isInReg() && PSInputNum <= 15) {
1689       bool SkipArg = !Arg->Used && !Info->isPSInputAllocated(PSInputNum);
1690 
1691       // Inconveniently only the first part of the split is marked as isSplit,
1692       // so skip to the end. We only want to increment PSInputNum once for the
1693       // entire split argument.
1694       if (Arg->Flags.isSplit()) {
1695         while (!Arg->Flags.isSplitEnd()) {
1696           assert((!Arg->VT.isVector() ||
1697                   Arg->VT.getScalarSizeInBits() == 16) &&
1698                  "unexpected vector split in ps argument type");
1699           if (!SkipArg)
1700             Splits.push_back(*Arg);
1701           Arg = &Ins[++I];
1702         }
1703       }
1704 
1705       if (SkipArg) {
1706         // We can safely skip PS inputs.
1707         Skipped.set(Arg->getOrigArgIndex());
1708         ++PSInputNum;
1709         continue;
1710       }
1711 
1712       Info->markPSInputAllocated(PSInputNum);
1713       if (Arg->Used)
1714         Info->markPSInputEnabled(PSInputNum);
1715 
1716       ++PSInputNum;
1717     }
1718 
1719     Splits.push_back(*Arg);
1720   }
1721 }
1722 
1723 // Allocate special inputs passed in VGPRs.
1724 void SITargetLowering::allocateSpecialEntryInputVGPRs(CCState &CCInfo,
1725                                                       MachineFunction &MF,
1726                                                       const SIRegisterInfo &TRI,
1727                                                       SIMachineFunctionInfo &Info) const {
1728   const LLT S32 = LLT::scalar(32);
1729   MachineRegisterInfo &MRI = MF.getRegInfo();
1730 
1731   if (Info.hasWorkItemIDX()) {
1732     Register Reg = AMDGPU::VGPR0;
1733     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1734 
1735     CCInfo.AllocateReg(Reg);
1736     Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg));
1737   }
1738 
1739   if (Info.hasWorkItemIDY()) {
1740     Register Reg = AMDGPU::VGPR1;
1741     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1742 
1743     CCInfo.AllocateReg(Reg);
1744     Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg));
1745   }
1746 
1747   if (Info.hasWorkItemIDZ()) {
1748     Register Reg = AMDGPU::VGPR2;
1749     MRI.setType(MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass), S32);
1750 
1751     CCInfo.AllocateReg(Reg);
1752     Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg));
1753   }
1754 }
1755 
1756 // Try to allocate a VGPR at the end of the argument list, or if no argument
1757 // VGPRs are left allocating a stack slot.
1758 // If \p Mask is is given it indicates bitfield position in the register.
1759 // If \p Arg is given use it with new ]p Mask instead of allocating new.
1760 static ArgDescriptor allocateVGPR32Input(CCState &CCInfo, unsigned Mask = ~0u,
1761                                          ArgDescriptor Arg = ArgDescriptor()) {
1762   if (Arg.isSet())
1763     return ArgDescriptor::createArg(Arg, Mask);
1764 
1765   ArrayRef<MCPhysReg> ArgVGPRs
1766     = makeArrayRef(AMDGPU::VGPR_32RegClass.begin(), 32);
1767   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgVGPRs);
1768   if (RegIdx == ArgVGPRs.size()) {
1769     // Spill to stack required.
1770     int64_t Offset = CCInfo.AllocateStack(4, Align(4));
1771 
1772     return ArgDescriptor::createStack(Offset, Mask);
1773   }
1774 
1775   unsigned Reg = ArgVGPRs[RegIdx];
1776   Reg = CCInfo.AllocateReg(Reg);
1777   assert(Reg != AMDGPU::NoRegister);
1778 
1779   MachineFunction &MF = CCInfo.getMachineFunction();
1780   Register LiveInVReg = MF.addLiveIn(Reg, &AMDGPU::VGPR_32RegClass);
1781   MF.getRegInfo().setType(LiveInVReg, LLT::scalar(32));
1782   return ArgDescriptor::createRegister(Reg, Mask);
1783 }
1784 
1785 static ArgDescriptor allocateSGPR32InputImpl(CCState &CCInfo,
1786                                              const TargetRegisterClass *RC,
1787                                              unsigned NumArgRegs) {
1788   ArrayRef<MCPhysReg> ArgSGPRs = makeArrayRef(RC->begin(), 32);
1789   unsigned RegIdx = CCInfo.getFirstUnallocated(ArgSGPRs);
1790   if (RegIdx == ArgSGPRs.size())
1791     report_fatal_error("ran out of SGPRs for arguments");
1792 
1793   unsigned Reg = ArgSGPRs[RegIdx];
1794   Reg = CCInfo.AllocateReg(Reg);
1795   assert(Reg != AMDGPU::NoRegister);
1796 
1797   MachineFunction &MF = CCInfo.getMachineFunction();
1798   MF.addLiveIn(Reg, RC);
1799   return ArgDescriptor::createRegister(Reg);
1800 }
1801 
1802 static ArgDescriptor allocateSGPR32Input(CCState &CCInfo) {
1803   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_32RegClass, 32);
1804 }
1805 
1806 static ArgDescriptor allocateSGPR64Input(CCState &CCInfo) {
1807   return allocateSGPR32InputImpl(CCInfo, &AMDGPU::SGPR_64RegClass, 16);
1808 }
1809 
1810 /// Allocate implicit function VGPR arguments at the end of allocated user
1811 /// arguments.
1812 void SITargetLowering::allocateSpecialInputVGPRs(
1813   CCState &CCInfo, MachineFunction &MF,
1814   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1815   const unsigned Mask = 0x3ff;
1816   ArgDescriptor Arg;
1817 
1818   if (Info.hasWorkItemIDX()) {
1819     Arg = allocateVGPR32Input(CCInfo, Mask);
1820     Info.setWorkItemIDX(Arg);
1821   }
1822 
1823   if (Info.hasWorkItemIDY()) {
1824     Arg = allocateVGPR32Input(CCInfo, Mask << 10, Arg);
1825     Info.setWorkItemIDY(Arg);
1826   }
1827 
1828   if (Info.hasWorkItemIDZ())
1829     Info.setWorkItemIDZ(allocateVGPR32Input(CCInfo, Mask << 20, Arg));
1830 }
1831 
1832 /// Allocate implicit function VGPR arguments in fixed registers.
1833 void SITargetLowering::allocateSpecialInputVGPRsFixed(
1834   CCState &CCInfo, MachineFunction &MF,
1835   const SIRegisterInfo &TRI, SIMachineFunctionInfo &Info) const {
1836   Register Reg = CCInfo.AllocateReg(AMDGPU::VGPR31);
1837   if (!Reg)
1838     report_fatal_error("failed to allocated VGPR for implicit arguments");
1839 
1840   const unsigned Mask = 0x3ff;
1841   Info.setWorkItemIDX(ArgDescriptor::createRegister(Reg, Mask));
1842   Info.setWorkItemIDY(ArgDescriptor::createRegister(Reg, Mask << 10));
1843   Info.setWorkItemIDZ(ArgDescriptor::createRegister(Reg, Mask << 20));
1844 }
1845 
1846 void SITargetLowering::allocateSpecialInputSGPRs(
1847   CCState &CCInfo,
1848   MachineFunction &MF,
1849   const SIRegisterInfo &TRI,
1850   SIMachineFunctionInfo &Info) const {
1851   auto &ArgInfo = Info.getArgInfo();
1852 
1853   // TODO: Unify handling with private memory pointers.
1854 
1855   if (Info.hasDispatchPtr())
1856     ArgInfo.DispatchPtr = allocateSGPR64Input(CCInfo);
1857 
1858   if (Info.hasQueuePtr())
1859     ArgInfo.QueuePtr = allocateSGPR64Input(CCInfo);
1860 
1861   // Implicit arg ptr takes the place of the kernarg segment pointer. This is a
1862   // constant offset from the kernarg segment.
1863   if (Info.hasImplicitArgPtr())
1864     ArgInfo.ImplicitArgPtr = allocateSGPR64Input(CCInfo);
1865 
1866   if (Info.hasDispatchID())
1867     ArgInfo.DispatchID = allocateSGPR64Input(CCInfo);
1868 
1869   // flat_scratch_init is not applicable for non-kernel functions.
1870 
1871   if (Info.hasWorkGroupIDX())
1872     ArgInfo.WorkGroupIDX = allocateSGPR32Input(CCInfo);
1873 
1874   if (Info.hasWorkGroupIDY())
1875     ArgInfo.WorkGroupIDY = allocateSGPR32Input(CCInfo);
1876 
1877   if (Info.hasWorkGroupIDZ())
1878     ArgInfo.WorkGroupIDZ = allocateSGPR32Input(CCInfo);
1879 }
1880 
1881 // Allocate special inputs passed in user SGPRs.
1882 void SITargetLowering::allocateHSAUserSGPRs(CCState &CCInfo,
1883                                             MachineFunction &MF,
1884                                             const SIRegisterInfo &TRI,
1885                                             SIMachineFunctionInfo &Info) const {
1886   if (Info.hasImplicitBufferPtr()) {
1887     unsigned ImplicitBufferPtrReg = Info.addImplicitBufferPtr(TRI);
1888     MF.addLiveIn(ImplicitBufferPtrReg, &AMDGPU::SGPR_64RegClass);
1889     CCInfo.AllocateReg(ImplicitBufferPtrReg);
1890   }
1891 
1892   // FIXME: How should these inputs interact with inreg / custom SGPR inputs?
1893   if (Info.hasPrivateSegmentBuffer()) {
1894     unsigned PrivateSegmentBufferReg = Info.addPrivateSegmentBuffer(TRI);
1895     MF.addLiveIn(PrivateSegmentBufferReg, &AMDGPU::SGPR_128RegClass);
1896     CCInfo.AllocateReg(PrivateSegmentBufferReg);
1897   }
1898 
1899   if (Info.hasDispatchPtr()) {
1900     unsigned DispatchPtrReg = Info.addDispatchPtr(TRI);
1901     MF.addLiveIn(DispatchPtrReg, &AMDGPU::SGPR_64RegClass);
1902     CCInfo.AllocateReg(DispatchPtrReg);
1903   }
1904 
1905   if (Info.hasQueuePtr()) {
1906     unsigned QueuePtrReg = Info.addQueuePtr(TRI);
1907     MF.addLiveIn(QueuePtrReg, &AMDGPU::SGPR_64RegClass);
1908     CCInfo.AllocateReg(QueuePtrReg);
1909   }
1910 
1911   if (Info.hasKernargSegmentPtr()) {
1912     MachineRegisterInfo &MRI = MF.getRegInfo();
1913     Register InputPtrReg = Info.addKernargSegmentPtr(TRI);
1914     CCInfo.AllocateReg(InputPtrReg);
1915 
1916     Register VReg = MF.addLiveIn(InputPtrReg, &AMDGPU::SGPR_64RegClass);
1917     MRI.setType(VReg, LLT::pointer(AMDGPUAS::CONSTANT_ADDRESS, 64));
1918   }
1919 
1920   if (Info.hasDispatchID()) {
1921     unsigned DispatchIDReg = Info.addDispatchID(TRI);
1922     MF.addLiveIn(DispatchIDReg, &AMDGPU::SGPR_64RegClass);
1923     CCInfo.AllocateReg(DispatchIDReg);
1924   }
1925 
1926   if (Info.hasFlatScratchInit()) {
1927     unsigned FlatScratchInitReg = Info.addFlatScratchInit(TRI);
1928     MF.addLiveIn(FlatScratchInitReg, &AMDGPU::SGPR_64RegClass);
1929     CCInfo.AllocateReg(FlatScratchInitReg);
1930   }
1931 
1932   // TODO: Add GridWorkGroupCount user SGPRs when used. For now with HSA we read
1933   // these from the dispatch pointer.
1934 }
1935 
1936 // Allocate special input registers that are initialized per-wave.
1937 void SITargetLowering::allocateSystemSGPRs(CCState &CCInfo,
1938                                            MachineFunction &MF,
1939                                            SIMachineFunctionInfo &Info,
1940                                            CallingConv::ID CallConv,
1941                                            bool IsShader) const {
1942   if (Info.hasWorkGroupIDX()) {
1943     unsigned Reg = Info.addWorkGroupIDX();
1944     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1945     CCInfo.AllocateReg(Reg);
1946   }
1947 
1948   if (Info.hasWorkGroupIDY()) {
1949     unsigned Reg = Info.addWorkGroupIDY();
1950     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1951     CCInfo.AllocateReg(Reg);
1952   }
1953 
1954   if (Info.hasWorkGroupIDZ()) {
1955     unsigned Reg = Info.addWorkGroupIDZ();
1956     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1957     CCInfo.AllocateReg(Reg);
1958   }
1959 
1960   if (Info.hasWorkGroupInfo()) {
1961     unsigned Reg = Info.addWorkGroupInfo();
1962     MF.addLiveIn(Reg, &AMDGPU::SGPR_32RegClass);
1963     CCInfo.AllocateReg(Reg);
1964   }
1965 
1966   if (Info.hasPrivateSegmentWaveByteOffset()) {
1967     // Scratch wave offset passed in system SGPR.
1968     unsigned PrivateSegmentWaveByteOffsetReg;
1969 
1970     if (IsShader) {
1971       PrivateSegmentWaveByteOffsetReg =
1972         Info.getPrivateSegmentWaveByteOffsetSystemSGPR();
1973 
1974       // This is true if the scratch wave byte offset doesn't have a fixed
1975       // location.
1976       if (PrivateSegmentWaveByteOffsetReg == AMDGPU::NoRegister) {
1977         PrivateSegmentWaveByteOffsetReg = findFirstFreeSGPR(CCInfo);
1978         Info.setPrivateSegmentWaveByteOffset(PrivateSegmentWaveByteOffsetReg);
1979       }
1980     } else
1981       PrivateSegmentWaveByteOffsetReg = Info.addPrivateSegmentWaveByteOffset();
1982 
1983     MF.addLiveIn(PrivateSegmentWaveByteOffsetReg, &AMDGPU::SGPR_32RegClass);
1984     CCInfo.AllocateReg(PrivateSegmentWaveByteOffsetReg);
1985   }
1986 }
1987 
1988 static void reservePrivateMemoryRegs(const TargetMachine &TM,
1989                                      MachineFunction &MF,
1990                                      const SIRegisterInfo &TRI,
1991                                      SIMachineFunctionInfo &Info) {
1992   // Now that we've figured out where the scratch register inputs are, see if
1993   // should reserve the arguments and use them directly.
1994   MachineFrameInfo &MFI = MF.getFrameInfo();
1995   bool HasStackObjects = MFI.hasStackObjects();
1996   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
1997 
1998   // Record that we know we have non-spill stack objects so we don't need to
1999   // check all stack objects later.
2000   if (HasStackObjects)
2001     Info.setHasNonSpillStackObjects(true);
2002 
2003   // Everything live out of a block is spilled with fast regalloc, so it's
2004   // almost certain that spilling will be required.
2005   if (TM.getOptLevel() == CodeGenOpt::None)
2006     HasStackObjects = true;
2007 
2008   // For now assume stack access is needed in any callee functions, so we need
2009   // the scratch registers to pass in.
2010   bool RequiresStackAccess = HasStackObjects || MFI.hasCalls();
2011 
2012   if (RequiresStackAccess && ST.isAmdHsaOrMesa(MF.getFunction())) {
2013     // If we have stack objects, we unquestionably need the private buffer
2014     // resource. For the Code Object V2 ABI, this will be the first 4 user
2015     // SGPR inputs. We can reserve those and use them directly.
2016 
2017     Register PrivateSegmentBufferReg =
2018         Info.getPreloadedReg(AMDGPUFunctionArgInfo::PRIVATE_SEGMENT_BUFFER);
2019     Info.setScratchRSrcReg(PrivateSegmentBufferReg);
2020   } else {
2021     unsigned ReservedBufferReg = TRI.reservedPrivateSegmentBufferReg(MF);
2022     // We tentatively reserve the last registers (skipping the last registers
2023     // which may contain VCC, FLAT_SCR, and XNACK). After register allocation,
2024     // we'll replace these with the ones immediately after those which were
2025     // really allocated. In the prologue copies will be inserted from the
2026     // argument to these reserved registers.
2027 
2028     // Without HSA, relocations are used for the scratch pointer and the
2029     // buffer resource setup is always inserted in the prologue. Scratch wave
2030     // offset is still in an input SGPR.
2031     Info.setScratchRSrcReg(ReservedBufferReg);
2032   }
2033 
2034   MachineRegisterInfo &MRI = MF.getRegInfo();
2035 
2036   // For entry functions we have to set up the stack pointer if we use it,
2037   // whereas non-entry functions get this "for free". This means there is no
2038   // intrinsic advantage to using S32 over S34 in cases where we do not have
2039   // calls but do need a frame pointer (i.e. if we are requested to have one
2040   // because frame pointer elimination is disabled). To keep things simple we
2041   // only ever use S32 as the call ABI stack pointer, and so using it does not
2042   // imply we need a separate frame pointer.
2043   //
2044   // Try to use s32 as the SP, but move it if it would interfere with input
2045   // arguments. This won't work with calls though.
2046   //
2047   // FIXME: Move SP to avoid any possible inputs, or find a way to spill input
2048   // registers.
2049   if (!MRI.isLiveIn(AMDGPU::SGPR32)) {
2050     Info.setStackPtrOffsetReg(AMDGPU::SGPR32);
2051   } else {
2052     assert(AMDGPU::isShader(MF.getFunction().getCallingConv()));
2053 
2054     if (MFI.hasCalls())
2055       report_fatal_error("call in graphics shader with too many input SGPRs");
2056 
2057     for (unsigned Reg : AMDGPU::SGPR_32RegClass) {
2058       if (!MRI.isLiveIn(Reg)) {
2059         Info.setStackPtrOffsetReg(Reg);
2060         break;
2061       }
2062     }
2063 
2064     if (Info.getStackPtrOffsetReg() == AMDGPU::SP_REG)
2065       report_fatal_error("failed to find register for SP");
2066   }
2067 
2068   // hasFP should be accurate for entry functions even before the frame is
2069   // finalized, because it does not rely on the known stack size, only
2070   // properties like whether variable sized objects are present.
2071   if (ST.getFrameLowering()->hasFP(MF)) {
2072     Info.setFrameOffsetReg(AMDGPU::SGPR33);
2073   }
2074 }
2075 
2076 bool SITargetLowering::supportSplitCSR(MachineFunction *MF) const {
2077   const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
2078   return !Info->isEntryFunction();
2079 }
2080 
2081 void SITargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
2082 
2083 }
2084 
2085 void SITargetLowering::insertCopiesSplitCSR(
2086   MachineBasicBlock *Entry,
2087   const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
2088   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2089 
2090   const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
2091   if (!IStart)
2092     return;
2093 
2094   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
2095   MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
2096   MachineBasicBlock::iterator MBBI = Entry->begin();
2097   for (const MCPhysReg *I = IStart; *I; ++I) {
2098     const TargetRegisterClass *RC = nullptr;
2099     if (AMDGPU::SReg_64RegClass.contains(*I))
2100       RC = &AMDGPU::SGPR_64RegClass;
2101     else if (AMDGPU::SReg_32RegClass.contains(*I))
2102       RC = &AMDGPU::SGPR_32RegClass;
2103     else
2104       llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2105 
2106     Register NewVR = MRI->createVirtualRegister(RC);
2107     // Create copy from CSR to a virtual register.
2108     Entry->addLiveIn(*I);
2109     BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
2110       .addReg(*I);
2111 
2112     // Insert the copy-back instructions right before the terminator.
2113     for (auto *Exit : Exits)
2114       BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
2115               TII->get(TargetOpcode::COPY), *I)
2116         .addReg(NewVR);
2117   }
2118 }
2119 
2120 SDValue SITargetLowering::LowerFormalArguments(
2121     SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
2122     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2123     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
2124   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2125 
2126   MachineFunction &MF = DAG.getMachineFunction();
2127   const Function &Fn = MF.getFunction();
2128   FunctionType *FType = MF.getFunction().getFunctionType();
2129   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2130 
2131   if (Subtarget->isAmdHsaOS() && AMDGPU::isShader(CallConv)) {
2132     DiagnosticInfoUnsupported NoGraphicsHSA(
2133         Fn, "unsupported non-compute shaders with HSA", DL.getDebugLoc());
2134     DAG.getContext()->diagnose(NoGraphicsHSA);
2135     return DAG.getEntryNode();
2136   }
2137 
2138   SmallVector<ISD::InputArg, 16> Splits;
2139   SmallVector<CCValAssign, 16> ArgLocs;
2140   BitVector Skipped(Ins.size());
2141   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
2142                  *DAG.getContext());
2143 
2144   bool IsShader = AMDGPU::isShader(CallConv);
2145   bool IsKernel = AMDGPU::isKernel(CallConv);
2146   bool IsEntryFunc = AMDGPU::isEntryFunctionCC(CallConv);
2147 
2148   if (IsShader) {
2149     processShaderInputArgs(Splits, CallConv, Ins, Skipped, FType, Info);
2150 
2151     // At least one interpolation mode must be enabled or else the GPU will
2152     // hang.
2153     //
2154     // Check PSInputAddr instead of PSInputEnable. The idea is that if the user
2155     // set PSInputAddr, the user wants to enable some bits after the compilation
2156     // based on run-time states. Since we can't know what the final PSInputEna
2157     // will look like, so we shouldn't do anything here and the user should take
2158     // responsibility for the correct programming.
2159     //
2160     // Otherwise, the following restrictions apply:
2161     // - At least one of PERSP_* (0xF) or LINEAR_* (0x70) must be enabled.
2162     // - If POS_W_FLOAT (11) is enabled, at least one of PERSP_* must be
2163     //   enabled too.
2164     if (CallConv == CallingConv::AMDGPU_PS) {
2165       if ((Info->getPSInputAddr() & 0x7F) == 0 ||
2166            ((Info->getPSInputAddr() & 0xF) == 0 &&
2167             Info->isPSInputAllocated(11))) {
2168         CCInfo.AllocateReg(AMDGPU::VGPR0);
2169         CCInfo.AllocateReg(AMDGPU::VGPR1);
2170         Info->markPSInputAllocated(0);
2171         Info->markPSInputEnabled(0);
2172       }
2173       if (Subtarget->isAmdPalOS()) {
2174         // For isAmdPalOS, the user does not enable some bits after compilation
2175         // based on run-time states; the register values being generated here are
2176         // the final ones set in hardware. Therefore we need to apply the
2177         // workaround to PSInputAddr and PSInputEnable together.  (The case where
2178         // a bit is set in PSInputAddr but not PSInputEnable is where the
2179         // frontend set up an input arg for a particular interpolation mode, but
2180         // nothing uses that input arg. Really we should have an earlier pass
2181         // that removes such an arg.)
2182         unsigned PsInputBits = Info->getPSInputAddr() & Info->getPSInputEnable();
2183         if ((PsInputBits & 0x7F) == 0 ||
2184             ((PsInputBits & 0xF) == 0 &&
2185              (PsInputBits >> 11 & 1)))
2186           Info->markPSInputEnabled(
2187               countTrailingZeros(Info->getPSInputAddr(), ZB_Undefined));
2188       }
2189     }
2190 
2191     assert(!Info->hasDispatchPtr() &&
2192            !Info->hasKernargSegmentPtr() && !Info->hasFlatScratchInit() &&
2193            !Info->hasWorkGroupIDX() && !Info->hasWorkGroupIDY() &&
2194            !Info->hasWorkGroupIDZ() && !Info->hasWorkGroupInfo() &&
2195            !Info->hasWorkItemIDX() && !Info->hasWorkItemIDY() &&
2196            !Info->hasWorkItemIDZ());
2197   } else if (IsKernel) {
2198     assert(Info->hasWorkGroupIDX() && Info->hasWorkItemIDX());
2199   } else {
2200     Splits.append(Ins.begin(), Ins.end());
2201   }
2202 
2203   if (IsEntryFunc) {
2204     allocateSpecialEntryInputVGPRs(CCInfo, MF, *TRI, *Info);
2205     allocateHSAUserSGPRs(CCInfo, MF, *TRI, *Info);
2206   } else {
2207     // For the fixed ABI, pass workitem IDs in the last argument register.
2208     if (AMDGPUTargetMachine::EnableFixedFunctionABI)
2209       allocateSpecialInputVGPRsFixed(CCInfo, MF, *TRI, *Info);
2210   }
2211 
2212   if (IsKernel) {
2213     analyzeFormalArgumentsCompute(CCInfo, Ins);
2214   } else {
2215     CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, isVarArg);
2216     CCInfo.AnalyzeFormalArguments(Splits, AssignFn);
2217   }
2218 
2219   SmallVector<SDValue, 16> Chains;
2220 
2221   // FIXME: This is the minimum kernel argument alignment. We should improve
2222   // this to the maximum alignment of the arguments.
2223   //
2224   // FIXME: Alignment of explicit arguments totally broken with non-0 explicit
2225   // kern arg offset.
2226   const unsigned KernelArgBaseAlign = 16;
2227 
2228    for (unsigned i = 0, e = Ins.size(), ArgIdx = 0; i != e; ++i) {
2229     const ISD::InputArg &Arg = Ins[i];
2230     if (Arg.isOrigArg() && Skipped[Arg.getOrigArgIndex()]) {
2231       InVals.push_back(DAG.getUNDEF(Arg.VT));
2232       continue;
2233     }
2234 
2235     CCValAssign &VA = ArgLocs[ArgIdx++];
2236     MVT VT = VA.getLocVT();
2237 
2238     if (IsEntryFunc && VA.isMemLoc()) {
2239       VT = Ins[i].VT;
2240       EVT MemVT = VA.getLocVT();
2241 
2242       const uint64_t Offset = VA.getLocMemOffset();
2243       unsigned Align = MinAlign(KernelArgBaseAlign, Offset);
2244 
2245       SDValue Arg = lowerKernargMemParameter(
2246         DAG, VT, MemVT, DL, Chain, Offset, Align, Ins[i].Flags.isSExt(), &Ins[i]);
2247       Chains.push_back(Arg.getValue(1));
2248 
2249       auto *ParamTy =
2250         dyn_cast<PointerType>(FType->getParamType(Ins[i].getOrigArgIndex()));
2251       if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
2252           ParamTy && (ParamTy->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS ||
2253                       ParamTy->getAddressSpace() == AMDGPUAS::REGION_ADDRESS)) {
2254         // On SI local pointers are just offsets into LDS, so they are always
2255         // less than 16-bits.  On CI and newer they could potentially be
2256         // real pointers, so we can't guarantee their size.
2257         Arg = DAG.getNode(ISD::AssertZext, DL, Arg.getValueType(), Arg,
2258                           DAG.getValueType(MVT::i16));
2259       }
2260 
2261       InVals.push_back(Arg);
2262       continue;
2263     } else if (!IsEntryFunc && VA.isMemLoc()) {
2264       SDValue Val = lowerStackParameter(DAG, VA, DL, Chain, Arg);
2265       InVals.push_back(Val);
2266       if (!Arg.Flags.isByVal())
2267         Chains.push_back(Val.getValue(1));
2268       continue;
2269     }
2270 
2271     assert(VA.isRegLoc() && "Parameter must be in a register!");
2272 
2273     Register Reg = VA.getLocReg();
2274     const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg, VT);
2275     EVT ValVT = VA.getValVT();
2276 
2277     Reg = MF.addLiveIn(Reg, RC);
2278     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, VT);
2279 
2280     if (Arg.Flags.isSRet()) {
2281       // The return object should be reasonably addressable.
2282 
2283       // FIXME: This helps when the return is a real sret. If it is a
2284       // automatically inserted sret (i.e. CanLowerReturn returns false), an
2285       // extra copy is inserted in SelectionDAGBuilder which obscures this.
2286       unsigned NumBits
2287         = 32 - getSubtarget()->getKnownHighZeroBitsForFrameIndex();
2288       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2289         DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(), NumBits)));
2290     }
2291 
2292     // If this is an 8 or 16-bit value, it is really passed promoted
2293     // to 32 bits. Insert an assert[sz]ext to capture this, then
2294     // truncate to the right size.
2295     switch (VA.getLocInfo()) {
2296     case CCValAssign::Full:
2297       break;
2298     case CCValAssign::BCvt:
2299       Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2300       break;
2301     case CCValAssign::SExt:
2302       Val = DAG.getNode(ISD::AssertSext, DL, VT, Val,
2303                         DAG.getValueType(ValVT));
2304       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2305       break;
2306     case CCValAssign::ZExt:
2307       Val = DAG.getNode(ISD::AssertZext, DL, VT, Val,
2308                         DAG.getValueType(ValVT));
2309       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2310       break;
2311     case CCValAssign::AExt:
2312       Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2313       break;
2314     default:
2315       llvm_unreachable("Unknown loc info!");
2316     }
2317 
2318     InVals.push_back(Val);
2319   }
2320 
2321   if (!IsEntryFunc && !AMDGPUTargetMachine::EnableFixedFunctionABI) {
2322     // Special inputs come after user arguments.
2323     allocateSpecialInputVGPRs(CCInfo, MF, *TRI, *Info);
2324   }
2325 
2326   // Start adding system SGPRs.
2327   if (IsEntryFunc) {
2328     allocateSystemSGPRs(CCInfo, MF, *Info, CallConv, IsShader);
2329   } else {
2330     CCInfo.AllocateReg(Info->getScratchRSrcReg());
2331     allocateSpecialInputSGPRs(CCInfo, MF, *TRI, *Info);
2332   }
2333 
2334   auto &ArgUsageInfo =
2335     DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2336   ArgUsageInfo.setFuncArgInfo(Fn, Info->getArgInfo());
2337 
2338   unsigned StackArgSize = CCInfo.getNextStackOffset();
2339   Info->setBytesInStackArgArea(StackArgSize);
2340 
2341   return Chains.empty() ? Chain :
2342     DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
2343 }
2344 
2345 // TODO: If return values can't fit in registers, we should return as many as
2346 // possible in registers before passing on stack.
2347 bool SITargetLowering::CanLowerReturn(
2348   CallingConv::ID CallConv,
2349   MachineFunction &MF, bool IsVarArg,
2350   const SmallVectorImpl<ISD::OutputArg> &Outs,
2351   LLVMContext &Context) const {
2352   // Replacing returns with sret/stack usage doesn't make sense for shaders.
2353   // FIXME: Also sort of a workaround for custom vector splitting in LowerReturn
2354   // for shaders. Vector types should be explicitly handled by CC.
2355   if (AMDGPU::isEntryFunctionCC(CallConv))
2356     return true;
2357 
2358   SmallVector<CCValAssign, 16> RVLocs;
2359   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2360   return CCInfo.CheckReturn(Outs, CCAssignFnForReturn(CallConv, IsVarArg));
2361 }
2362 
2363 SDValue
2364 SITargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
2365                               bool isVarArg,
2366                               const SmallVectorImpl<ISD::OutputArg> &Outs,
2367                               const SmallVectorImpl<SDValue> &OutVals,
2368                               const SDLoc &DL, SelectionDAG &DAG) const {
2369   MachineFunction &MF = DAG.getMachineFunction();
2370   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2371 
2372   if (AMDGPU::isKernel(CallConv)) {
2373     return AMDGPUTargetLowering::LowerReturn(Chain, CallConv, isVarArg, Outs,
2374                                              OutVals, DL, DAG);
2375   }
2376 
2377   bool IsShader = AMDGPU::isShader(CallConv);
2378 
2379   Info->setIfReturnsVoid(Outs.empty());
2380   bool IsWaveEnd = Info->returnsVoid() && IsShader;
2381 
2382   // CCValAssign - represent the assignment of the return value to a location.
2383   SmallVector<CCValAssign, 48> RVLocs;
2384   SmallVector<ISD::OutputArg, 48> Splits;
2385 
2386   // CCState - Info about the registers and stack slots.
2387   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2388                  *DAG.getContext());
2389 
2390   // Analyze outgoing return values.
2391   CCInfo.AnalyzeReturn(Outs, CCAssignFnForReturn(CallConv, isVarArg));
2392 
2393   SDValue Flag;
2394   SmallVector<SDValue, 48> RetOps;
2395   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2396 
2397   // Add return address for callable functions.
2398   if (!Info->isEntryFunction()) {
2399     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2400     SDValue ReturnAddrReg = CreateLiveInRegister(
2401       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
2402 
2403     SDValue ReturnAddrVirtualReg = DAG.getRegister(
2404         MF.getRegInfo().createVirtualRegister(&AMDGPU::CCR_SGPR_64RegClass),
2405         MVT::i64);
2406     Chain =
2407         DAG.getCopyToReg(Chain, DL, ReturnAddrVirtualReg, ReturnAddrReg, Flag);
2408     Flag = Chain.getValue(1);
2409     RetOps.push_back(ReturnAddrVirtualReg);
2410   }
2411 
2412   // Copy the result values into the output registers.
2413   for (unsigned I = 0, RealRVLocIdx = 0, E = RVLocs.size(); I != E;
2414        ++I, ++RealRVLocIdx) {
2415     CCValAssign &VA = RVLocs[I];
2416     assert(VA.isRegLoc() && "Can only return in registers!");
2417     // TODO: Partially return in registers if return values don't fit.
2418     SDValue Arg = OutVals[RealRVLocIdx];
2419 
2420     // Copied from other backends.
2421     switch (VA.getLocInfo()) {
2422     case CCValAssign::Full:
2423       break;
2424     case CCValAssign::BCvt:
2425       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2426       break;
2427     case CCValAssign::SExt:
2428       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2429       break;
2430     case CCValAssign::ZExt:
2431       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2432       break;
2433     case CCValAssign::AExt:
2434       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2435       break;
2436     default:
2437       llvm_unreachable("Unknown loc info!");
2438     }
2439 
2440     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Arg, Flag);
2441     Flag = Chain.getValue(1);
2442     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2443   }
2444 
2445   // FIXME: Does sret work properly?
2446   if (!Info->isEntryFunction()) {
2447     const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2448     const MCPhysReg *I =
2449       TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
2450     if (I) {
2451       for (; *I; ++I) {
2452         if (AMDGPU::SReg_64RegClass.contains(*I))
2453           RetOps.push_back(DAG.getRegister(*I, MVT::i64));
2454         else if (AMDGPU::SReg_32RegClass.contains(*I))
2455           RetOps.push_back(DAG.getRegister(*I, MVT::i32));
2456         else
2457           llvm_unreachable("Unexpected register class in CSRsViaCopy!");
2458       }
2459     }
2460   }
2461 
2462   // Update chain and glue.
2463   RetOps[0] = Chain;
2464   if (Flag.getNode())
2465     RetOps.push_back(Flag);
2466 
2467   unsigned Opc = AMDGPUISD::ENDPGM;
2468   if (!IsWaveEnd)
2469     Opc = IsShader ? AMDGPUISD::RETURN_TO_EPILOG : AMDGPUISD::RET_FLAG;
2470   return DAG.getNode(Opc, DL, MVT::Other, RetOps);
2471 }
2472 
2473 SDValue SITargetLowering::LowerCallResult(
2474     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2475     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
2476     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool IsThisReturn,
2477     SDValue ThisVal) const {
2478   CCAssignFn *RetCC = CCAssignFnForReturn(CallConv, IsVarArg);
2479 
2480   // Assign locations to each value returned by this call.
2481   SmallVector<CCValAssign, 16> RVLocs;
2482   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2483                  *DAG.getContext());
2484   CCInfo.AnalyzeCallResult(Ins, RetCC);
2485 
2486   // Copy all of the result registers out of their specified physreg.
2487   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2488     CCValAssign VA = RVLocs[i];
2489     SDValue Val;
2490 
2491     if (VA.isRegLoc()) {
2492       Val = DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
2493       Chain = Val.getValue(1);
2494       InFlag = Val.getValue(2);
2495     } else if (VA.isMemLoc()) {
2496       report_fatal_error("TODO: return values in memory");
2497     } else
2498       llvm_unreachable("unknown argument location type");
2499 
2500     switch (VA.getLocInfo()) {
2501     case CCValAssign::Full:
2502       break;
2503     case CCValAssign::BCvt:
2504       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2505       break;
2506     case CCValAssign::ZExt:
2507       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2508                         DAG.getValueType(VA.getValVT()));
2509       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2510       break;
2511     case CCValAssign::SExt:
2512       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2513                         DAG.getValueType(VA.getValVT()));
2514       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2515       break;
2516     case CCValAssign::AExt:
2517       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2518       break;
2519     default:
2520       llvm_unreachable("Unknown loc info!");
2521     }
2522 
2523     InVals.push_back(Val);
2524   }
2525 
2526   return Chain;
2527 }
2528 
2529 // Add code to pass special inputs required depending on used features separate
2530 // from the explicit user arguments present in the IR.
2531 void SITargetLowering::passSpecialInputs(
2532     CallLoweringInfo &CLI,
2533     CCState &CCInfo,
2534     const SIMachineFunctionInfo &Info,
2535     SmallVectorImpl<std::pair<unsigned, SDValue>> &RegsToPass,
2536     SmallVectorImpl<SDValue> &MemOpChains,
2537     SDValue Chain) const {
2538   // If we don't have a call site, this was a call inserted by
2539   // legalization. These can never use special inputs.
2540   if (!CLI.CB)
2541     return;
2542 
2543   SelectionDAG &DAG = CLI.DAG;
2544   const SDLoc &DL = CLI.DL;
2545 
2546   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
2547   const AMDGPUFunctionArgInfo &CallerArgInfo = Info.getArgInfo();
2548 
2549   const AMDGPUFunctionArgInfo *CalleeArgInfo
2550     = &AMDGPUArgumentUsageInfo::FixedABIFunctionInfo;
2551   if (const Function *CalleeFunc = CLI.CB->getCalledFunction()) {
2552     auto &ArgUsageInfo =
2553       DAG.getPass()->getAnalysis<AMDGPUArgumentUsageInfo>();
2554     CalleeArgInfo = &ArgUsageInfo.lookupFuncArgInfo(*CalleeFunc);
2555   }
2556 
2557   // TODO: Unify with private memory register handling. This is complicated by
2558   // the fact that at least in kernels, the input argument is not necessarily
2559   // in the same location as the input.
2560   AMDGPUFunctionArgInfo::PreloadedValue InputRegs[] = {
2561     AMDGPUFunctionArgInfo::DISPATCH_PTR,
2562     AMDGPUFunctionArgInfo::QUEUE_PTR,
2563     AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR,
2564     AMDGPUFunctionArgInfo::DISPATCH_ID,
2565     AMDGPUFunctionArgInfo::WORKGROUP_ID_X,
2566     AMDGPUFunctionArgInfo::WORKGROUP_ID_Y,
2567     AMDGPUFunctionArgInfo::WORKGROUP_ID_Z
2568   };
2569 
2570   for (auto InputID : InputRegs) {
2571     const ArgDescriptor *OutgoingArg;
2572     const TargetRegisterClass *ArgRC;
2573 
2574     std::tie(OutgoingArg, ArgRC) = CalleeArgInfo->getPreloadedValue(InputID);
2575     if (!OutgoingArg)
2576       continue;
2577 
2578     const ArgDescriptor *IncomingArg;
2579     const TargetRegisterClass *IncomingArgRC;
2580     std::tie(IncomingArg, IncomingArgRC)
2581       = CallerArgInfo.getPreloadedValue(InputID);
2582     assert(IncomingArgRC == ArgRC);
2583 
2584     // All special arguments are ints for now.
2585     EVT ArgVT = TRI->getSpillSize(*ArgRC) == 8 ? MVT::i64 : MVT::i32;
2586     SDValue InputReg;
2587 
2588     if (IncomingArg) {
2589       InputReg = loadInputValue(DAG, ArgRC, ArgVT, DL, *IncomingArg);
2590     } else {
2591       // The implicit arg ptr is special because it doesn't have a corresponding
2592       // input for kernels, and is computed from the kernarg segment pointer.
2593       assert(InputID == AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
2594       InputReg = getImplicitArgPtr(DAG, DL);
2595     }
2596 
2597     if (OutgoingArg->isRegister()) {
2598       RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2599       if (!CCInfo.AllocateReg(OutgoingArg->getRegister()))
2600         report_fatal_error("failed to allocate implicit input argument");
2601     } else {
2602       unsigned SpecialArgOffset =
2603           CCInfo.AllocateStack(ArgVT.getStoreSize(), Align(4));
2604       SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2605                                               SpecialArgOffset);
2606       MemOpChains.push_back(ArgStore);
2607     }
2608   }
2609 
2610   // Pack workitem IDs into a single register or pass it as is if already
2611   // packed.
2612   const ArgDescriptor *OutgoingArg;
2613   const TargetRegisterClass *ArgRC;
2614 
2615   std::tie(OutgoingArg, ArgRC) =
2616     CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X);
2617   if (!OutgoingArg)
2618     std::tie(OutgoingArg, ArgRC) =
2619       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y);
2620   if (!OutgoingArg)
2621     std::tie(OutgoingArg, ArgRC) =
2622       CalleeArgInfo->getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z);
2623   if (!OutgoingArg)
2624     return;
2625 
2626   const ArgDescriptor *IncomingArgX
2627     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_X).first;
2628   const ArgDescriptor *IncomingArgY
2629     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Y).first;
2630   const ArgDescriptor *IncomingArgZ
2631     = CallerArgInfo.getPreloadedValue(AMDGPUFunctionArgInfo::WORKITEM_ID_Z).first;
2632 
2633   SDValue InputReg;
2634   SDLoc SL;
2635 
2636   // If incoming ids are not packed we need to pack them.
2637   if (IncomingArgX && !IncomingArgX->isMasked() && CalleeArgInfo->WorkItemIDX)
2638     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgX);
2639 
2640   if (IncomingArgY && !IncomingArgY->isMasked() && CalleeArgInfo->WorkItemIDY) {
2641     SDValue Y = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgY);
2642     Y = DAG.getNode(ISD::SHL, SL, MVT::i32, Y,
2643                     DAG.getShiftAmountConstant(10, MVT::i32, SL));
2644     InputReg = InputReg.getNode() ?
2645                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Y) : Y;
2646   }
2647 
2648   if (IncomingArgZ && !IncomingArgZ->isMasked() && CalleeArgInfo->WorkItemIDZ) {
2649     SDValue Z = loadInputValue(DAG, ArgRC, MVT::i32, DL, *IncomingArgZ);
2650     Z = DAG.getNode(ISD::SHL, SL, MVT::i32, Z,
2651                     DAG.getShiftAmountConstant(20, MVT::i32, SL));
2652     InputReg = InputReg.getNode() ?
2653                  DAG.getNode(ISD::OR, SL, MVT::i32, InputReg, Z) : Z;
2654   }
2655 
2656   if (!InputReg.getNode()) {
2657     // Workitem ids are already packed, any of present incoming arguments
2658     // will carry all required fields.
2659     ArgDescriptor IncomingArg = ArgDescriptor::createArg(
2660       IncomingArgX ? *IncomingArgX :
2661       IncomingArgY ? *IncomingArgY :
2662                      *IncomingArgZ, ~0u);
2663     InputReg = loadInputValue(DAG, ArgRC, MVT::i32, DL, IncomingArg);
2664   }
2665 
2666   if (OutgoingArg->isRegister()) {
2667     RegsToPass.emplace_back(OutgoingArg->getRegister(), InputReg);
2668     CCInfo.AllocateReg(OutgoingArg->getRegister());
2669   } else {
2670     unsigned SpecialArgOffset = CCInfo.AllocateStack(4, Align(4));
2671     SDValue ArgStore = storeStackInputValue(DAG, DL, Chain, InputReg,
2672                                             SpecialArgOffset);
2673     MemOpChains.push_back(ArgStore);
2674   }
2675 }
2676 
2677 static bool canGuaranteeTCO(CallingConv::ID CC) {
2678   return CC == CallingConv::Fast;
2679 }
2680 
2681 /// Return true if we might ever do TCO for calls with this calling convention.
2682 static bool mayTailCallThisCC(CallingConv::ID CC) {
2683   switch (CC) {
2684   case CallingConv::C:
2685     return true;
2686   default:
2687     return canGuaranteeTCO(CC);
2688   }
2689 }
2690 
2691 bool SITargetLowering::isEligibleForTailCallOptimization(
2692     SDValue Callee, CallingConv::ID CalleeCC, bool IsVarArg,
2693     const SmallVectorImpl<ISD::OutputArg> &Outs,
2694     const SmallVectorImpl<SDValue> &OutVals,
2695     const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
2696   if (!mayTailCallThisCC(CalleeCC))
2697     return false;
2698 
2699   MachineFunction &MF = DAG.getMachineFunction();
2700   const Function &CallerF = MF.getFunction();
2701   CallingConv::ID CallerCC = CallerF.getCallingConv();
2702   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
2703   const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
2704 
2705   // Kernels aren't callable, and don't have a live in return address so it
2706   // doesn't make sense to do a tail call with entry functions.
2707   if (!CallerPreserved)
2708     return false;
2709 
2710   bool CCMatch = CallerCC == CalleeCC;
2711 
2712   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
2713     if (canGuaranteeTCO(CalleeCC) && CCMatch)
2714       return true;
2715     return false;
2716   }
2717 
2718   // TODO: Can we handle var args?
2719   if (IsVarArg)
2720     return false;
2721 
2722   for (const Argument &Arg : CallerF.args()) {
2723     if (Arg.hasByValAttr())
2724       return false;
2725   }
2726 
2727   LLVMContext &Ctx = *DAG.getContext();
2728 
2729   // Check that the call results are passed in the same way.
2730   if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, Ctx, Ins,
2731                                   CCAssignFnForCall(CalleeCC, IsVarArg),
2732                                   CCAssignFnForCall(CallerCC, IsVarArg)))
2733     return false;
2734 
2735   // The callee has to preserve all registers the caller needs to preserve.
2736   if (!CCMatch) {
2737     const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
2738     if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
2739       return false;
2740   }
2741 
2742   // Nothing more to check if the callee is taking no arguments.
2743   if (Outs.empty())
2744     return true;
2745 
2746   SmallVector<CCValAssign, 16> ArgLocs;
2747   CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, Ctx);
2748 
2749   CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, IsVarArg));
2750 
2751   const SIMachineFunctionInfo *FuncInfo = MF.getInfo<SIMachineFunctionInfo>();
2752   // If the stack arguments for this call do not fit into our own save area then
2753   // the call cannot be made tail.
2754   // TODO: Is this really necessary?
2755   if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
2756     return false;
2757 
2758   const MachineRegisterInfo &MRI = MF.getRegInfo();
2759   return parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals);
2760 }
2761 
2762 bool SITargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
2763   if (!CI->isTailCall())
2764     return false;
2765 
2766   const Function *ParentFn = CI->getParent()->getParent();
2767   if (AMDGPU::isEntryFunctionCC(ParentFn->getCallingConv()))
2768     return false;
2769   return true;
2770 }
2771 
2772 // The wave scratch offset register is used as the global base pointer.
2773 SDValue SITargetLowering::LowerCall(CallLoweringInfo &CLI,
2774                                     SmallVectorImpl<SDValue> &InVals) const {
2775   SelectionDAG &DAG = CLI.DAG;
2776   const SDLoc &DL = CLI.DL;
2777   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2778   SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2779   SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2780   SDValue Chain = CLI.Chain;
2781   SDValue Callee = CLI.Callee;
2782   bool &IsTailCall = CLI.IsTailCall;
2783   CallingConv::ID CallConv = CLI.CallConv;
2784   bool IsVarArg = CLI.IsVarArg;
2785   bool IsSibCall = false;
2786   bool IsThisReturn = false;
2787   MachineFunction &MF = DAG.getMachineFunction();
2788 
2789   if (Callee.isUndef() || isNullConstant(Callee)) {
2790     if (!CLI.IsTailCall) {
2791       for (unsigned I = 0, E = CLI.Ins.size(); I != E; ++I)
2792         InVals.push_back(DAG.getUNDEF(CLI.Ins[I].VT));
2793     }
2794 
2795     return Chain;
2796   }
2797 
2798   if (IsVarArg) {
2799     return lowerUnhandledCall(CLI, InVals,
2800                               "unsupported call to variadic function ");
2801   }
2802 
2803   if (!CLI.CB)
2804     report_fatal_error("unsupported libcall legalization");
2805 
2806   if (!AMDGPUTargetMachine::EnableFixedFunctionABI &&
2807       !CLI.CB->getCalledFunction()) {
2808     return lowerUnhandledCall(CLI, InVals,
2809                               "unsupported indirect call to function ");
2810   }
2811 
2812   if (IsTailCall && MF.getTarget().Options.GuaranteedTailCallOpt) {
2813     return lowerUnhandledCall(CLI, InVals,
2814                               "unsupported required tail call to function ");
2815   }
2816 
2817   if (AMDGPU::isShader(MF.getFunction().getCallingConv())) {
2818     // Note the issue is with the CC of the calling function, not of the call
2819     // itself.
2820     return lowerUnhandledCall(CLI, InVals,
2821                           "unsupported call from graphics shader of function ");
2822   }
2823 
2824   if (IsTailCall) {
2825     IsTailCall = isEligibleForTailCallOptimization(
2826       Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
2827     if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall()) {
2828       report_fatal_error("failed to perform tail call elimination on a call "
2829                          "site marked musttail");
2830     }
2831 
2832     bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
2833 
2834     // A sibling call is one where we're under the usual C ABI and not planning
2835     // to change that but can still do a tail call:
2836     if (!TailCallOpt && IsTailCall)
2837       IsSibCall = true;
2838 
2839     if (IsTailCall)
2840       ++NumTailCalls;
2841   }
2842 
2843   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
2844   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2845   SmallVector<SDValue, 8> MemOpChains;
2846 
2847   // Analyze operands of the call, assigning locations to each operand.
2848   SmallVector<CCValAssign, 16> ArgLocs;
2849   CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
2850   CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, IsVarArg);
2851 
2852   if (AMDGPUTargetMachine::EnableFixedFunctionABI) {
2853     // With a fixed ABI, allocate fixed registers before user arguments.
2854     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2855   }
2856 
2857   CCInfo.AnalyzeCallOperands(Outs, AssignFn);
2858 
2859   // Get a count of how many bytes are to be pushed on the stack.
2860   unsigned NumBytes = CCInfo.getNextStackOffset();
2861 
2862   if (IsSibCall) {
2863     // Since we're not changing the ABI to make this a tail call, the memory
2864     // operands are already available in the caller's incoming argument space.
2865     NumBytes = 0;
2866   }
2867 
2868   // FPDiff is the byte offset of the call's argument area from the callee's.
2869   // Stores to callee stack arguments will be placed in FixedStackSlots offset
2870   // by this amount for a tail call. In a sibling call it must be 0 because the
2871   // caller will deallocate the entire stack and the callee still expects its
2872   // arguments to begin at SP+0. Completely unused for non-tail calls.
2873   int32_t FPDiff = 0;
2874   MachineFrameInfo &MFI = MF.getFrameInfo();
2875 
2876   // Adjust the stack pointer for the new arguments...
2877   // These operations are automatically eliminated by the prolog/epilog pass
2878   if (!IsSibCall) {
2879     Chain = DAG.getCALLSEQ_START(Chain, 0, 0, DL);
2880 
2881     SmallVector<SDValue, 4> CopyFromChains;
2882 
2883     // In the HSA case, this should be an identity copy.
2884     SDValue ScratchRSrcReg
2885       = DAG.getCopyFromReg(Chain, DL, Info->getScratchRSrcReg(), MVT::v4i32);
2886     RegsToPass.emplace_back(AMDGPU::SGPR0_SGPR1_SGPR2_SGPR3, ScratchRSrcReg);
2887     CopyFromChains.push_back(ScratchRSrcReg.getValue(1));
2888     Chain = DAG.getTokenFactor(DL, CopyFromChains);
2889   }
2890 
2891   MVT PtrVT = MVT::i32;
2892 
2893   // Walk the register/memloc assignments, inserting copies/loads.
2894   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2895     CCValAssign &VA = ArgLocs[i];
2896     SDValue Arg = OutVals[i];
2897 
2898     // Promote the value if needed.
2899     switch (VA.getLocInfo()) {
2900     case CCValAssign::Full:
2901       break;
2902     case CCValAssign::BCvt:
2903       Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
2904       break;
2905     case CCValAssign::ZExt:
2906       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
2907       break;
2908     case CCValAssign::SExt:
2909       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
2910       break;
2911     case CCValAssign::AExt:
2912       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
2913       break;
2914     case CCValAssign::FPExt:
2915       Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
2916       break;
2917     default:
2918       llvm_unreachable("Unknown loc info!");
2919     }
2920 
2921     if (VA.isRegLoc()) {
2922       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2923     } else {
2924       assert(VA.isMemLoc());
2925 
2926       SDValue DstAddr;
2927       MachinePointerInfo DstInfo;
2928 
2929       unsigned LocMemOffset = VA.getLocMemOffset();
2930       int32_t Offset = LocMemOffset;
2931 
2932       SDValue PtrOff = DAG.getConstant(Offset, DL, PtrVT);
2933       MaybeAlign Alignment;
2934 
2935       if (IsTailCall) {
2936         ISD::ArgFlagsTy Flags = Outs[i].Flags;
2937         unsigned OpSize = Flags.isByVal() ?
2938           Flags.getByValSize() : VA.getValVT().getStoreSize();
2939 
2940         // FIXME: We can have better than the minimum byval required alignment.
2941         Alignment =
2942             Flags.isByVal()
2943                 ? Flags.getNonZeroByValAlign()
2944                 : commonAlignment(Subtarget->getStackAlignment(), Offset);
2945 
2946         Offset = Offset + FPDiff;
2947         int FI = MFI.CreateFixedObject(OpSize, Offset, true);
2948 
2949         DstAddr = DAG.getFrameIndex(FI, PtrVT);
2950         DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
2951 
2952         // Make sure any stack arguments overlapping with where we're storing
2953         // are loaded before this eventual operation. Otherwise they'll be
2954         // clobbered.
2955 
2956         // FIXME: Why is this really necessary? This seems to just result in a
2957         // lot of code to copy the stack and write them back to the same
2958         // locations, which are supposed to be immutable?
2959         Chain = addTokenForArgument(Chain, DAG, MFI, FI);
2960       } else {
2961         DstAddr = PtrOff;
2962         DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
2963         Alignment =
2964             commonAlignment(Subtarget->getStackAlignment(), LocMemOffset);
2965       }
2966 
2967       if (Outs[i].Flags.isByVal()) {
2968         SDValue SizeNode =
2969             DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i32);
2970         SDValue Cpy =
2971             DAG.getMemcpy(Chain, DL, DstAddr, Arg, SizeNode,
2972                           Outs[i].Flags.getNonZeroByValAlign(),
2973                           /*isVol = */ false, /*AlwaysInline = */ true,
2974                           /*isTailCall = */ false, DstInfo,
2975                           MachinePointerInfo(AMDGPUAS::PRIVATE_ADDRESS));
2976 
2977         MemOpChains.push_back(Cpy);
2978       } else {
2979         SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo,
2980                                      Alignment ? Alignment->value() : 0);
2981         MemOpChains.push_back(Store);
2982       }
2983     }
2984   }
2985 
2986   if (!AMDGPUTargetMachine::EnableFixedFunctionABI) {
2987     // Copy special input registers after user input arguments.
2988     passSpecialInputs(CLI, CCInfo, *Info, RegsToPass, MemOpChains, Chain);
2989   }
2990 
2991   if (!MemOpChains.empty())
2992     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2993 
2994   // Build a sequence of copy-to-reg nodes chained together with token chain
2995   // and flag operands which copy the outgoing args into the appropriate regs.
2996   SDValue InFlag;
2997   for (auto &RegToPass : RegsToPass) {
2998     Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
2999                              RegToPass.second, InFlag);
3000     InFlag = Chain.getValue(1);
3001   }
3002 
3003 
3004   SDValue PhysReturnAddrReg;
3005   if (IsTailCall) {
3006     // Since the return is being combined with the call, we need to pass on the
3007     // return address.
3008 
3009     const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
3010     SDValue ReturnAddrReg = CreateLiveInRegister(
3011       DAG, &AMDGPU::SReg_64RegClass, TRI->getReturnAddressReg(MF), MVT::i64);
3012 
3013     PhysReturnAddrReg = DAG.getRegister(TRI->getReturnAddressReg(MF),
3014                                         MVT::i64);
3015     Chain = DAG.getCopyToReg(Chain, DL, PhysReturnAddrReg, ReturnAddrReg, InFlag);
3016     InFlag = Chain.getValue(1);
3017   }
3018 
3019   // We don't usually want to end the call-sequence here because we would tidy
3020   // the frame up *after* the call, however in the ABI-changing tail-call case
3021   // we've carefully laid out the parameters so that when sp is reset they'll be
3022   // in the correct location.
3023   if (IsTailCall && !IsSibCall) {
3024     Chain = DAG.getCALLSEQ_END(Chain,
3025                                DAG.getTargetConstant(NumBytes, DL, MVT::i32),
3026                                DAG.getTargetConstant(0, DL, MVT::i32),
3027                                InFlag, DL);
3028     InFlag = Chain.getValue(1);
3029   }
3030 
3031   std::vector<SDValue> Ops;
3032   Ops.push_back(Chain);
3033   Ops.push_back(Callee);
3034   // Add a redundant copy of the callee global which will not be legalized, as
3035   // we need direct access to the callee later.
3036   if (GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(Callee)) {
3037     const GlobalValue *GV = GSD->getGlobal();
3038     Ops.push_back(DAG.getTargetGlobalAddress(GV, DL, MVT::i64));
3039   } else {
3040     Ops.push_back(DAG.getTargetConstant(0, DL, MVT::i64));
3041   }
3042 
3043   if (IsTailCall) {
3044     // Each tail call may have to adjust the stack by a different amount, so
3045     // this information must travel along with the operation for eventual
3046     // consumption by emitEpilogue.
3047     Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
3048 
3049     Ops.push_back(PhysReturnAddrReg);
3050   }
3051 
3052   // Add argument registers to the end of the list so that they are known live
3053   // into the call.
3054   for (auto &RegToPass : RegsToPass) {
3055     Ops.push_back(DAG.getRegister(RegToPass.first,
3056                                   RegToPass.second.getValueType()));
3057   }
3058 
3059   // Add a register mask operand representing the call-preserved registers.
3060 
3061   auto *TRI = static_cast<const SIRegisterInfo*>(Subtarget->getRegisterInfo());
3062   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3063   assert(Mask && "Missing call preserved mask for calling convention");
3064   Ops.push_back(DAG.getRegisterMask(Mask));
3065 
3066   if (InFlag.getNode())
3067     Ops.push_back(InFlag);
3068 
3069   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3070 
3071   // If we're doing a tall call, use a TC_RETURN here rather than an
3072   // actual call instruction.
3073   if (IsTailCall) {
3074     MFI.setHasTailCall();
3075     return DAG.getNode(AMDGPUISD::TC_RETURN, DL, NodeTys, Ops);
3076   }
3077 
3078   // Returns a chain and a flag for retval copy to use.
3079   SDValue Call = DAG.getNode(AMDGPUISD::CALL, DL, NodeTys, Ops);
3080   Chain = Call.getValue(0);
3081   InFlag = Call.getValue(1);
3082 
3083   uint64_t CalleePopBytes = NumBytes;
3084   Chain = DAG.getCALLSEQ_END(Chain, DAG.getTargetConstant(0, DL, MVT::i32),
3085                              DAG.getTargetConstant(CalleePopBytes, DL, MVT::i32),
3086                              InFlag, DL);
3087   if (!Ins.empty())
3088     InFlag = Chain.getValue(1);
3089 
3090   // Handle result values, copying them out of physregs into vregs that we
3091   // return.
3092   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3093                          InVals, IsThisReturn,
3094                          IsThisReturn ? OutVals[0] : SDValue());
3095 }
3096 
3097 // This is identical to the default implementation in ExpandDYNAMIC_STACKALLOC,
3098 // except for applying the wave size scale to the increment amount.
3099 SDValue SITargetLowering::lowerDYNAMIC_STACKALLOCImpl(
3100     SDValue Op, SelectionDAG &DAG) const {
3101   const MachineFunction &MF = DAG.getMachineFunction();
3102   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
3103 
3104   SDLoc dl(Op);
3105   EVT VT = Op.getValueType();
3106   SDValue Tmp1 = Op;
3107   SDValue Tmp2 = Op.getValue(1);
3108   SDValue Tmp3 = Op.getOperand(2);
3109   SDValue Chain = Tmp1.getOperand(0);
3110 
3111   Register SPReg = Info->getStackPtrOffsetReg();
3112 
3113   // Chain the dynamic stack allocation so that it doesn't modify the stack
3114   // pointer when other instructions are using the stack.
3115   Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
3116 
3117   SDValue Size  = Tmp2.getOperand(1);
3118   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
3119   Chain = SP.getValue(1);
3120   unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
3121   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
3122   const TargetFrameLowering *TFL = ST.getFrameLowering();
3123   unsigned Opc =
3124     TFL->getStackGrowthDirection() == TargetFrameLowering::StackGrowsUp ?
3125     ISD::ADD : ISD::SUB;
3126 
3127   SDValue ScaledSize = DAG.getNode(
3128       ISD::SHL, dl, VT, Size,
3129       DAG.getConstant(ST.getWavefrontSizeLog2(), dl, MVT::i32));
3130 
3131   unsigned StackAlign = TFL->getStackAlignment();
3132   Tmp1 = DAG.getNode(Opc, dl, VT, SP, ScaledSize); // Value
3133   if (Align > StackAlign) {
3134     Tmp1 = DAG.getNode(
3135       ISD::AND, dl, VT, Tmp1,
3136       DAG.getConstant(-(uint64_t)Align << ST.getWavefrontSizeLog2(), dl, VT));
3137   }
3138 
3139   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);    // Output chain
3140   Tmp2 = DAG.getCALLSEQ_END(
3141       Chain, DAG.getIntPtrConstant(0, dl, true),
3142       DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
3143 
3144   return DAG.getMergeValues({Tmp1, Tmp2}, dl);
3145 }
3146 
3147 SDValue SITargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
3148                                                   SelectionDAG &DAG) const {
3149   // We only handle constant sizes here to allow non-entry block, static sized
3150   // allocas. A truly dynamic value is more difficult to support because we
3151   // don't know if the size value is uniform or not. If the size isn't uniform,
3152   // we would need to do a wave reduction to get the maximum size to know how
3153   // much to increment the uniform stack pointer.
3154   SDValue Size = Op.getOperand(1);
3155   if (isa<ConstantSDNode>(Size))
3156       return lowerDYNAMIC_STACKALLOCImpl(Op, DAG); // Use "generic" expansion.
3157 
3158   return AMDGPUTargetLowering::LowerDYNAMIC_STACKALLOC(Op, DAG);
3159 }
3160 
3161 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
3162                                              const MachineFunction &MF) const {
3163   Register Reg = StringSwitch<Register>(RegName)
3164     .Case("m0", AMDGPU::M0)
3165     .Case("exec", AMDGPU::EXEC)
3166     .Case("exec_lo", AMDGPU::EXEC_LO)
3167     .Case("exec_hi", AMDGPU::EXEC_HI)
3168     .Case("flat_scratch", AMDGPU::FLAT_SCR)
3169     .Case("flat_scratch_lo", AMDGPU::FLAT_SCR_LO)
3170     .Case("flat_scratch_hi", AMDGPU::FLAT_SCR_HI)
3171     .Default(Register());
3172 
3173   if (Reg == AMDGPU::NoRegister) {
3174     report_fatal_error(Twine("invalid register name \""
3175                              + StringRef(RegName)  + "\"."));
3176 
3177   }
3178 
3179   if (!Subtarget->hasFlatScrRegister() &&
3180        Subtarget->getRegisterInfo()->regsOverlap(Reg, AMDGPU::FLAT_SCR)) {
3181     report_fatal_error(Twine("invalid register \""
3182                              + StringRef(RegName)  + "\" for subtarget."));
3183   }
3184 
3185   switch (Reg) {
3186   case AMDGPU::M0:
3187   case AMDGPU::EXEC_LO:
3188   case AMDGPU::EXEC_HI:
3189   case AMDGPU::FLAT_SCR_LO:
3190   case AMDGPU::FLAT_SCR_HI:
3191     if (VT.getSizeInBits() == 32)
3192       return Reg;
3193     break;
3194   case AMDGPU::EXEC:
3195   case AMDGPU::FLAT_SCR:
3196     if (VT.getSizeInBits() == 64)
3197       return Reg;
3198     break;
3199   default:
3200     llvm_unreachable("missing register type checking");
3201   }
3202 
3203   report_fatal_error(Twine("invalid type for register \""
3204                            + StringRef(RegName) + "\"."));
3205 }
3206 
3207 // If kill is not the last instruction, split the block so kill is always a
3208 // proper terminator.
3209 MachineBasicBlock *SITargetLowering::splitKillBlock(MachineInstr &MI,
3210                                                     MachineBasicBlock *BB) const {
3211   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3212 
3213   MachineBasicBlock::iterator SplitPoint(&MI);
3214   ++SplitPoint;
3215 
3216   if (SplitPoint == BB->end()) {
3217     // Don't bother with a new block.
3218     MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3219     return BB;
3220   }
3221 
3222   MachineFunction *MF = BB->getParent();
3223   MachineBasicBlock *SplitBB
3224     = MF->CreateMachineBasicBlock(BB->getBasicBlock());
3225 
3226   MF->insert(++MachineFunction::iterator(BB), SplitBB);
3227   SplitBB->splice(SplitBB->begin(), BB, SplitPoint, BB->end());
3228 
3229   SplitBB->transferSuccessorsAndUpdatePHIs(BB);
3230   BB->addSuccessor(SplitBB);
3231 
3232   MI.setDesc(TII->getKillTerminatorFromPseudo(MI.getOpcode()));
3233   return SplitBB;
3234 }
3235 
3236 // Split block \p MBB at \p MI, as to insert a loop. If \p InstInLoop is true,
3237 // \p MI will be the only instruction in the loop body block. Otherwise, it will
3238 // be the first instruction in the remainder block.
3239 //
3240 /// \returns { LoopBody, Remainder }
3241 static std::pair<MachineBasicBlock *, MachineBasicBlock *>
3242 splitBlockForLoop(MachineInstr &MI, MachineBasicBlock &MBB, bool InstInLoop) {
3243   MachineFunction *MF = MBB.getParent();
3244   MachineBasicBlock::iterator I(&MI);
3245 
3246   // To insert the loop we need to split the block. Move everything after this
3247   // point to a new block, and insert a new empty block between the two.
3248   MachineBasicBlock *LoopBB = MF->CreateMachineBasicBlock();
3249   MachineBasicBlock *RemainderBB = MF->CreateMachineBasicBlock();
3250   MachineFunction::iterator MBBI(MBB);
3251   ++MBBI;
3252 
3253   MF->insert(MBBI, LoopBB);
3254   MF->insert(MBBI, RemainderBB);
3255 
3256   LoopBB->addSuccessor(LoopBB);
3257   LoopBB->addSuccessor(RemainderBB);
3258 
3259   // Move the rest of the block into a new block.
3260   RemainderBB->transferSuccessorsAndUpdatePHIs(&MBB);
3261 
3262   if (InstInLoop) {
3263     auto Next = std::next(I);
3264 
3265     // Move instruction to loop body.
3266     LoopBB->splice(LoopBB->begin(), &MBB, I, Next);
3267 
3268     // Move the rest of the block.
3269     RemainderBB->splice(RemainderBB->begin(), &MBB, Next, MBB.end());
3270   } else {
3271     RemainderBB->splice(RemainderBB->begin(), &MBB, I, MBB.end());
3272   }
3273 
3274   MBB.addSuccessor(LoopBB);
3275 
3276   return std::make_pair(LoopBB, RemainderBB);
3277 }
3278 
3279 /// Insert \p MI into a BUNDLE with an S_WAITCNT 0 immediately following it.
3280 void SITargetLowering::bundleInstWithWaitcnt(MachineInstr &MI) const {
3281   MachineBasicBlock *MBB = MI.getParent();
3282   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3283   auto I = MI.getIterator();
3284   auto E = std::next(I);
3285 
3286   BuildMI(*MBB, E, MI.getDebugLoc(), TII->get(AMDGPU::S_WAITCNT))
3287     .addImm(0);
3288 
3289   MIBundleBuilder Bundler(*MBB, I, E);
3290   finalizeBundle(*MBB, Bundler.begin());
3291 }
3292 
3293 MachineBasicBlock *
3294 SITargetLowering::emitGWSMemViolTestLoop(MachineInstr &MI,
3295                                          MachineBasicBlock *BB) const {
3296   const DebugLoc &DL = MI.getDebugLoc();
3297 
3298   MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3299 
3300   MachineBasicBlock *LoopBB;
3301   MachineBasicBlock *RemainderBB;
3302   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3303 
3304   // Apparently kill flags are only valid if the def is in the same block?
3305   if (MachineOperand *Src = TII->getNamedOperand(MI, AMDGPU::OpName::data0))
3306     Src->setIsKill(false);
3307 
3308   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, *BB, true);
3309 
3310   MachineBasicBlock::iterator I = LoopBB->end();
3311 
3312   const unsigned EncodedReg = AMDGPU::Hwreg::encodeHwreg(
3313     AMDGPU::Hwreg::ID_TRAPSTS, AMDGPU::Hwreg::OFFSET_MEM_VIOL, 1);
3314 
3315   // Clear TRAP_STS.MEM_VIOL
3316   BuildMI(*LoopBB, LoopBB->begin(), DL, TII->get(AMDGPU::S_SETREG_IMM32_B32))
3317     .addImm(0)
3318     .addImm(EncodedReg);
3319 
3320   bundleInstWithWaitcnt(MI);
3321 
3322   Register Reg = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3323 
3324   // Load and check TRAP_STS.MEM_VIOL
3325   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_GETREG_B32), Reg)
3326     .addImm(EncodedReg);
3327 
3328   // FIXME: Do we need to use an isel pseudo that may clobber scc?
3329   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CMP_LG_U32))
3330     .addReg(Reg, RegState::Kill)
3331     .addImm(0);
3332   BuildMI(*LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
3333     .addMBB(LoopBB);
3334 
3335   return RemainderBB;
3336 }
3337 
3338 // Do a v_movrels_b32 or v_movreld_b32 for each unique value of \p IdxReg in the
3339 // wavefront. If the value is uniform and just happens to be in a VGPR, this
3340 // will only do one iteration. In the worst case, this will loop 64 times.
3341 //
3342 // TODO: Just use v_readlane_b32 if we know the VGPR has a uniform value.
3343 static MachineBasicBlock::iterator emitLoadM0FromVGPRLoop(
3344   const SIInstrInfo *TII,
3345   MachineRegisterInfo &MRI,
3346   MachineBasicBlock &OrigBB,
3347   MachineBasicBlock &LoopBB,
3348   const DebugLoc &DL,
3349   const MachineOperand &IdxReg,
3350   unsigned InitReg,
3351   unsigned ResultReg,
3352   unsigned PhiReg,
3353   unsigned InitSaveExecReg,
3354   int Offset,
3355   bool UseGPRIdxMode,
3356   bool IsIndirectSrc) {
3357   MachineFunction *MF = OrigBB.getParent();
3358   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3359   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3360   MachineBasicBlock::iterator I = LoopBB.begin();
3361 
3362   const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3363   Register PhiExec = MRI.createVirtualRegister(BoolRC);
3364   Register NewExec = MRI.createVirtualRegister(BoolRC);
3365   Register CurrentIdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3366   Register CondReg = MRI.createVirtualRegister(BoolRC);
3367 
3368   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiReg)
3369     .addReg(InitReg)
3370     .addMBB(&OrigBB)
3371     .addReg(ResultReg)
3372     .addMBB(&LoopBB);
3373 
3374   BuildMI(LoopBB, I, DL, TII->get(TargetOpcode::PHI), PhiExec)
3375     .addReg(InitSaveExecReg)
3376     .addMBB(&OrigBB)
3377     .addReg(NewExec)
3378     .addMBB(&LoopBB);
3379 
3380   // Read the next variant <- also loop target.
3381   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), CurrentIdxReg)
3382     .addReg(IdxReg.getReg(), getUndefRegState(IdxReg.isUndef()));
3383 
3384   // Compare the just read M0 value to all possible Idx values.
3385   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::V_CMP_EQ_U32_e64), CondReg)
3386     .addReg(CurrentIdxReg)
3387     .addReg(IdxReg.getReg(), 0, IdxReg.getSubReg());
3388 
3389   // Update EXEC, save the original EXEC value to VCC.
3390   BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_AND_SAVEEXEC_B32
3391                                                 : AMDGPU::S_AND_SAVEEXEC_B64),
3392           NewExec)
3393     .addReg(CondReg, RegState::Kill);
3394 
3395   MRI.setSimpleHint(NewExec, CondReg);
3396 
3397   if (UseGPRIdxMode) {
3398     unsigned IdxReg;
3399     if (Offset == 0) {
3400       IdxReg = CurrentIdxReg;
3401     } else {
3402       IdxReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3403       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), IdxReg)
3404         .addReg(CurrentIdxReg, RegState::Kill)
3405         .addImm(Offset);
3406     }
3407     unsigned IdxMode = IsIndirectSrc ?
3408       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3409     MachineInstr *SetOn =
3410       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3411       .addReg(IdxReg, RegState::Kill)
3412       .addImm(IdxMode);
3413     SetOn->getOperand(3).setIsUndef();
3414   } else {
3415     // Move index from VCC into M0
3416     if (Offset == 0) {
3417       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3418         .addReg(CurrentIdxReg, RegState::Kill);
3419     } else {
3420       BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3421         .addReg(CurrentIdxReg, RegState::Kill)
3422         .addImm(Offset);
3423     }
3424   }
3425 
3426   // Update EXEC, switch all done bits to 0 and all todo bits to 1.
3427   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3428   MachineInstr *InsertPt =
3429     BuildMI(LoopBB, I, DL, TII->get(ST.isWave32() ? AMDGPU::S_XOR_B32_term
3430                                                   : AMDGPU::S_XOR_B64_term), Exec)
3431       .addReg(Exec)
3432       .addReg(NewExec);
3433 
3434   // XXX - s_xor_b64 sets scc to 1 if the result is nonzero, so can we use
3435   // s_cbranch_scc0?
3436 
3437   // Loop back to V_READFIRSTLANE_B32 if there are still variants to cover.
3438   BuildMI(LoopBB, I, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ))
3439     .addMBB(&LoopBB);
3440 
3441   return InsertPt->getIterator();
3442 }
3443 
3444 // This has slightly sub-optimal regalloc when the source vector is killed by
3445 // the read. The register allocator does not understand that the kill is
3446 // per-workitem, so is kept alive for the whole loop so we end up not re-using a
3447 // subregister from it, using 1 more VGPR than necessary. This was saved when
3448 // this was expanded after register allocation.
3449 static MachineBasicBlock::iterator loadM0FromVGPR(const SIInstrInfo *TII,
3450                                                   MachineBasicBlock &MBB,
3451                                                   MachineInstr &MI,
3452                                                   unsigned InitResultReg,
3453                                                   unsigned PhiReg,
3454                                                   int Offset,
3455                                                   bool UseGPRIdxMode,
3456                                                   bool IsIndirectSrc) {
3457   MachineFunction *MF = MBB.getParent();
3458   const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3459   const SIRegisterInfo *TRI = ST.getRegisterInfo();
3460   MachineRegisterInfo &MRI = MF->getRegInfo();
3461   const DebugLoc &DL = MI.getDebugLoc();
3462   MachineBasicBlock::iterator I(&MI);
3463 
3464   const auto *BoolXExecRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3465   Register DstReg = MI.getOperand(0).getReg();
3466   Register SaveExec = MRI.createVirtualRegister(BoolXExecRC);
3467   Register TmpExec = MRI.createVirtualRegister(BoolXExecRC);
3468   unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3469   unsigned MovExecOpc = ST.isWave32() ? AMDGPU::S_MOV_B32 : AMDGPU::S_MOV_B64;
3470 
3471   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), TmpExec);
3472 
3473   // Save the EXEC mask
3474   BuildMI(MBB, I, DL, TII->get(MovExecOpc), SaveExec)
3475     .addReg(Exec);
3476 
3477   MachineBasicBlock *LoopBB;
3478   MachineBasicBlock *RemainderBB;
3479   std::tie(LoopBB, RemainderBB) = splitBlockForLoop(MI, MBB, false);
3480 
3481   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3482 
3483   auto InsPt = emitLoadM0FromVGPRLoop(TII, MRI, MBB, *LoopBB, DL, *Idx,
3484                                       InitResultReg, DstReg, PhiReg, TmpExec,
3485                                       Offset, UseGPRIdxMode, IsIndirectSrc);
3486   MachineBasicBlock* LandingPad = MF->CreateMachineBasicBlock();
3487   MachineFunction::iterator MBBI(LoopBB);
3488   ++MBBI;
3489   MF->insert(MBBI, LandingPad);
3490   LoopBB->removeSuccessor(RemainderBB);
3491   LandingPad->addSuccessor(RemainderBB);
3492   LoopBB->addSuccessor(LandingPad);
3493   MachineBasicBlock::iterator First = LandingPad->begin();
3494   BuildMI(*LandingPad, First, DL, TII->get(MovExecOpc), Exec)
3495     .addReg(SaveExec);
3496 
3497   return InsPt;
3498 }
3499 
3500 // Returns subreg index, offset
3501 static std::pair<unsigned, int>
3502 computeIndirectRegAndOffset(const SIRegisterInfo &TRI,
3503                             const TargetRegisterClass *SuperRC,
3504                             unsigned VecReg,
3505                             int Offset) {
3506   int NumElts = TRI.getRegSizeInBits(*SuperRC) / 32;
3507 
3508   // Skip out of bounds offsets, or else we would end up using an undefined
3509   // register.
3510   if (Offset >= NumElts || Offset < 0)
3511     return std::make_pair(AMDGPU::sub0, Offset);
3512 
3513   return std::make_pair(SIRegisterInfo::getSubRegFromChannel(Offset), 0);
3514 }
3515 
3516 // Return true if the index is an SGPR and was set.
3517 static bool setM0ToIndexFromSGPR(const SIInstrInfo *TII,
3518                                  MachineRegisterInfo &MRI,
3519                                  MachineInstr &MI,
3520                                  int Offset,
3521                                  bool UseGPRIdxMode,
3522                                  bool IsIndirectSrc) {
3523   MachineBasicBlock *MBB = MI.getParent();
3524   const DebugLoc &DL = MI.getDebugLoc();
3525   MachineBasicBlock::iterator I(&MI);
3526 
3527   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3528   const TargetRegisterClass *IdxRC = MRI.getRegClass(Idx->getReg());
3529 
3530   assert(Idx->getReg() != AMDGPU::NoRegister);
3531 
3532   if (!TII->getRegisterInfo().isSGPRClass(IdxRC))
3533     return false;
3534 
3535   if (UseGPRIdxMode) {
3536     unsigned IdxMode = IsIndirectSrc ?
3537       AMDGPU::VGPRIndexMode::SRC0_ENABLE : AMDGPU::VGPRIndexMode::DST_ENABLE;
3538     if (Offset == 0) {
3539       MachineInstr *SetOn =
3540           BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3541               .add(*Idx)
3542               .addImm(IdxMode);
3543 
3544       SetOn->getOperand(3).setIsUndef();
3545     } else {
3546       Register Tmp = MRI.createVirtualRegister(&AMDGPU::SReg_32_XM0RegClass);
3547       BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), Tmp)
3548           .add(*Idx)
3549           .addImm(Offset);
3550       MachineInstr *SetOn =
3551         BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_ON))
3552         .addReg(Tmp, RegState::Kill)
3553         .addImm(IdxMode);
3554 
3555       SetOn->getOperand(3).setIsUndef();
3556     }
3557 
3558     return true;
3559   }
3560 
3561   if (Offset == 0) {
3562     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3563       .add(*Idx);
3564   } else {
3565     BuildMI(*MBB, I, DL, TII->get(AMDGPU::S_ADD_I32), AMDGPU::M0)
3566       .add(*Idx)
3567       .addImm(Offset);
3568   }
3569 
3570   return true;
3571 }
3572 
3573 // Control flow needs to be inserted if indexing with a VGPR.
3574 static MachineBasicBlock *emitIndirectSrc(MachineInstr &MI,
3575                                           MachineBasicBlock &MBB,
3576                                           const GCNSubtarget &ST) {
3577   const SIInstrInfo *TII = ST.getInstrInfo();
3578   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3579   MachineFunction *MF = MBB.getParent();
3580   MachineRegisterInfo &MRI = MF->getRegInfo();
3581 
3582   Register Dst = MI.getOperand(0).getReg();
3583   Register SrcReg = TII->getNamedOperand(MI, AMDGPU::OpName::src)->getReg();
3584   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3585 
3586   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcReg);
3587 
3588   unsigned SubReg;
3589   std::tie(SubReg, Offset)
3590     = computeIndirectRegAndOffset(TRI, VecRC, SrcReg, Offset);
3591 
3592   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3593 
3594   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, true)) {
3595     MachineBasicBlock::iterator I(&MI);
3596     const DebugLoc &DL = MI.getDebugLoc();
3597 
3598     if (UseGPRIdxMode) {
3599       // TODO: Look at the uses to avoid the copy. This may require rescheduling
3600       // to avoid interfering with other uses, so probably requires a new
3601       // optimization pass.
3602       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3603         .addReg(SrcReg, RegState::Undef, SubReg)
3604         .addReg(SrcReg, RegState::Implicit)
3605         .addReg(AMDGPU::M0, RegState::Implicit);
3606       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3607     } else {
3608       BuildMI(MBB, I, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3609         .addReg(SrcReg, RegState::Undef, SubReg)
3610         .addReg(SrcReg, RegState::Implicit);
3611     }
3612 
3613     MI.eraseFromParent();
3614 
3615     return &MBB;
3616   }
3617 
3618   const DebugLoc &DL = MI.getDebugLoc();
3619   MachineBasicBlock::iterator I(&MI);
3620 
3621   Register PhiReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3622   Register InitReg = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3623 
3624   BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), InitReg);
3625 
3626   auto InsPt = loadM0FromVGPR(TII, MBB, MI, InitReg, PhiReg,
3627                               Offset, UseGPRIdxMode, true);
3628   MachineBasicBlock *LoopBB = InsPt->getParent();
3629 
3630   if (UseGPRIdxMode) {
3631     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOV_B32_e32), Dst)
3632       .addReg(SrcReg, RegState::Undef, SubReg)
3633       .addReg(SrcReg, RegState::Implicit)
3634       .addReg(AMDGPU::M0, RegState::Implicit);
3635     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3636   } else {
3637     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::V_MOVRELS_B32_e32), Dst)
3638       .addReg(SrcReg, RegState::Undef, SubReg)
3639       .addReg(SrcReg, RegState::Implicit);
3640   }
3641 
3642   MI.eraseFromParent();
3643 
3644   return LoopBB;
3645 }
3646 
3647 static MachineBasicBlock *emitIndirectDst(MachineInstr &MI,
3648                                           MachineBasicBlock &MBB,
3649                                           const GCNSubtarget &ST) {
3650   const SIInstrInfo *TII = ST.getInstrInfo();
3651   const SIRegisterInfo &TRI = TII->getRegisterInfo();
3652   MachineFunction *MF = MBB.getParent();
3653   MachineRegisterInfo &MRI = MF->getRegInfo();
3654 
3655   Register Dst = MI.getOperand(0).getReg();
3656   const MachineOperand *SrcVec = TII->getNamedOperand(MI, AMDGPU::OpName::src);
3657   const MachineOperand *Idx = TII->getNamedOperand(MI, AMDGPU::OpName::idx);
3658   const MachineOperand *Val = TII->getNamedOperand(MI, AMDGPU::OpName::val);
3659   int Offset = TII->getNamedOperand(MI, AMDGPU::OpName::offset)->getImm();
3660   const TargetRegisterClass *VecRC = MRI.getRegClass(SrcVec->getReg());
3661 
3662   // This can be an immediate, but will be folded later.
3663   assert(Val->getReg());
3664 
3665   unsigned SubReg;
3666   std::tie(SubReg, Offset) = computeIndirectRegAndOffset(TRI, VecRC,
3667                                                          SrcVec->getReg(),
3668                                                          Offset);
3669   const bool UseGPRIdxMode = ST.useVGPRIndexMode();
3670 
3671   if (Idx->getReg() == AMDGPU::NoRegister) {
3672     MachineBasicBlock::iterator I(&MI);
3673     const DebugLoc &DL = MI.getDebugLoc();
3674 
3675     assert(Offset == 0);
3676 
3677     BuildMI(MBB, I, DL, TII->get(TargetOpcode::INSERT_SUBREG), Dst)
3678         .add(*SrcVec)
3679         .add(*Val)
3680         .addImm(SubReg);
3681 
3682     MI.eraseFromParent();
3683     return &MBB;
3684   }
3685 
3686   const MCInstrDesc &MovRelDesc
3687     = TII->getIndirectRegWritePseudo(TRI.getRegSizeInBits(*VecRC), 32, false);
3688 
3689   if (setM0ToIndexFromSGPR(TII, MRI, MI, Offset, UseGPRIdxMode, false)) {
3690     MachineBasicBlock::iterator I(&MI);
3691     const DebugLoc &DL = MI.getDebugLoc();
3692     BuildMI(MBB, I, DL, MovRelDesc, Dst)
3693       .addReg(SrcVec->getReg())
3694       .add(*Val)
3695       .addImm(SubReg);
3696     if (UseGPRIdxMode)
3697       BuildMI(MBB, I, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3698 
3699     MI.eraseFromParent();
3700     return &MBB;
3701   }
3702 
3703   if (Val->isReg())
3704     MRI.clearKillFlags(Val->getReg());
3705 
3706   const DebugLoc &DL = MI.getDebugLoc();
3707 
3708   Register PhiReg = MRI.createVirtualRegister(VecRC);
3709 
3710   auto InsPt = loadM0FromVGPR(TII, MBB, MI, SrcVec->getReg(), PhiReg,
3711                               Offset, UseGPRIdxMode, false);
3712   MachineBasicBlock *LoopBB = InsPt->getParent();
3713 
3714   BuildMI(*LoopBB, InsPt, DL, MovRelDesc, Dst)
3715     .addReg(PhiReg)
3716     .add(*Val)
3717     .addImm(AMDGPU::sub0);
3718   if (UseGPRIdxMode)
3719     BuildMI(*LoopBB, InsPt, DL, TII->get(AMDGPU::S_SET_GPR_IDX_OFF));
3720 
3721   MI.eraseFromParent();
3722   return LoopBB;
3723 }
3724 
3725 MachineBasicBlock *SITargetLowering::EmitInstrWithCustomInserter(
3726   MachineInstr &MI, MachineBasicBlock *BB) const {
3727 
3728   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
3729   MachineFunction *MF = BB->getParent();
3730   SIMachineFunctionInfo *MFI = MF->getInfo<SIMachineFunctionInfo>();
3731 
3732   switch (MI.getOpcode()) {
3733   case AMDGPU::S_UADDO_PSEUDO:
3734   case AMDGPU::S_USUBO_PSEUDO: {
3735     const DebugLoc &DL = MI.getDebugLoc();
3736     MachineOperand &Dest0 = MI.getOperand(0);
3737     MachineOperand &Dest1 = MI.getOperand(1);
3738     MachineOperand &Src0 = MI.getOperand(2);
3739     MachineOperand &Src1 = MI.getOperand(3);
3740 
3741     unsigned Opc = (MI.getOpcode() == AMDGPU::S_UADDO_PSEUDO)
3742                        ? AMDGPU::S_ADD_I32
3743                        : AMDGPU::S_SUB_I32;
3744     BuildMI(*BB, MI, DL, TII->get(Opc), Dest0.getReg()).add(Src0).add(Src1);
3745 
3746     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CSELECT_B64), Dest1.getReg())
3747         .addImm(1)
3748         .addImm(0);
3749 
3750     MI.eraseFromParent();
3751     return BB;
3752   }
3753   case AMDGPU::S_ADD_U64_PSEUDO:
3754   case AMDGPU::S_SUB_U64_PSEUDO: {
3755     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3756     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3757     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3758     const TargetRegisterClass *BoolRC = TRI->getBoolRC();
3759     const DebugLoc &DL = MI.getDebugLoc();
3760 
3761     MachineOperand &Dest = MI.getOperand(0);
3762     MachineOperand &Src0 = MI.getOperand(1);
3763     MachineOperand &Src1 = MI.getOperand(2);
3764 
3765     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3766     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3767 
3768     MachineOperand Src0Sub0 = TII->buildExtractSubRegOrImm(
3769         MI, MRI, Src0, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3770     MachineOperand Src0Sub1 = TII->buildExtractSubRegOrImm(
3771         MI, MRI, Src0, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3772 
3773     MachineOperand Src1Sub0 = TII->buildExtractSubRegOrImm(
3774         MI, MRI, Src1, BoolRC, AMDGPU::sub0, &AMDGPU::SReg_32RegClass);
3775     MachineOperand Src1Sub1 = TII->buildExtractSubRegOrImm(
3776         MI, MRI, Src1, BoolRC, AMDGPU::sub1, &AMDGPU::SReg_32RegClass);
3777 
3778     bool IsAdd = (MI.getOpcode() == AMDGPU::S_ADD_U64_PSEUDO);
3779 
3780     unsigned LoOpc = IsAdd ? AMDGPU::S_ADD_U32 : AMDGPU::S_SUB_U32;
3781     unsigned HiOpc = IsAdd ? AMDGPU::S_ADDC_U32 : AMDGPU::S_SUBB_U32;
3782     BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0).add(Src0Sub0).add(Src1Sub0);
3783     BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1).add(Src0Sub1).add(Src1Sub1);
3784     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3785         .addReg(DestSub0)
3786         .addImm(AMDGPU::sub0)
3787         .addReg(DestSub1)
3788         .addImm(AMDGPU::sub1);
3789     MI.eraseFromParent();
3790     return BB;
3791   }
3792   case AMDGPU::V_ADD_U64_PSEUDO:
3793   case AMDGPU::V_SUB_U64_PSEUDO: {
3794     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3795     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3796     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3797     const DebugLoc &DL = MI.getDebugLoc();
3798 
3799     bool IsAdd = (MI.getOpcode() == AMDGPU::V_ADD_U64_PSEUDO);
3800 
3801     const auto *CarryRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
3802 
3803     Register DestSub0 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3804     Register DestSub1 = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
3805 
3806     Register CarryReg = MRI.createVirtualRegister(CarryRC);
3807     Register DeadCarryReg = MRI.createVirtualRegister(CarryRC);
3808 
3809     MachineOperand &Dest = MI.getOperand(0);
3810     MachineOperand &Src0 = MI.getOperand(1);
3811     MachineOperand &Src1 = MI.getOperand(2);
3812 
3813     const TargetRegisterClass *Src0RC = Src0.isReg()
3814                                             ? MRI.getRegClass(Src0.getReg())
3815                                             : &AMDGPU::VReg_64RegClass;
3816     const TargetRegisterClass *Src1RC = Src1.isReg()
3817                                             ? MRI.getRegClass(Src1.getReg())
3818                                             : &AMDGPU::VReg_64RegClass;
3819 
3820     const TargetRegisterClass *Src0SubRC =
3821         TRI->getSubRegClass(Src0RC, AMDGPU::sub0);
3822     const TargetRegisterClass *Src1SubRC =
3823         TRI->getSubRegClass(Src1RC, AMDGPU::sub1);
3824 
3825     MachineOperand SrcReg0Sub0 = TII->buildExtractSubRegOrImm(
3826         MI, MRI, Src0, Src0RC, AMDGPU::sub0, Src0SubRC);
3827     MachineOperand SrcReg1Sub0 = TII->buildExtractSubRegOrImm(
3828         MI, MRI, Src1, Src1RC, AMDGPU::sub0, Src1SubRC);
3829 
3830     MachineOperand SrcReg0Sub1 = TII->buildExtractSubRegOrImm(
3831         MI, MRI, Src0, Src0RC, AMDGPU::sub1, Src0SubRC);
3832     MachineOperand SrcReg1Sub1 = TII->buildExtractSubRegOrImm(
3833         MI, MRI, Src1, Src1RC, AMDGPU::sub1, Src1SubRC);
3834 
3835     unsigned LoOpc = IsAdd ? AMDGPU::V_ADD_I32_e64 : AMDGPU::V_SUB_I32_e64;
3836     MachineInstr *LoHalf = BuildMI(*BB, MI, DL, TII->get(LoOpc), DestSub0)
3837                                .addReg(CarryReg, RegState::Define)
3838                                .add(SrcReg0Sub0)
3839                                .add(SrcReg1Sub0)
3840                                .addImm(0); // clamp bit
3841 
3842     unsigned HiOpc = IsAdd ? AMDGPU::V_ADDC_U32_e64 : AMDGPU::V_SUBB_U32_e64;
3843     MachineInstr *HiHalf =
3844         BuildMI(*BB, MI, DL, TII->get(HiOpc), DestSub1)
3845             .addReg(DeadCarryReg, RegState::Define | RegState::Dead)
3846             .add(SrcReg0Sub1)
3847             .add(SrcReg1Sub1)
3848             .addReg(CarryReg, RegState::Kill)
3849             .addImm(0); // clamp bit
3850 
3851     BuildMI(*BB, MI, DL, TII->get(TargetOpcode::REG_SEQUENCE), Dest.getReg())
3852         .addReg(DestSub0)
3853         .addImm(AMDGPU::sub0)
3854         .addReg(DestSub1)
3855         .addImm(AMDGPU::sub1);
3856     TII->legalizeOperands(*LoHalf);
3857     TII->legalizeOperands(*HiHalf);
3858     MI.eraseFromParent();
3859     return BB;
3860   }
3861   case AMDGPU::S_ADD_CO_PSEUDO:
3862   case AMDGPU::S_SUB_CO_PSEUDO: {
3863     // This pseudo has a chance to be selected
3864     // only from uniform add/subcarry node. All the VGPR operands
3865     // therefore assumed to be splat vectors.
3866     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
3867     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
3868     const SIRegisterInfo *TRI = ST.getRegisterInfo();
3869     MachineBasicBlock::iterator MII = MI;
3870     const DebugLoc &DL = MI.getDebugLoc();
3871     MachineOperand &Dest = MI.getOperand(0);
3872     MachineOperand &Src0 = MI.getOperand(2);
3873     MachineOperand &Src1 = MI.getOperand(3);
3874     MachineOperand &Src2 = MI.getOperand(4);
3875     unsigned Opc = (MI.getOpcode() == AMDGPU::S_ADD_CO_PSEUDO)
3876                        ? AMDGPU::S_ADDC_U32
3877                        : AMDGPU::S_SUBB_U32;
3878     if (Src0.isReg() && TRI->isVectorRegister(MRI, Src0.getReg())) {
3879       Register RegOp0 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3880       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp0)
3881           .addReg(Src0.getReg());
3882       Src0.setReg(RegOp0);
3883     }
3884     if (Src1.isReg() && TRI->isVectorRegister(MRI, Src1.getReg())) {
3885       Register RegOp1 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3886       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp1)
3887           .addReg(Src1.getReg());
3888       Src1.setReg(RegOp1);
3889     }
3890     Register RegOp2 = MRI.createVirtualRegister(&AMDGPU::SReg_32RegClass);
3891     if (TRI->isVectorRegister(MRI, Src2.getReg())) {
3892       BuildMI(*BB, MII, DL, TII->get(AMDGPU::V_READFIRSTLANE_B32), RegOp2)
3893           .addReg(Src2.getReg());
3894       Src2.setReg(RegOp2);
3895     }
3896 
3897     if (TRI->getRegSizeInBits(*MRI.getRegClass(Src2.getReg())) == 64) {
3898       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMP_LG_U64))
3899           .addReg(Src2.getReg())
3900           .addImm(0);
3901     } else {
3902       BuildMI(*BB, MII, DL, TII->get(AMDGPU::S_CMPK_LG_U32))
3903           .addReg(Src2.getReg())
3904           .addImm(0);
3905     }
3906 
3907     BuildMI(*BB, MII, DL, TII->get(Opc), Dest.getReg()).add(Src0).add(Src1);
3908     MI.eraseFromParent();
3909     return BB;
3910   }
3911   case AMDGPU::SI_INIT_M0: {
3912     BuildMI(*BB, MI.getIterator(), MI.getDebugLoc(),
3913             TII->get(AMDGPU::S_MOV_B32), AMDGPU::M0)
3914         .add(MI.getOperand(0));
3915     MI.eraseFromParent();
3916     return BB;
3917   }
3918   case AMDGPU::SI_INIT_EXEC:
3919     // This should be before all vector instructions.
3920     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B64),
3921             AMDGPU::EXEC)
3922         .addImm(MI.getOperand(0).getImm());
3923     MI.eraseFromParent();
3924     return BB;
3925 
3926   case AMDGPU::SI_INIT_EXEC_LO:
3927     // This should be before all vector instructions.
3928     BuildMI(*BB, &*BB->begin(), MI.getDebugLoc(), TII->get(AMDGPU::S_MOV_B32),
3929             AMDGPU::EXEC_LO)
3930         .addImm(MI.getOperand(0).getImm());
3931     MI.eraseFromParent();
3932     return BB;
3933 
3934   case AMDGPU::SI_INIT_EXEC_FROM_INPUT: {
3935     // Extract the thread count from an SGPR input and set EXEC accordingly.
3936     // Since BFM can't shift by 64, handle that case with CMP + CMOV.
3937     //
3938     // S_BFE_U32 count, input, {shift, 7}
3939     // S_BFM_B64 exec, count, 0
3940     // S_CMP_EQ_U32 count, 64
3941     // S_CMOV_B64 exec, -1
3942     MachineInstr *FirstMI = &*BB->begin();
3943     MachineRegisterInfo &MRI = MF->getRegInfo();
3944     Register InputReg = MI.getOperand(0).getReg();
3945     Register CountReg = MRI.createVirtualRegister(&AMDGPU::SGPR_32RegClass);
3946     bool Found = false;
3947 
3948     // Move the COPY of the input reg to the beginning, so that we can use it.
3949     for (auto I = BB->begin(); I != &MI; I++) {
3950       if (I->getOpcode() != TargetOpcode::COPY ||
3951           I->getOperand(0).getReg() != InputReg)
3952         continue;
3953 
3954       if (I == FirstMI) {
3955         FirstMI = &*++BB->begin();
3956       } else {
3957         I->removeFromParent();
3958         BB->insert(FirstMI, &*I);
3959       }
3960       Found = true;
3961       break;
3962     }
3963     assert(Found);
3964     (void)Found;
3965 
3966     // This should be before all vector instructions.
3967     unsigned Mask = (getSubtarget()->getWavefrontSize() << 1) - 1;
3968     bool isWave32 = getSubtarget()->isWave32();
3969     unsigned Exec = isWave32 ? AMDGPU::EXEC_LO : AMDGPU::EXEC;
3970     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_BFE_U32), CountReg)
3971         .addReg(InputReg)
3972         .addImm((MI.getOperand(1).getImm() & Mask) | 0x70000);
3973     BuildMI(*BB, FirstMI, DebugLoc(),
3974             TII->get(isWave32 ? AMDGPU::S_BFM_B32 : AMDGPU::S_BFM_B64),
3975             Exec)
3976         .addReg(CountReg)
3977         .addImm(0);
3978     BuildMI(*BB, FirstMI, DebugLoc(), TII->get(AMDGPU::S_CMP_EQ_U32))
3979         .addReg(CountReg, RegState::Kill)
3980         .addImm(getSubtarget()->getWavefrontSize());
3981     BuildMI(*BB, FirstMI, DebugLoc(),
3982             TII->get(isWave32 ? AMDGPU::S_CMOV_B32 : AMDGPU::S_CMOV_B64),
3983             Exec)
3984         .addImm(-1);
3985     MI.eraseFromParent();
3986     return BB;
3987   }
3988 
3989   case AMDGPU::GET_GROUPSTATICSIZE: {
3990     assert(getTargetMachine().getTargetTriple().getOS() == Triple::AMDHSA ||
3991            getTargetMachine().getTargetTriple().getOS() == Triple::AMDPAL);
3992     DebugLoc DL = MI.getDebugLoc();
3993     BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_MOV_B32))
3994         .add(MI.getOperand(0))
3995         .addImm(MFI->getLDSSize());
3996     MI.eraseFromParent();
3997     return BB;
3998   }
3999   case AMDGPU::SI_INDIRECT_SRC_V1:
4000   case AMDGPU::SI_INDIRECT_SRC_V2:
4001   case AMDGPU::SI_INDIRECT_SRC_V4:
4002   case AMDGPU::SI_INDIRECT_SRC_V8:
4003   case AMDGPU::SI_INDIRECT_SRC_V16:
4004   case AMDGPU::SI_INDIRECT_SRC_V32:
4005     return emitIndirectSrc(MI, *BB, *getSubtarget());
4006   case AMDGPU::SI_INDIRECT_DST_V1:
4007   case AMDGPU::SI_INDIRECT_DST_V2:
4008   case AMDGPU::SI_INDIRECT_DST_V4:
4009   case AMDGPU::SI_INDIRECT_DST_V8:
4010   case AMDGPU::SI_INDIRECT_DST_V16:
4011   case AMDGPU::SI_INDIRECT_DST_V32:
4012     return emitIndirectDst(MI, *BB, *getSubtarget());
4013   case AMDGPU::SI_KILL_F32_COND_IMM_PSEUDO:
4014   case AMDGPU::SI_KILL_I1_PSEUDO:
4015     return splitKillBlock(MI, BB);
4016   case AMDGPU::V_CNDMASK_B64_PSEUDO: {
4017     MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4018     const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4019     const SIRegisterInfo *TRI = ST.getRegisterInfo();
4020 
4021     Register Dst = MI.getOperand(0).getReg();
4022     Register Src0 = MI.getOperand(1).getReg();
4023     Register Src1 = MI.getOperand(2).getReg();
4024     const DebugLoc &DL = MI.getDebugLoc();
4025     Register SrcCond = MI.getOperand(3).getReg();
4026 
4027     Register DstLo = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4028     Register DstHi = MRI.createVirtualRegister(&AMDGPU::VGPR_32RegClass);
4029     const auto *CondRC = TRI->getRegClass(AMDGPU::SReg_1_XEXECRegClassID);
4030     Register SrcCondCopy = MRI.createVirtualRegister(CondRC);
4031 
4032     BuildMI(*BB, MI, DL, TII->get(AMDGPU::COPY), SrcCondCopy)
4033       .addReg(SrcCond);
4034     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstLo)
4035       .addImm(0)
4036       .addReg(Src0, 0, AMDGPU::sub0)
4037       .addImm(0)
4038       .addReg(Src1, 0, AMDGPU::sub0)
4039       .addReg(SrcCondCopy);
4040     BuildMI(*BB, MI, DL, TII->get(AMDGPU::V_CNDMASK_B32_e64), DstHi)
4041       .addImm(0)
4042       .addReg(Src0, 0, AMDGPU::sub1)
4043       .addImm(0)
4044       .addReg(Src1, 0, AMDGPU::sub1)
4045       .addReg(SrcCondCopy);
4046 
4047     BuildMI(*BB, MI, DL, TII->get(AMDGPU::REG_SEQUENCE), Dst)
4048       .addReg(DstLo)
4049       .addImm(AMDGPU::sub0)
4050       .addReg(DstHi)
4051       .addImm(AMDGPU::sub1);
4052     MI.eraseFromParent();
4053     return BB;
4054   }
4055   case AMDGPU::SI_BR_UNDEF: {
4056     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4057     const DebugLoc &DL = MI.getDebugLoc();
4058     MachineInstr *Br = BuildMI(*BB, MI, DL, TII->get(AMDGPU::S_CBRANCH_SCC1))
4059                            .add(MI.getOperand(0));
4060     Br->getOperand(1).setIsUndef(true); // read undef SCC
4061     MI.eraseFromParent();
4062     return BB;
4063   }
4064   case AMDGPU::ADJCALLSTACKUP:
4065   case AMDGPU::ADJCALLSTACKDOWN: {
4066     const SIMachineFunctionInfo *Info = MF->getInfo<SIMachineFunctionInfo>();
4067     MachineInstrBuilder MIB(*MF, &MI);
4068 
4069     // Add an implicit use of the frame offset reg to prevent the restore copy
4070     // inserted after the call from being reorderd after stack operations in the
4071     // the caller's frame.
4072     MIB.addReg(Info->getStackPtrOffsetReg(), RegState::ImplicitDefine)
4073         .addReg(Info->getStackPtrOffsetReg(), RegState::Implicit)
4074         .addReg(Info->getFrameOffsetReg(), RegState::Implicit);
4075     return BB;
4076   }
4077   case AMDGPU::SI_CALL_ISEL: {
4078     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
4079     const DebugLoc &DL = MI.getDebugLoc();
4080 
4081     unsigned ReturnAddrReg = TII->getRegisterInfo().getReturnAddressReg(*MF);
4082 
4083     MachineInstrBuilder MIB;
4084     MIB = BuildMI(*BB, MI, DL, TII->get(AMDGPU::SI_CALL), ReturnAddrReg);
4085 
4086     for (unsigned I = 0, E = MI.getNumOperands(); I != E; ++I)
4087       MIB.add(MI.getOperand(I));
4088 
4089     MIB.cloneMemRefs(MI);
4090     MI.eraseFromParent();
4091     return BB;
4092   }
4093   case AMDGPU::V_ADD_I32_e32:
4094   case AMDGPU::V_SUB_I32_e32:
4095   case AMDGPU::V_SUBREV_I32_e32: {
4096     // TODO: Define distinct V_*_I32_Pseudo instructions instead.
4097     const DebugLoc &DL = MI.getDebugLoc();
4098     unsigned Opc = MI.getOpcode();
4099 
4100     bool NeedClampOperand = false;
4101     if (TII->pseudoToMCOpcode(Opc) == -1) {
4102       Opc = AMDGPU::getVOPe64(Opc);
4103       NeedClampOperand = true;
4104     }
4105 
4106     auto I = BuildMI(*BB, MI, DL, TII->get(Opc), MI.getOperand(0).getReg());
4107     if (TII->isVOP3(*I)) {
4108       const GCNSubtarget &ST = MF->getSubtarget<GCNSubtarget>();
4109       const SIRegisterInfo *TRI = ST.getRegisterInfo();
4110       I.addReg(TRI->getVCC(), RegState::Define);
4111     }
4112     I.add(MI.getOperand(1))
4113      .add(MI.getOperand(2));
4114     if (NeedClampOperand)
4115       I.addImm(0); // clamp bit for e64 encoding
4116 
4117     TII->legalizeOperands(*I);
4118 
4119     MI.eraseFromParent();
4120     return BB;
4121   }
4122   case AMDGPU::DS_GWS_INIT:
4123   case AMDGPU::DS_GWS_SEMA_V:
4124   case AMDGPU::DS_GWS_SEMA_BR:
4125   case AMDGPU::DS_GWS_SEMA_P:
4126   case AMDGPU::DS_GWS_SEMA_RELEASE_ALL:
4127   case AMDGPU::DS_GWS_BARRIER:
4128     // A s_waitcnt 0 is required to be the instruction immediately following.
4129     if (getSubtarget()->hasGWSAutoReplay()) {
4130       bundleInstWithWaitcnt(MI);
4131       return BB;
4132     }
4133 
4134     return emitGWSMemViolTestLoop(MI, BB);
4135   case AMDGPU::S_SETREG_B32: {
4136     if (!getSubtarget()->hasDenormModeInst())
4137       return BB;
4138 
4139     // Try to optimize cases that only set the denormal mode or rounding mode.
4140     //
4141     // If the s_setreg_b32 fully sets all of the bits in the rounding mode or
4142     // denormal mode to a constant, we can use s_round_mode or s_denorm_mode
4143     // instead.
4144     //
4145     // FIXME: This could be predicates on the immediate, but tablegen doesn't
4146     // allow you to have a no side effect instruction in the output of a
4147     // sideeffecting pattern.
4148 
4149     // TODO: Should also emit a no side effects pseudo if only FP bits are
4150     // touched, even if not all of them or to a variable.
4151     unsigned ID, Offset, Width;
4152     AMDGPU::Hwreg::decodeHwreg(MI.getOperand(1).getImm(), ID, Offset, Width);
4153     if (ID != AMDGPU::Hwreg::ID_MODE)
4154       return BB;
4155 
4156     const unsigned WidthMask = maskTrailingOnes<unsigned>(Width);
4157     const unsigned SetMask = WidthMask << Offset;
4158     unsigned SetDenormOp = 0;
4159     unsigned SetRoundOp = 0;
4160 
4161     // The dedicated instructions can only set the whole denorm or round mode at
4162     // once, not a subset of bits in either.
4163     if (Width == 8 && (SetMask & (AMDGPU::Hwreg::FP_ROUND_MASK |
4164                                   AMDGPU::Hwreg::FP_DENORM_MASK)) == SetMask) {
4165       // If this fully sets both the round and denorm mode, emit the two
4166       // dedicated instructions for these.
4167       assert(Offset == 0);
4168       SetRoundOp = AMDGPU::S_ROUND_MODE;
4169       SetDenormOp = AMDGPU::S_DENORM_MODE;
4170     } else if (Width == 4) {
4171       if ((SetMask & AMDGPU::Hwreg::FP_ROUND_MASK) == SetMask) {
4172         SetRoundOp = AMDGPU::S_ROUND_MODE;
4173         assert(Offset == 0);
4174       } else if ((SetMask & AMDGPU::Hwreg::FP_DENORM_MASK) == SetMask) {
4175         SetDenormOp = AMDGPU::S_DENORM_MODE;
4176         assert(Offset == 4);
4177       }
4178     }
4179 
4180     if (SetRoundOp || SetDenormOp) {
4181       MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
4182       MachineInstr *Def = MRI.getVRegDef(MI.getOperand(0).getReg());
4183       if (Def && Def->isMoveImmediate() && Def->getOperand(1).isImm()) {
4184         unsigned ImmVal = Def->getOperand(1).getImm();
4185         if (SetRoundOp) {
4186           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetRoundOp))
4187             .addImm(ImmVal & 0xf);
4188 
4189           // If we also have the denorm mode, get just the denorm mode bits.
4190           ImmVal >>= 4;
4191         }
4192 
4193         if (SetDenormOp) {
4194           BuildMI(*BB, MI, MI.getDebugLoc(), TII->get(SetDenormOp))
4195             .addImm(ImmVal & 0xf);
4196         }
4197 
4198         MI.eraseFromParent();
4199       }
4200     }
4201 
4202     return BB;
4203   }
4204   default:
4205     return AMDGPUTargetLowering::EmitInstrWithCustomInserter(MI, BB);
4206   }
4207 }
4208 
4209 bool SITargetLowering::hasBitPreservingFPLogic(EVT VT) const {
4210   return isTypeLegal(VT.getScalarType());
4211 }
4212 
4213 bool SITargetLowering::enableAggressiveFMAFusion(EVT VT) const {
4214   // This currently forces unfolding various combinations of fsub into fma with
4215   // free fneg'd operands. As long as we have fast FMA (controlled by
4216   // isFMAFasterThanFMulAndFAdd), we should perform these.
4217 
4218   // When fma is quarter rate, for f64 where add / sub are at best half rate,
4219   // most of these combines appear to be cycle neutral but save on instruction
4220   // count / code size.
4221   return true;
4222 }
4223 
4224 EVT SITargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &Ctx,
4225                                          EVT VT) const {
4226   if (!VT.isVector()) {
4227     return MVT::i1;
4228   }
4229   return EVT::getVectorVT(Ctx, MVT::i1, VT.getVectorNumElements());
4230 }
4231 
4232 MVT SITargetLowering::getScalarShiftAmountTy(const DataLayout &, EVT VT) const {
4233   // TODO: Should i16 be used always if legal? For now it would force VALU
4234   // shifts.
4235   return (VT == MVT::i16) ? MVT::i16 : MVT::i32;
4236 }
4237 
4238 // Answering this is somewhat tricky and depends on the specific device which
4239 // have different rates for fma or all f64 operations.
4240 //
4241 // v_fma_f64 and v_mul_f64 always take the same number of cycles as each other
4242 // regardless of which device (although the number of cycles differs between
4243 // devices), so it is always profitable for f64.
4244 //
4245 // v_fma_f32 takes 4 or 16 cycles depending on the device, so it is profitable
4246 // only on full rate devices. Normally, we should prefer selecting v_mad_f32
4247 // which we can always do even without fused FP ops since it returns the same
4248 // result as the separate operations and since it is always full
4249 // rate. Therefore, we lie and report that it is not faster for f32. v_mad_f32
4250 // however does not support denormals, so we do report fma as faster if we have
4251 // a fast fma device and require denormals.
4252 //
4253 bool SITargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
4254                                                   EVT VT) const {
4255   VT = VT.getScalarType();
4256 
4257   switch (VT.getSimpleVT().SimpleTy) {
4258   case MVT::f32: {
4259     // This is as fast on some subtargets. However, we always have full rate f32
4260     // mad available which returns the same result as the separate operations
4261     // which we should prefer over fma. We can't use this if we want to support
4262     // denormals, so only report this in these cases.
4263     if (hasFP32Denormals(MF))
4264       return Subtarget->hasFastFMAF32() || Subtarget->hasDLInsts();
4265 
4266     // If the subtarget has v_fmac_f32, that's just as good as v_mac_f32.
4267     return Subtarget->hasFastFMAF32() && Subtarget->hasDLInsts();
4268   }
4269   case MVT::f64:
4270     return true;
4271   case MVT::f16:
4272     return Subtarget->has16BitInsts() && hasFP64FP16Denormals(MF);
4273   default:
4274     break;
4275   }
4276 
4277   return false;
4278 }
4279 
4280 bool SITargetLowering::isFMADLegal(const SelectionDAG &DAG,
4281                                    const SDNode *N) const {
4282   // TODO: Check future ftz flag
4283   // v_mad_f32/v_mac_f32 do not support denormals.
4284   EVT VT = N->getValueType(0);
4285   if (VT == MVT::f32)
4286     return !hasFP32Denormals(DAG.getMachineFunction());
4287   if (VT == MVT::f16) {
4288     return Subtarget->hasMadF16() &&
4289            !hasFP64FP16Denormals(DAG.getMachineFunction());
4290   }
4291 
4292   return false;
4293 }
4294 
4295 //===----------------------------------------------------------------------===//
4296 // Custom DAG Lowering Operations
4297 //===----------------------------------------------------------------------===//
4298 
4299 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4300 // wider vector type is legal.
4301 SDValue SITargetLowering::splitUnaryVectorOp(SDValue Op,
4302                                              SelectionDAG &DAG) const {
4303   unsigned Opc = Op.getOpcode();
4304   EVT VT = Op.getValueType();
4305   assert(VT == MVT::v4f16 || VT == MVT::v4i16);
4306 
4307   SDValue Lo, Hi;
4308   std::tie(Lo, Hi) = DAG.SplitVectorOperand(Op.getNode(), 0);
4309 
4310   SDLoc SL(Op);
4311   SDValue OpLo = DAG.getNode(Opc, SL, Lo.getValueType(), Lo,
4312                              Op->getFlags());
4313   SDValue OpHi = DAG.getNode(Opc, SL, Hi.getValueType(), Hi,
4314                              Op->getFlags());
4315 
4316   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4317 }
4318 
4319 // Work around LegalizeDAG doing the wrong thing and fully scalarizing if the
4320 // wider vector type is legal.
4321 SDValue SITargetLowering::splitBinaryVectorOp(SDValue Op,
4322                                               SelectionDAG &DAG) const {
4323   unsigned Opc = Op.getOpcode();
4324   EVT VT = Op.getValueType();
4325   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4326 
4327   SDValue Lo0, Hi0;
4328   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4329   SDValue Lo1, Hi1;
4330   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4331 
4332   SDLoc SL(Op);
4333 
4334   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1,
4335                              Op->getFlags());
4336   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1,
4337                              Op->getFlags());
4338 
4339   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4340 }
4341 
4342 SDValue SITargetLowering::splitTernaryVectorOp(SDValue Op,
4343                                               SelectionDAG &DAG) const {
4344   unsigned Opc = Op.getOpcode();
4345   EVT VT = Op.getValueType();
4346   assert(VT == MVT::v4i16 || VT == MVT::v4f16);
4347 
4348   SDValue Lo0, Hi0;
4349   std::tie(Lo0, Hi0) = DAG.SplitVectorOperand(Op.getNode(), 0);
4350   SDValue Lo1, Hi1;
4351   std::tie(Lo1, Hi1) = DAG.SplitVectorOperand(Op.getNode(), 1);
4352   SDValue Lo2, Hi2;
4353   std::tie(Lo2, Hi2) = DAG.SplitVectorOperand(Op.getNode(), 2);
4354 
4355   SDLoc SL(Op);
4356 
4357   SDValue OpLo = DAG.getNode(Opc, SL, Lo0.getValueType(), Lo0, Lo1, Lo2,
4358                              Op->getFlags());
4359   SDValue OpHi = DAG.getNode(Opc, SL, Hi0.getValueType(), Hi0, Hi1, Hi2,
4360                              Op->getFlags());
4361 
4362   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), VT, OpLo, OpHi);
4363 }
4364 
4365 
4366 SDValue SITargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
4367   switch (Op.getOpcode()) {
4368   default: return AMDGPUTargetLowering::LowerOperation(Op, DAG);
4369   case ISD::BRCOND: return LowerBRCOND(Op, DAG);
4370   case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
4371   case ISD::LOAD: {
4372     SDValue Result = LowerLOAD(Op, DAG);
4373     assert((!Result.getNode() ||
4374             Result.getNode()->getNumValues() == 2) &&
4375            "Load should return a value and a chain");
4376     return Result;
4377   }
4378 
4379   case ISD::FSIN:
4380   case ISD::FCOS:
4381     return LowerTrig(Op, DAG);
4382   case ISD::SELECT: return LowerSELECT(Op, DAG);
4383   case ISD::FDIV: return LowerFDIV(Op, DAG);
4384   case ISD::ATOMIC_CMP_SWAP: return LowerATOMIC_CMP_SWAP(Op, DAG);
4385   case ISD::STORE: return LowerSTORE(Op, DAG);
4386   case ISD::GlobalAddress: {
4387     MachineFunction &MF = DAG.getMachineFunction();
4388     SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
4389     return LowerGlobalAddress(MFI, Op, DAG);
4390   }
4391   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
4392   case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
4393   case ISD::INTRINSIC_VOID: return LowerINTRINSIC_VOID(Op, DAG);
4394   case ISD::ADDRSPACECAST: return lowerADDRSPACECAST(Op, DAG);
4395   case ISD::INSERT_SUBVECTOR:
4396     return lowerINSERT_SUBVECTOR(Op, DAG);
4397   case ISD::INSERT_VECTOR_ELT:
4398     return lowerINSERT_VECTOR_ELT(Op, DAG);
4399   case ISD::EXTRACT_VECTOR_ELT:
4400     return lowerEXTRACT_VECTOR_ELT(Op, DAG);
4401   case ISD::VECTOR_SHUFFLE:
4402     return lowerVECTOR_SHUFFLE(Op, DAG);
4403   case ISD::BUILD_VECTOR:
4404     return lowerBUILD_VECTOR(Op, DAG);
4405   case ISD::FP_ROUND:
4406     return lowerFP_ROUND(Op, DAG);
4407   case ISD::TRAP:
4408     return lowerTRAP(Op, DAG);
4409   case ISD::DEBUGTRAP:
4410     return lowerDEBUGTRAP(Op, DAG);
4411   case ISD::FABS:
4412   case ISD::FNEG:
4413   case ISD::FCANONICALIZE:
4414   case ISD::BSWAP:
4415     return splitUnaryVectorOp(Op, DAG);
4416   case ISD::FMINNUM:
4417   case ISD::FMAXNUM:
4418     return lowerFMINNUM_FMAXNUM(Op, DAG);
4419   case ISD::FMA:
4420     return splitTernaryVectorOp(Op, DAG);
4421   case ISD::SHL:
4422   case ISD::SRA:
4423   case ISD::SRL:
4424   case ISD::ADD:
4425   case ISD::SUB:
4426   case ISD::MUL:
4427   case ISD::SMIN:
4428   case ISD::SMAX:
4429   case ISD::UMIN:
4430   case ISD::UMAX:
4431   case ISD::FADD:
4432   case ISD::FMUL:
4433   case ISD::FMINNUM_IEEE:
4434   case ISD::FMAXNUM_IEEE:
4435     return splitBinaryVectorOp(Op, DAG);
4436   case ISD::SMULO:
4437   case ISD::UMULO:
4438     return lowerXMULO(Op, DAG);
4439   case ISD::DYNAMIC_STACKALLOC:
4440     return LowerDYNAMIC_STACKALLOC(Op, DAG);
4441   }
4442   return SDValue();
4443 }
4444 
4445 static SDValue adjustLoadValueTypeImpl(SDValue Result, EVT LoadVT,
4446                                        const SDLoc &DL,
4447                                        SelectionDAG &DAG, bool Unpacked) {
4448   if (!LoadVT.isVector())
4449     return Result;
4450 
4451   if (Unpacked) { // From v2i32/v4i32 back to v2f16/v4f16.
4452     // Truncate to v2i16/v4i16.
4453     EVT IntLoadVT = LoadVT.changeTypeToInteger();
4454 
4455     // Workaround legalizer not scalarizing truncate after vector op
4456     // legalization byt not creating intermediate vector trunc.
4457     SmallVector<SDValue, 4> Elts;
4458     DAG.ExtractVectorElements(Result, Elts);
4459     for (SDValue &Elt : Elts)
4460       Elt = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Elt);
4461 
4462     Result = DAG.getBuildVector(IntLoadVT, DL, Elts);
4463 
4464     // Bitcast to original type (v2f16/v4f16).
4465     return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4466   }
4467 
4468   // Cast back to the original packed type.
4469   return DAG.getNode(ISD::BITCAST, DL, LoadVT, Result);
4470 }
4471 
4472 SDValue SITargetLowering::adjustLoadValueType(unsigned Opcode,
4473                                               MemSDNode *M,
4474                                               SelectionDAG &DAG,
4475                                               ArrayRef<SDValue> Ops,
4476                                               bool IsIntrinsic) const {
4477   SDLoc DL(M);
4478 
4479   bool Unpacked = Subtarget->hasUnpackedD16VMem();
4480   EVT LoadVT = M->getValueType(0);
4481 
4482   EVT EquivLoadVT = LoadVT;
4483   if (Unpacked && LoadVT.isVector()) {
4484     EquivLoadVT = LoadVT.isVector() ?
4485       EVT::getVectorVT(*DAG.getContext(), MVT::i32,
4486                        LoadVT.getVectorNumElements()) : LoadVT;
4487   }
4488 
4489   // Change from v4f16/v2f16 to EquivLoadVT.
4490   SDVTList VTList = DAG.getVTList(EquivLoadVT, MVT::Other);
4491 
4492   SDValue Load
4493     = DAG.getMemIntrinsicNode(
4494       IsIntrinsic ? (unsigned)ISD::INTRINSIC_W_CHAIN : Opcode, DL,
4495       VTList, Ops, M->getMemoryVT(),
4496       M->getMemOperand());
4497   if (!Unpacked) // Just adjusted the opcode.
4498     return Load;
4499 
4500   SDValue Adjusted = adjustLoadValueTypeImpl(Load, LoadVT, DL, DAG, Unpacked);
4501 
4502   return DAG.getMergeValues({ Adjusted, Load.getValue(1) }, DL);
4503 }
4504 
4505 SDValue SITargetLowering::lowerIntrinsicLoad(MemSDNode *M, bool IsFormat,
4506                                              SelectionDAG &DAG,
4507                                              ArrayRef<SDValue> Ops) const {
4508   SDLoc DL(M);
4509   EVT LoadVT = M->getValueType(0);
4510   EVT EltType = LoadVT.getScalarType();
4511   EVT IntVT = LoadVT.changeTypeToInteger();
4512 
4513   bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
4514 
4515   unsigned Opc =
4516       IsFormat ? AMDGPUISD::BUFFER_LOAD_FORMAT : AMDGPUISD::BUFFER_LOAD;
4517 
4518   if (IsD16) {
4519     return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16, M, DAG, Ops);
4520   }
4521 
4522   // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
4523   if (!IsD16 && !LoadVT.isVector() && EltType.getSizeInBits() < 32)
4524     return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
4525 
4526   if (isTypeLegal(LoadVT)) {
4527     return getMemIntrinsicNode(Opc, DL, M->getVTList(), Ops, IntVT,
4528                                M->getMemOperand(), DAG);
4529   }
4530 
4531   EVT CastVT = getEquivalentMemType(*DAG.getContext(), LoadVT);
4532   SDVTList VTList = DAG.getVTList(CastVT, MVT::Other);
4533   SDValue MemNode = getMemIntrinsicNode(Opc, DL, VTList, Ops, CastVT,
4534                                         M->getMemOperand(), DAG);
4535   return DAG.getMergeValues(
4536       {DAG.getNode(ISD::BITCAST, DL, LoadVT, MemNode), MemNode.getValue(1)},
4537       DL);
4538 }
4539 
4540 static SDValue lowerICMPIntrinsic(const SITargetLowering &TLI,
4541                                   SDNode *N, SelectionDAG &DAG) {
4542   EVT VT = N->getValueType(0);
4543   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4544   int CondCode = CD->getSExtValue();
4545   if (CondCode < ICmpInst::Predicate::FIRST_ICMP_PREDICATE ||
4546       CondCode > ICmpInst::Predicate::LAST_ICMP_PREDICATE)
4547     return DAG.getUNDEF(VT);
4548 
4549   ICmpInst::Predicate IcInput = static_cast<ICmpInst::Predicate>(CondCode);
4550 
4551   SDValue LHS = N->getOperand(1);
4552   SDValue RHS = N->getOperand(2);
4553 
4554   SDLoc DL(N);
4555 
4556   EVT CmpVT = LHS.getValueType();
4557   if (CmpVT == MVT::i16 && !TLI.isTypeLegal(MVT::i16)) {
4558     unsigned PromoteOp = ICmpInst::isSigned(IcInput) ?
4559       ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
4560     LHS = DAG.getNode(PromoteOp, DL, MVT::i32, LHS);
4561     RHS = DAG.getNode(PromoteOp, DL, MVT::i32, RHS);
4562   }
4563 
4564   ISD::CondCode CCOpcode = getICmpCondCode(IcInput);
4565 
4566   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4567   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4568 
4569   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, DL, CCVT, LHS, RHS,
4570                               DAG.getCondCode(CCOpcode));
4571   if (VT.bitsEq(CCVT))
4572     return SetCC;
4573   return DAG.getZExtOrTrunc(SetCC, DL, VT);
4574 }
4575 
4576 static SDValue lowerFCMPIntrinsic(const SITargetLowering &TLI,
4577                                   SDNode *N, SelectionDAG &DAG) {
4578   EVT VT = N->getValueType(0);
4579   const auto *CD = cast<ConstantSDNode>(N->getOperand(3));
4580 
4581   int CondCode = CD->getSExtValue();
4582   if (CondCode < FCmpInst::Predicate::FIRST_FCMP_PREDICATE ||
4583       CondCode > FCmpInst::Predicate::LAST_FCMP_PREDICATE) {
4584     return DAG.getUNDEF(VT);
4585   }
4586 
4587   SDValue Src0 = N->getOperand(1);
4588   SDValue Src1 = N->getOperand(2);
4589   EVT CmpVT = Src0.getValueType();
4590   SDLoc SL(N);
4591 
4592   if (CmpVT == MVT::f16 && !TLI.isTypeLegal(CmpVT)) {
4593     Src0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
4594     Src1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
4595   }
4596 
4597   FCmpInst::Predicate IcInput = static_cast<FCmpInst::Predicate>(CondCode);
4598   ISD::CondCode CCOpcode = getFCmpCondCode(IcInput);
4599   unsigned WavefrontSize = TLI.getSubtarget()->getWavefrontSize();
4600   EVT CCVT = EVT::getIntegerVT(*DAG.getContext(), WavefrontSize);
4601   SDValue SetCC = DAG.getNode(AMDGPUISD::SETCC, SL, CCVT, Src0,
4602                               Src1, DAG.getCondCode(CCOpcode));
4603   if (VT.bitsEq(CCVT))
4604     return SetCC;
4605   return DAG.getZExtOrTrunc(SetCC, SL, VT);
4606 }
4607 
4608 static SDValue lowerBALLOTIntrinsic(const SITargetLowering &TLI, SDNode *N,
4609                                     SelectionDAG &DAG) {
4610   EVT VT = N->getValueType(0);
4611   SDValue Src = N->getOperand(1);
4612   SDLoc SL(N);
4613 
4614   if (Src.getOpcode() == ISD::SETCC) {
4615     // (ballot (ISD::SETCC ...)) -> (AMDGPUISD::SETCC ...)
4616     return DAG.getNode(AMDGPUISD::SETCC, SL, VT, Src.getOperand(0),
4617                        Src.getOperand(1), Src.getOperand(2));
4618   }
4619   if (const ConstantSDNode *Arg = dyn_cast<ConstantSDNode>(Src)) {
4620     // (ballot 0) -> 0
4621     if (Arg->isNullValue())
4622       return DAG.getConstant(0, SL, VT);
4623 
4624     // (ballot 1) -> EXEC/EXEC_LO
4625     if (Arg->isOne()) {
4626       Register Exec;
4627       if (VT.getScalarSizeInBits() == 32)
4628         Exec = AMDGPU::EXEC_LO;
4629       else if (VT.getScalarSizeInBits() == 64)
4630         Exec = AMDGPU::EXEC;
4631       else
4632         return SDValue();
4633 
4634       return DAG.getCopyFromReg(DAG.getEntryNode(), SL, Exec, VT);
4635     }
4636   }
4637 
4638   // (ballot (i1 $src)) -> (AMDGPUISD::SETCC (i32 (zext $src)) (i32 0)
4639   // ISD::SETNE)
4640   return DAG.getNode(
4641       AMDGPUISD::SETCC, SL, VT, DAG.getZExtOrTrunc(Src, SL, MVT::i32),
4642       DAG.getConstant(0, SL, MVT::i32), DAG.getCondCode(ISD::SETNE));
4643 }
4644 
4645 void SITargetLowering::ReplaceNodeResults(SDNode *N,
4646                                           SmallVectorImpl<SDValue> &Results,
4647                                           SelectionDAG &DAG) const {
4648   switch (N->getOpcode()) {
4649   case ISD::INSERT_VECTOR_ELT: {
4650     if (SDValue Res = lowerINSERT_VECTOR_ELT(SDValue(N, 0), DAG))
4651       Results.push_back(Res);
4652     return;
4653   }
4654   case ISD::EXTRACT_VECTOR_ELT: {
4655     if (SDValue Res = lowerEXTRACT_VECTOR_ELT(SDValue(N, 0), DAG))
4656       Results.push_back(Res);
4657     return;
4658   }
4659   case ISD::INTRINSIC_WO_CHAIN: {
4660     unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
4661     switch (IID) {
4662     case Intrinsic::amdgcn_cvt_pkrtz: {
4663       SDValue Src0 = N->getOperand(1);
4664       SDValue Src1 = N->getOperand(2);
4665       SDLoc SL(N);
4666       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_PKRTZ_F16_F32, SL, MVT::i32,
4667                                 Src0, Src1);
4668       Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Cvt));
4669       return;
4670     }
4671     case Intrinsic::amdgcn_cvt_pknorm_i16:
4672     case Intrinsic::amdgcn_cvt_pknorm_u16:
4673     case Intrinsic::amdgcn_cvt_pk_i16:
4674     case Intrinsic::amdgcn_cvt_pk_u16: {
4675       SDValue Src0 = N->getOperand(1);
4676       SDValue Src1 = N->getOperand(2);
4677       SDLoc SL(N);
4678       unsigned Opcode;
4679 
4680       if (IID == Intrinsic::amdgcn_cvt_pknorm_i16)
4681         Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
4682       else if (IID == Intrinsic::amdgcn_cvt_pknorm_u16)
4683         Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
4684       else if (IID == Intrinsic::amdgcn_cvt_pk_i16)
4685         Opcode = AMDGPUISD::CVT_PK_I16_I32;
4686       else
4687         Opcode = AMDGPUISD::CVT_PK_U16_U32;
4688 
4689       EVT VT = N->getValueType(0);
4690       if (isTypeLegal(VT))
4691         Results.push_back(DAG.getNode(Opcode, SL, VT, Src0, Src1));
4692       else {
4693         SDValue Cvt = DAG.getNode(Opcode, SL, MVT::i32, Src0, Src1);
4694         Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, Cvt));
4695       }
4696       return;
4697     }
4698     }
4699     break;
4700   }
4701   case ISD::INTRINSIC_W_CHAIN: {
4702     if (SDValue Res = LowerINTRINSIC_W_CHAIN(SDValue(N, 0), DAG)) {
4703       if (Res.getOpcode() == ISD::MERGE_VALUES) {
4704         // FIXME: Hacky
4705         Results.push_back(Res.getOperand(0));
4706         Results.push_back(Res.getOperand(1));
4707       } else {
4708         Results.push_back(Res);
4709         Results.push_back(Res.getValue(1));
4710       }
4711       return;
4712     }
4713 
4714     break;
4715   }
4716   case ISD::SELECT: {
4717     SDLoc SL(N);
4718     EVT VT = N->getValueType(0);
4719     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VT);
4720     SDValue LHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(1));
4721     SDValue RHS = DAG.getNode(ISD::BITCAST, SL, NewVT, N->getOperand(2));
4722 
4723     EVT SelectVT = NewVT;
4724     if (NewVT.bitsLT(MVT::i32)) {
4725       LHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, LHS);
4726       RHS = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, RHS);
4727       SelectVT = MVT::i32;
4728     }
4729 
4730     SDValue NewSelect = DAG.getNode(ISD::SELECT, SL, SelectVT,
4731                                     N->getOperand(0), LHS, RHS);
4732 
4733     if (NewVT != SelectVT)
4734       NewSelect = DAG.getNode(ISD::TRUNCATE, SL, NewVT, NewSelect);
4735     Results.push_back(DAG.getNode(ISD::BITCAST, SL, VT, NewSelect));
4736     return;
4737   }
4738   case ISD::FNEG: {
4739     if (N->getValueType(0) != MVT::v2f16)
4740       break;
4741 
4742     SDLoc SL(N);
4743     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4744 
4745     SDValue Op = DAG.getNode(ISD::XOR, SL, MVT::i32,
4746                              BC,
4747                              DAG.getConstant(0x80008000, SL, MVT::i32));
4748     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4749     return;
4750   }
4751   case ISD::FABS: {
4752     if (N->getValueType(0) != MVT::v2f16)
4753       break;
4754 
4755     SDLoc SL(N);
4756     SDValue BC = DAG.getNode(ISD::BITCAST, SL, MVT::i32, N->getOperand(0));
4757 
4758     SDValue Op = DAG.getNode(ISD::AND, SL, MVT::i32,
4759                              BC,
4760                              DAG.getConstant(0x7fff7fff, SL, MVT::i32));
4761     Results.push_back(DAG.getNode(ISD::BITCAST, SL, MVT::v2f16, Op));
4762     return;
4763   }
4764   default:
4765     break;
4766   }
4767 }
4768 
4769 /// Helper function for LowerBRCOND
4770 static SDNode *findUser(SDValue Value, unsigned Opcode) {
4771 
4772   SDNode *Parent = Value.getNode();
4773   for (SDNode::use_iterator I = Parent->use_begin(), E = Parent->use_end();
4774        I != E; ++I) {
4775 
4776     if (I.getUse().get() != Value)
4777       continue;
4778 
4779     if (I->getOpcode() == Opcode)
4780       return *I;
4781   }
4782   return nullptr;
4783 }
4784 
4785 unsigned SITargetLowering::isCFIntrinsic(const SDNode *Intr) const {
4786   if (Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN) {
4787     switch (cast<ConstantSDNode>(Intr->getOperand(1))->getZExtValue()) {
4788     case Intrinsic::amdgcn_if:
4789       return AMDGPUISD::IF;
4790     case Intrinsic::amdgcn_else:
4791       return AMDGPUISD::ELSE;
4792     case Intrinsic::amdgcn_loop:
4793       return AMDGPUISD::LOOP;
4794     case Intrinsic::amdgcn_end_cf:
4795       llvm_unreachable("should not occur");
4796     default:
4797       return 0;
4798     }
4799   }
4800 
4801   // break, if_break, else_break are all only used as inputs to loop, not
4802   // directly as branch conditions.
4803   return 0;
4804 }
4805 
4806 bool SITargetLowering::shouldEmitFixup(const GlobalValue *GV) const {
4807   const Triple &TT = getTargetMachine().getTargetTriple();
4808   return (GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
4809           GV->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
4810          AMDGPU::shouldEmitConstantsToTextSection(TT);
4811 }
4812 
4813 bool SITargetLowering::shouldEmitGOTReloc(const GlobalValue *GV) const {
4814   // FIXME: Either avoid relying on address space here or change the default
4815   // address space for functions to avoid the explicit check.
4816   return (GV->getValueType()->isFunctionTy() ||
4817           !isNonGlobalAddrSpace(GV->getAddressSpace())) &&
4818          !shouldEmitFixup(GV) &&
4819          !getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV);
4820 }
4821 
4822 bool SITargetLowering::shouldEmitPCReloc(const GlobalValue *GV) const {
4823   return !shouldEmitFixup(GV) && !shouldEmitGOTReloc(GV);
4824 }
4825 
4826 bool SITargetLowering::shouldUseLDSConstAddress(const GlobalValue *GV) const {
4827   if (!GV->hasExternalLinkage())
4828     return true;
4829 
4830   const auto OS = getTargetMachine().getTargetTriple().getOS();
4831   return OS == Triple::AMDHSA || OS == Triple::AMDPAL;
4832 }
4833 
4834 /// This transforms the control flow intrinsics to get the branch destination as
4835 /// last parameter, also switches branch target with BR if the need arise
4836 SDValue SITargetLowering::LowerBRCOND(SDValue BRCOND,
4837                                       SelectionDAG &DAG) const {
4838   SDLoc DL(BRCOND);
4839 
4840   SDNode *Intr = BRCOND.getOperand(1).getNode();
4841   SDValue Target = BRCOND.getOperand(2);
4842   SDNode *BR = nullptr;
4843   SDNode *SetCC = nullptr;
4844 
4845   if (Intr->getOpcode() == ISD::SETCC) {
4846     // As long as we negate the condition everything is fine
4847     SetCC = Intr;
4848     Intr = SetCC->getOperand(0).getNode();
4849 
4850   } else {
4851     // Get the target from BR if we don't negate the condition
4852     BR = findUser(BRCOND, ISD::BR);
4853     assert(BR && "brcond missing unconditional branch user");
4854     Target = BR->getOperand(1);
4855   }
4856 
4857   unsigned CFNode = isCFIntrinsic(Intr);
4858   if (CFNode == 0) {
4859     // This is a uniform branch so we don't need to legalize.
4860     return BRCOND;
4861   }
4862 
4863   bool HaveChain = Intr->getOpcode() == ISD::INTRINSIC_VOID ||
4864                    Intr->getOpcode() == ISD::INTRINSIC_W_CHAIN;
4865 
4866   assert(!SetCC ||
4867         (SetCC->getConstantOperandVal(1) == 1 &&
4868          cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get() ==
4869                                                              ISD::SETNE));
4870 
4871   // operands of the new intrinsic call
4872   SmallVector<SDValue, 4> Ops;
4873   if (HaveChain)
4874     Ops.push_back(BRCOND.getOperand(0));
4875 
4876   Ops.append(Intr->op_begin() + (HaveChain ?  2 : 1), Intr->op_end());
4877   Ops.push_back(Target);
4878 
4879   ArrayRef<EVT> Res(Intr->value_begin() + 1, Intr->value_end());
4880 
4881   // build the new intrinsic call
4882   SDNode *Result = DAG.getNode(CFNode, DL, DAG.getVTList(Res), Ops).getNode();
4883 
4884   if (!HaveChain) {
4885     SDValue Ops[] =  {
4886       SDValue(Result, 0),
4887       BRCOND.getOperand(0)
4888     };
4889 
4890     Result = DAG.getMergeValues(Ops, DL).getNode();
4891   }
4892 
4893   if (BR) {
4894     // Give the branch instruction our target
4895     SDValue Ops[] = {
4896       BR->getOperand(0),
4897       BRCOND.getOperand(2)
4898     };
4899     SDValue NewBR = DAG.getNode(ISD::BR, DL, BR->getVTList(), Ops);
4900     DAG.ReplaceAllUsesWith(BR, NewBR.getNode());
4901   }
4902 
4903   SDValue Chain = SDValue(Result, Result->getNumValues() - 1);
4904 
4905   // Copy the intrinsic results to registers
4906   for (unsigned i = 1, e = Intr->getNumValues() - 1; i != e; ++i) {
4907     SDNode *CopyToReg = findUser(SDValue(Intr, i), ISD::CopyToReg);
4908     if (!CopyToReg)
4909       continue;
4910 
4911     Chain = DAG.getCopyToReg(
4912       Chain, DL,
4913       CopyToReg->getOperand(1),
4914       SDValue(Result, i - 1),
4915       SDValue());
4916 
4917     DAG.ReplaceAllUsesWith(SDValue(CopyToReg, 0), CopyToReg->getOperand(0));
4918   }
4919 
4920   // Remove the old intrinsic from the chain
4921   DAG.ReplaceAllUsesOfValueWith(
4922     SDValue(Intr, Intr->getNumValues() - 1),
4923     Intr->getOperand(0));
4924 
4925   return Chain;
4926 }
4927 
4928 SDValue SITargetLowering::LowerRETURNADDR(SDValue Op,
4929                                           SelectionDAG &DAG) const {
4930   MVT VT = Op.getSimpleValueType();
4931   SDLoc DL(Op);
4932   // Checking the depth
4933   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0)
4934     return DAG.getConstant(0, DL, VT);
4935 
4936   MachineFunction &MF = DAG.getMachineFunction();
4937   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4938   // Check for kernel and shader functions
4939   if (Info->isEntryFunction())
4940     return DAG.getConstant(0, DL, VT);
4941 
4942   MachineFrameInfo &MFI = MF.getFrameInfo();
4943   // There is a call to @llvm.returnaddress in this function
4944   MFI.setReturnAddressIsTaken(true);
4945 
4946   const SIRegisterInfo *TRI = getSubtarget()->getRegisterInfo();
4947   // Get the return address reg and mark it as an implicit live-in
4948   unsigned Reg = MF.addLiveIn(TRI->getReturnAddressReg(MF), getRegClassFor(VT, Op.getNode()->isDivergent()));
4949 
4950   return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
4951 }
4952 
4953 SDValue SITargetLowering::getFPExtOrFPRound(SelectionDAG &DAG,
4954                                             SDValue Op,
4955                                             const SDLoc &DL,
4956                                             EVT VT) const {
4957   return Op.getValueType().bitsLE(VT) ?
4958       DAG.getNode(ISD::FP_EXTEND, DL, VT, Op) :
4959     DAG.getNode(ISD::FP_ROUND, DL, VT, Op,
4960                 DAG.getTargetConstant(0, DL, MVT::i32));
4961 }
4962 
4963 SDValue SITargetLowering::lowerFP_ROUND(SDValue Op, SelectionDAG &DAG) const {
4964   assert(Op.getValueType() == MVT::f16 &&
4965          "Do not know how to custom lower FP_ROUND for non-f16 type");
4966 
4967   SDValue Src = Op.getOperand(0);
4968   EVT SrcVT = Src.getValueType();
4969   if (SrcVT != MVT::f64)
4970     return Op;
4971 
4972   SDLoc DL(Op);
4973 
4974   SDValue FpToFp16 = DAG.getNode(ISD::FP_TO_FP16, DL, MVT::i32, Src);
4975   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FpToFp16);
4976   return DAG.getNode(ISD::BITCAST, DL, MVT::f16, Trunc);
4977 }
4978 
4979 SDValue SITargetLowering::lowerFMINNUM_FMAXNUM(SDValue Op,
4980                                                SelectionDAG &DAG) const {
4981   EVT VT = Op.getValueType();
4982   const MachineFunction &MF = DAG.getMachineFunction();
4983   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
4984   bool IsIEEEMode = Info->getMode().IEEE;
4985 
4986   // FIXME: Assert during selection that this is only selected for
4987   // ieee_mode. Currently a combine can produce the ieee version for non-ieee
4988   // mode functions, but this happens to be OK since it's only done in cases
4989   // where there is known no sNaN.
4990   if (IsIEEEMode)
4991     return expandFMINNUM_FMAXNUM(Op.getNode(), DAG);
4992 
4993   if (VT == MVT::v4f16)
4994     return splitBinaryVectorOp(Op, DAG);
4995   return Op;
4996 }
4997 
4998 SDValue SITargetLowering::lowerXMULO(SDValue Op, SelectionDAG &DAG) const {
4999   EVT VT = Op.getValueType();
5000   SDLoc SL(Op);
5001   SDValue LHS = Op.getOperand(0);
5002   SDValue RHS = Op.getOperand(1);
5003   bool isSigned = Op.getOpcode() == ISD::SMULO;
5004 
5005   if (ConstantSDNode *RHSC = isConstOrConstSplat(RHS)) {
5006     const APInt &C = RHSC->getAPIntValue();
5007     // mulo(X, 1 << S) -> { X << S, (X << S) >> S != X }
5008     if (C.isPowerOf2()) {
5009       // smulo(x, signed_min) is same as umulo(x, signed_min).
5010       bool UseArithShift = isSigned && !C.isMinSignedValue();
5011       SDValue ShiftAmt = DAG.getConstant(C.logBase2(), SL, MVT::i32);
5012       SDValue Result = DAG.getNode(ISD::SHL, SL, VT, LHS, ShiftAmt);
5013       SDValue Overflow = DAG.getSetCC(SL, MVT::i1,
5014           DAG.getNode(UseArithShift ? ISD::SRA : ISD::SRL,
5015                       SL, VT, Result, ShiftAmt),
5016           LHS, ISD::SETNE);
5017       return DAG.getMergeValues({ Result, Overflow }, SL);
5018     }
5019   }
5020 
5021   SDValue Result = DAG.getNode(ISD::MUL, SL, VT, LHS, RHS);
5022   SDValue Top = DAG.getNode(isSigned ? ISD::MULHS : ISD::MULHU,
5023                             SL, VT, LHS, RHS);
5024 
5025   SDValue Sign = isSigned
5026     ? DAG.getNode(ISD::SRA, SL, VT, Result,
5027                   DAG.getConstant(VT.getScalarSizeInBits() - 1, SL, MVT::i32))
5028     : DAG.getConstant(0, SL, VT);
5029   SDValue Overflow = DAG.getSetCC(SL, MVT::i1, Top, Sign, ISD::SETNE);
5030 
5031   return DAG.getMergeValues({ Result, Overflow }, SL);
5032 }
5033 
5034 SDValue SITargetLowering::lowerTRAP(SDValue Op, SelectionDAG &DAG) const {
5035   SDLoc SL(Op);
5036   SDValue Chain = Op.getOperand(0);
5037 
5038   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5039       !Subtarget->isTrapHandlerEnabled())
5040     return DAG.getNode(AMDGPUISD::ENDPGM, SL, MVT::Other, Chain);
5041 
5042   MachineFunction &MF = DAG.getMachineFunction();
5043   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5044   unsigned UserSGPR = Info->getQueuePtrUserSGPR();
5045   assert(UserSGPR != AMDGPU::NoRegister);
5046   SDValue QueuePtr = CreateLiveInRegister(
5047     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5048   SDValue SGPR01 = DAG.getRegister(AMDGPU::SGPR0_SGPR1, MVT::i64);
5049   SDValue ToReg = DAG.getCopyToReg(Chain, SL, SGPR01,
5050                                    QueuePtr, SDValue());
5051   SDValue Ops[] = {
5052     ToReg,
5053     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMTrap, SL, MVT::i16),
5054     SGPR01,
5055     ToReg.getValue(1)
5056   };
5057   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5058 }
5059 
5060 SDValue SITargetLowering::lowerDEBUGTRAP(SDValue Op, SelectionDAG &DAG) const {
5061   SDLoc SL(Op);
5062   SDValue Chain = Op.getOperand(0);
5063   MachineFunction &MF = DAG.getMachineFunction();
5064 
5065   if (Subtarget->getTrapHandlerAbi() != GCNSubtarget::TrapHandlerAbiHsa ||
5066       !Subtarget->isTrapHandlerEnabled()) {
5067     DiagnosticInfoUnsupported NoTrap(MF.getFunction(),
5068                                      "debugtrap handler not supported",
5069                                      Op.getDebugLoc(),
5070                                      DS_Warning);
5071     LLVMContext &Ctx = MF.getFunction().getContext();
5072     Ctx.diagnose(NoTrap);
5073     return Chain;
5074   }
5075 
5076   SDValue Ops[] = {
5077     Chain,
5078     DAG.getTargetConstant(GCNSubtarget::TrapIDLLVMDebugTrap, SL, MVT::i16)
5079   };
5080   return DAG.getNode(AMDGPUISD::TRAP, SL, MVT::Other, Ops);
5081 }
5082 
5083 SDValue SITargetLowering::getSegmentAperture(unsigned AS, const SDLoc &DL,
5084                                              SelectionDAG &DAG) const {
5085   // FIXME: Use inline constants (src_{shared, private}_base) instead.
5086   if (Subtarget->hasApertureRegs()) {
5087     unsigned Offset = AS == AMDGPUAS::LOCAL_ADDRESS ?
5088         AMDGPU::Hwreg::OFFSET_SRC_SHARED_BASE :
5089         AMDGPU::Hwreg::OFFSET_SRC_PRIVATE_BASE;
5090     unsigned WidthM1 = AS == AMDGPUAS::LOCAL_ADDRESS ?
5091         AMDGPU::Hwreg::WIDTH_M1_SRC_SHARED_BASE :
5092         AMDGPU::Hwreg::WIDTH_M1_SRC_PRIVATE_BASE;
5093     unsigned Encoding =
5094         AMDGPU::Hwreg::ID_MEM_BASES << AMDGPU::Hwreg::ID_SHIFT_ |
5095         Offset << AMDGPU::Hwreg::OFFSET_SHIFT_ |
5096         WidthM1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_;
5097 
5098     SDValue EncodingImm = DAG.getTargetConstant(Encoding, DL, MVT::i16);
5099     SDValue ApertureReg = SDValue(
5100         DAG.getMachineNode(AMDGPU::S_GETREG_B32, DL, MVT::i32, EncodingImm), 0);
5101     SDValue ShiftAmount = DAG.getTargetConstant(WidthM1 + 1, DL, MVT::i32);
5102     return DAG.getNode(ISD::SHL, DL, MVT::i32, ApertureReg, ShiftAmount);
5103   }
5104 
5105   MachineFunction &MF = DAG.getMachineFunction();
5106   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
5107   Register UserSGPR = Info->getQueuePtrUserSGPR();
5108   assert(UserSGPR != AMDGPU::NoRegister);
5109 
5110   SDValue QueuePtr = CreateLiveInRegister(
5111     DAG, &AMDGPU::SReg_64RegClass, UserSGPR, MVT::i64);
5112 
5113   // Offset into amd_queue_t for group_segment_aperture_base_hi /
5114   // private_segment_aperture_base_hi.
5115   uint32_t StructOffset = (AS == AMDGPUAS::LOCAL_ADDRESS) ? 0x40 : 0x44;
5116 
5117   SDValue Ptr = DAG.getObjectPtrOffset(DL, QueuePtr, StructOffset);
5118 
5119   // TODO: Use custom target PseudoSourceValue.
5120   // TODO: We should use the value from the IR intrinsic call, but it might not
5121   // be available and how do we get it?
5122   MachinePointerInfo PtrInfo(AMDGPUAS::CONSTANT_ADDRESS);
5123   return DAG.getLoad(MVT::i32, DL, QueuePtr.getValue(1), Ptr, PtrInfo,
5124                      MinAlign(64, StructOffset),
5125                      MachineMemOperand::MODereferenceable |
5126                          MachineMemOperand::MOInvariant);
5127 }
5128 
5129 SDValue SITargetLowering::lowerADDRSPACECAST(SDValue Op,
5130                                              SelectionDAG &DAG) const {
5131   SDLoc SL(Op);
5132   const AddrSpaceCastSDNode *ASC = cast<AddrSpaceCastSDNode>(Op);
5133 
5134   SDValue Src = ASC->getOperand(0);
5135   SDValue FlatNullPtr = DAG.getConstant(0, SL, MVT::i64);
5136 
5137   const AMDGPUTargetMachine &TM =
5138     static_cast<const AMDGPUTargetMachine &>(getTargetMachine());
5139 
5140   // flat -> local/private
5141   if (ASC->getSrcAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5142     unsigned DestAS = ASC->getDestAddressSpace();
5143 
5144     if (DestAS == AMDGPUAS::LOCAL_ADDRESS ||
5145         DestAS == AMDGPUAS::PRIVATE_ADDRESS) {
5146       unsigned NullVal = TM.getNullPointerValue(DestAS);
5147       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5148       SDValue NonNull = DAG.getSetCC(SL, MVT::i1, Src, FlatNullPtr, ISD::SETNE);
5149       SDValue Ptr = DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5150 
5151       return DAG.getNode(ISD::SELECT, SL, MVT::i32,
5152                          NonNull, Ptr, SegmentNullPtr);
5153     }
5154   }
5155 
5156   // local/private -> flat
5157   if (ASC->getDestAddressSpace() == AMDGPUAS::FLAT_ADDRESS) {
5158     unsigned SrcAS = ASC->getSrcAddressSpace();
5159 
5160     if (SrcAS == AMDGPUAS::LOCAL_ADDRESS ||
5161         SrcAS == AMDGPUAS::PRIVATE_ADDRESS) {
5162       unsigned NullVal = TM.getNullPointerValue(SrcAS);
5163       SDValue SegmentNullPtr = DAG.getConstant(NullVal, SL, MVT::i32);
5164 
5165       SDValue NonNull
5166         = DAG.getSetCC(SL, MVT::i1, Src, SegmentNullPtr, ISD::SETNE);
5167 
5168       SDValue Aperture = getSegmentAperture(ASC->getSrcAddressSpace(), SL, DAG);
5169       SDValue CvtPtr
5170         = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32, Src, Aperture);
5171 
5172       return DAG.getNode(ISD::SELECT, SL, MVT::i64, NonNull,
5173                          DAG.getNode(ISD::BITCAST, SL, MVT::i64, CvtPtr),
5174                          FlatNullPtr);
5175     }
5176   }
5177 
5178   if (ASC->getDestAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
5179       Src.getValueType() == MVT::i64)
5180     return DAG.getNode(ISD::TRUNCATE, SL, MVT::i32, Src);
5181 
5182   // global <-> flat are no-ops and never emitted.
5183 
5184   const MachineFunction &MF = DAG.getMachineFunction();
5185   DiagnosticInfoUnsupported InvalidAddrSpaceCast(
5186     MF.getFunction(), "invalid addrspacecast", SL.getDebugLoc());
5187   DAG.getContext()->diagnose(InvalidAddrSpaceCast);
5188 
5189   return DAG.getUNDEF(ASC->getValueType(0));
5190 }
5191 
5192 // This lowers an INSERT_SUBVECTOR by extracting the individual elements from
5193 // the small vector and inserting them into the big vector. That is better than
5194 // the default expansion of doing it via a stack slot. Even though the use of
5195 // the stack slot would be optimized away afterwards, the stack slot itself
5196 // remains.
5197 SDValue SITargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
5198                                                 SelectionDAG &DAG) const {
5199   SDValue Vec = Op.getOperand(0);
5200   SDValue Ins = Op.getOperand(1);
5201   SDValue Idx = Op.getOperand(2);
5202   EVT VecVT = Vec.getValueType();
5203   EVT InsVT = Ins.getValueType();
5204   EVT EltVT = VecVT.getVectorElementType();
5205   unsigned InsNumElts = InsVT.getVectorNumElements();
5206   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
5207   SDLoc SL(Op);
5208 
5209   for (unsigned I = 0; I != InsNumElts; ++I) {
5210     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Ins,
5211                               DAG.getConstant(I, SL, MVT::i32));
5212     Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, VecVT, Vec, Elt,
5213                       DAG.getConstant(IdxVal + I, SL, MVT::i32));
5214   }
5215   return Vec;
5216 }
5217 
5218 SDValue SITargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
5219                                                  SelectionDAG &DAG) const {
5220   SDValue Vec = Op.getOperand(0);
5221   SDValue InsVal = Op.getOperand(1);
5222   SDValue Idx = Op.getOperand(2);
5223   EVT VecVT = Vec.getValueType();
5224   EVT EltVT = VecVT.getVectorElementType();
5225   unsigned VecSize = VecVT.getSizeInBits();
5226   unsigned EltSize = EltVT.getSizeInBits();
5227 
5228 
5229   assert(VecSize <= 64);
5230 
5231   unsigned NumElts = VecVT.getVectorNumElements();
5232   SDLoc SL(Op);
5233   auto KIdx = dyn_cast<ConstantSDNode>(Idx);
5234 
5235   if (NumElts == 4 && EltSize == 16 && KIdx) {
5236     SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Vec);
5237 
5238     SDValue LoHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5239                                  DAG.getConstant(0, SL, MVT::i32));
5240     SDValue HiHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, BCVec,
5241                                  DAG.getConstant(1, SL, MVT::i32));
5242 
5243     SDValue LoVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, LoHalf);
5244     SDValue HiVec = DAG.getNode(ISD::BITCAST, SL, MVT::v2i16, HiHalf);
5245 
5246     unsigned Idx = KIdx->getZExtValue();
5247     bool InsertLo = Idx < 2;
5248     SDValue InsHalf = DAG.getNode(ISD::INSERT_VECTOR_ELT, SL, MVT::v2i16,
5249       InsertLo ? LoVec : HiVec,
5250       DAG.getNode(ISD::BITCAST, SL, MVT::i16, InsVal),
5251       DAG.getConstant(InsertLo ? Idx : (Idx - 2), SL, MVT::i32));
5252 
5253     InsHalf = DAG.getNode(ISD::BITCAST, SL, MVT::i32, InsHalf);
5254 
5255     SDValue Concat = InsertLo ?
5256       DAG.getBuildVector(MVT::v2i32, SL, { InsHalf, HiHalf }) :
5257       DAG.getBuildVector(MVT::v2i32, SL, { LoHalf, InsHalf });
5258 
5259     return DAG.getNode(ISD::BITCAST, SL, VecVT, Concat);
5260   }
5261 
5262   if (isa<ConstantSDNode>(Idx))
5263     return SDValue();
5264 
5265   MVT IntVT = MVT::getIntegerVT(VecSize);
5266 
5267   // Avoid stack access for dynamic indexing.
5268   // v_bfi_b32 (v_bfm_b32 16, (shl idx, 16)), val, vec
5269 
5270   // Create a congruent vector with the target value in each element so that
5271   // the required element can be masked and ORed into the target vector.
5272   SDValue ExtVal = DAG.getNode(ISD::BITCAST, SL, IntVT,
5273                                DAG.getSplatBuildVector(VecVT, SL, InsVal));
5274 
5275   assert(isPowerOf2_32(EltSize));
5276   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5277 
5278   // Convert vector index to bit-index.
5279   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5280 
5281   SDValue BCVec = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5282   SDValue BFM = DAG.getNode(ISD::SHL, SL, IntVT,
5283                             DAG.getConstant(0xffff, SL, IntVT),
5284                             ScaledIdx);
5285 
5286   SDValue LHS = DAG.getNode(ISD::AND, SL, IntVT, BFM, ExtVal);
5287   SDValue RHS = DAG.getNode(ISD::AND, SL, IntVT,
5288                             DAG.getNOT(SL, BFM, IntVT), BCVec);
5289 
5290   SDValue BFI = DAG.getNode(ISD::OR, SL, IntVT, LHS, RHS);
5291   return DAG.getNode(ISD::BITCAST, SL, VecVT, BFI);
5292 }
5293 
5294 SDValue SITargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
5295                                                   SelectionDAG &DAG) const {
5296   SDLoc SL(Op);
5297 
5298   EVT ResultVT = Op.getValueType();
5299   SDValue Vec = Op.getOperand(0);
5300   SDValue Idx = Op.getOperand(1);
5301   EVT VecVT = Vec.getValueType();
5302   unsigned VecSize = VecVT.getSizeInBits();
5303   EVT EltVT = VecVT.getVectorElementType();
5304   assert(VecSize <= 64);
5305 
5306   DAGCombinerInfo DCI(DAG, AfterLegalizeVectorOps, true, nullptr);
5307 
5308   // Make sure we do any optimizations that will make it easier to fold
5309   // source modifiers before obscuring it with bit operations.
5310 
5311   // XXX - Why doesn't this get called when vector_shuffle is expanded?
5312   if (SDValue Combined = performExtractVectorEltCombine(Op.getNode(), DCI))
5313     return Combined;
5314 
5315   unsigned EltSize = EltVT.getSizeInBits();
5316   assert(isPowerOf2_32(EltSize));
5317 
5318   MVT IntVT = MVT::getIntegerVT(VecSize);
5319   SDValue ScaleFactor = DAG.getConstant(Log2_32(EltSize), SL, MVT::i32);
5320 
5321   // Convert vector index to bit-index (* EltSize)
5322   SDValue ScaledIdx = DAG.getNode(ISD::SHL, SL, MVT::i32, Idx, ScaleFactor);
5323 
5324   SDValue BC = DAG.getNode(ISD::BITCAST, SL, IntVT, Vec);
5325   SDValue Elt = DAG.getNode(ISD::SRL, SL, IntVT, BC, ScaledIdx);
5326 
5327   if (ResultVT == MVT::f16) {
5328     SDValue Result = DAG.getNode(ISD::TRUNCATE, SL, MVT::i16, Elt);
5329     return DAG.getNode(ISD::BITCAST, SL, ResultVT, Result);
5330   }
5331 
5332   return DAG.getAnyExtOrTrunc(Elt, SL, ResultVT);
5333 }
5334 
5335 static bool elementPairIsContiguous(ArrayRef<int> Mask, int Elt) {
5336   assert(Elt % 2 == 0);
5337   return Mask[Elt + 1] == Mask[Elt] + 1 && (Mask[Elt] % 2 == 0);
5338 }
5339 
5340 SDValue SITargetLowering::lowerVECTOR_SHUFFLE(SDValue Op,
5341                                               SelectionDAG &DAG) const {
5342   SDLoc SL(Op);
5343   EVT ResultVT = Op.getValueType();
5344   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
5345 
5346   EVT PackVT = ResultVT.isInteger() ? MVT::v2i16 : MVT::v2f16;
5347   EVT EltVT = PackVT.getVectorElementType();
5348   int SrcNumElts = Op.getOperand(0).getValueType().getVectorNumElements();
5349 
5350   // vector_shuffle <0,1,6,7> lhs, rhs
5351   // -> concat_vectors (extract_subvector lhs, 0), (extract_subvector rhs, 2)
5352   //
5353   // vector_shuffle <6,7,2,3> lhs, rhs
5354   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 2)
5355   //
5356   // vector_shuffle <6,7,0,1> lhs, rhs
5357   // -> concat_vectors (extract_subvector rhs, 2), (extract_subvector lhs, 0)
5358 
5359   // Avoid scalarizing when both halves are reading from consecutive elements.
5360   SmallVector<SDValue, 4> Pieces;
5361   for (int I = 0, N = ResultVT.getVectorNumElements(); I != N; I += 2) {
5362     if (elementPairIsContiguous(SVN->getMask(), I)) {
5363       const int Idx = SVN->getMaskElt(I);
5364       int VecIdx = Idx < SrcNumElts ? 0 : 1;
5365       int EltIdx = Idx < SrcNumElts ? Idx : Idx - SrcNumElts;
5366       SDValue SubVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SL,
5367                                     PackVT, SVN->getOperand(VecIdx),
5368                                     DAG.getConstant(EltIdx, SL, MVT::i32));
5369       Pieces.push_back(SubVec);
5370     } else {
5371       const int Idx0 = SVN->getMaskElt(I);
5372       const int Idx1 = SVN->getMaskElt(I + 1);
5373       int VecIdx0 = Idx0 < SrcNumElts ? 0 : 1;
5374       int VecIdx1 = Idx1 < SrcNumElts ? 0 : 1;
5375       int EltIdx0 = Idx0 < SrcNumElts ? Idx0 : Idx0 - SrcNumElts;
5376       int EltIdx1 = Idx1 < SrcNumElts ? Idx1 : Idx1 - SrcNumElts;
5377 
5378       SDValue Vec0 = SVN->getOperand(VecIdx0);
5379       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5380                                  Vec0, DAG.getConstant(EltIdx0, SL, MVT::i32));
5381 
5382       SDValue Vec1 = SVN->getOperand(VecIdx1);
5383       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
5384                                  Vec1, DAG.getConstant(EltIdx1, SL, MVT::i32));
5385       Pieces.push_back(DAG.getBuildVector(PackVT, SL, { Elt0, Elt1 }));
5386     }
5387   }
5388 
5389   return DAG.getNode(ISD::CONCAT_VECTORS, SL, ResultVT, Pieces);
5390 }
5391 
5392 SDValue SITargetLowering::lowerBUILD_VECTOR(SDValue Op,
5393                                             SelectionDAG &DAG) const {
5394   SDLoc SL(Op);
5395   EVT VT = Op.getValueType();
5396 
5397   if (VT == MVT::v4i16 || VT == MVT::v4f16) {
5398     EVT HalfVT = MVT::getVectorVT(VT.getVectorElementType().getSimpleVT(), 2);
5399 
5400     // Turn into pair of packed build_vectors.
5401     // TODO: Special case for constants that can be materialized with s_mov_b64.
5402     SDValue Lo = DAG.getBuildVector(HalfVT, SL,
5403                                     { Op.getOperand(0), Op.getOperand(1) });
5404     SDValue Hi = DAG.getBuildVector(HalfVT, SL,
5405                                     { Op.getOperand(2), Op.getOperand(3) });
5406 
5407     SDValue CastLo = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Lo);
5408     SDValue CastHi = DAG.getNode(ISD::BITCAST, SL, MVT::i32, Hi);
5409 
5410     SDValue Blend = DAG.getBuildVector(MVT::v2i32, SL, { CastLo, CastHi });
5411     return DAG.getNode(ISD::BITCAST, SL, VT, Blend);
5412   }
5413 
5414   assert(VT == MVT::v2f16 || VT == MVT::v2i16);
5415   assert(!Subtarget->hasVOP3PInsts() && "this should be legal");
5416 
5417   SDValue Lo = Op.getOperand(0);
5418   SDValue Hi = Op.getOperand(1);
5419 
5420   // Avoid adding defined bits with the zero_extend.
5421   if (Hi.isUndef()) {
5422     Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5423     SDValue ExtLo = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Lo);
5424     return DAG.getNode(ISD::BITCAST, SL, VT, ExtLo);
5425   }
5426 
5427   Hi = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Hi);
5428   Hi = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Hi);
5429 
5430   SDValue ShlHi = DAG.getNode(ISD::SHL, SL, MVT::i32, Hi,
5431                               DAG.getConstant(16, SL, MVT::i32));
5432   if (Lo.isUndef())
5433     return DAG.getNode(ISD::BITCAST, SL, VT, ShlHi);
5434 
5435   Lo = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Lo);
5436   Lo = DAG.getNode(ISD::ZERO_EXTEND, SL, MVT::i32, Lo);
5437 
5438   SDValue Or = DAG.getNode(ISD::OR, SL, MVT::i32, Lo, ShlHi);
5439   return DAG.getNode(ISD::BITCAST, SL, VT, Or);
5440 }
5441 
5442 bool
5443 SITargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
5444   // We can fold offsets for anything that doesn't require a GOT relocation.
5445   return (GA->getAddressSpace() == AMDGPUAS::GLOBAL_ADDRESS ||
5446           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS ||
5447           GA->getAddressSpace() == AMDGPUAS::CONSTANT_ADDRESS_32BIT) &&
5448          !shouldEmitGOTReloc(GA->getGlobal());
5449 }
5450 
5451 static SDValue
5452 buildPCRelGlobalAddress(SelectionDAG &DAG, const GlobalValue *GV,
5453                         const SDLoc &DL, unsigned Offset, EVT PtrVT,
5454                         unsigned GAFlags = SIInstrInfo::MO_NONE) {
5455   // In order to support pc-relative addressing, the PC_ADD_REL_OFFSET SDNode is
5456   // lowered to the following code sequence:
5457   //
5458   // For constant address space:
5459   //   s_getpc_b64 s[0:1]
5460   //   s_add_u32 s0, s0, $symbol
5461   //   s_addc_u32 s1, s1, 0
5462   //
5463   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5464   //   a fixup or relocation is emitted to replace $symbol with a literal
5465   //   constant, which is a pc-relative offset from the encoding of the $symbol
5466   //   operand to the global variable.
5467   //
5468   // For global address space:
5469   //   s_getpc_b64 s[0:1]
5470   //   s_add_u32 s0, s0, $symbol@{gotpc}rel32@lo
5471   //   s_addc_u32 s1, s1, $symbol@{gotpc}rel32@hi
5472   //
5473   //   s_getpc_b64 returns the address of the s_add_u32 instruction and then
5474   //   fixups or relocations are emitted to replace $symbol@*@lo and
5475   //   $symbol@*@hi with lower 32 bits and higher 32 bits of a literal constant,
5476   //   which is a 64-bit pc-relative offset from the encoding of the $symbol
5477   //   operand to the global variable.
5478   //
5479   // What we want here is an offset from the value returned by s_getpc
5480   // (which is the address of the s_add_u32 instruction) to the global
5481   // variable, but since the encoding of $symbol starts 4 bytes after the start
5482   // of the s_add_u32 instruction, we end up with an offset that is 4 bytes too
5483   // small. This requires us to add 4 to the global variable offset in order to
5484   // compute the correct address.
5485   SDValue PtrLo =
5486       DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags);
5487   SDValue PtrHi;
5488   if (GAFlags == SIInstrInfo::MO_NONE) {
5489     PtrHi = DAG.getTargetConstant(0, DL, MVT::i32);
5490   } else {
5491     PtrHi =
5492         DAG.getTargetGlobalAddress(GV, DL, MVT::i32, Offset + 4, GAFlags + 1);
5493   }
5494   return DAG.getNode(AMDGPUISD::PC_ADD_REL_OFFSET, DL, PtrVT, PtrLo, PtrHi);
5495 }
5496 
5497 SDValue SITargetLowering::LowerGlobalAddress(AMDGPUMachineFunction *MFI,
5498                                              SDValue Op,
5499                                              SelectionDAG &DAG) const {
5500   GlobalAddressSDNode *GSD = cast<GlobalAddressSDNode>(Op);
5501   const GlobalValue *GV = GSD->getGlobal();
5502   if ((GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS &&
5503        shouldUseLDSConstAddress(GV)) ||
5504       GSD->getAddressSpace() == AMDGPUAS::REGION_ADDRESS ||
5505       GSD->getAddressSpace() == AMDGPUAS::PRIVATE_ADDRESS)
5506     return AMDGPUTargetLowering::LowerGlobalAddress(MFI, Op, DAG);
5507 
5508   SDLoc DL(GSD);
5509   EVT PtrVT = Op.getValueType();
5510 
5511   if (GSD->getAddressSpace() == AMDGPUAS::LOCAL_ADDRESS) {
5512     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, GSD->getOffset(),
5513                                             SIInstrInfo::MO_ABS32_LO);
5514     return DAG.getNode(AMDGPUISD::LDS, DL, MVT::i32, GA);
5515   }
5516 
5517   if (shouldEmitFixup(GV))
5518     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT);
5519   else if (shouldEmitPCReloc(GV))
5520     return buildPCRelGlobalAddress(DAG, GV, DL, GSD->getOffset(), PtrVT,
5521                                    SIInstrInfo::MO_REL32);
5522 
5523   SDValue GOTAddr = buildPCRelGlobalAddress(DAG, GV, DL, 0, PtrVT,
5524                                             SIInstrInfo::MO_GOTPCREL32);
5525 
5526   Type *Ty = PtrVT.getTypeForEVT(*DAG.getContext());
5527   PointerType *PtrTy = PointerType::get(Ty, AMDGPUAS::CONSTANT_ADDRESS);
5528   const DataLayout &DataLayout = DAG.getDataLayout();
5529   unsigned Align = DataLayout.getABITypeAlignment(PtrTy);
5530   MachinePointerInfo PtrInfo
5531     = MachinePointerInfo::getGOT(DAG.getMachineFunction());
5532 
5533   return DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), GOTAddr, PtrInfo, Align,
5534                      MachineMemOperand::MODereferenceable |
5535                          MachineMemOperand::MOInvariant);
5536 }
5537 
5538 SDValue SITargetLowering::copyToM0(SelectionDAG &DAG, SDValue Chain,
5539                                    const SDLoc &DL, SDValue V) const {
5540   // We can't use S_MOV_B32 directly, because there is no way to specify m0 as
5541   // the destination register.
5542   //
5543   // We can't use CopyToReg, because MachineCSE won't combine COPY instructions,
5544   // so we will end up with redundant moves to m0.
5545   //
5546   // We use a pseudo to ensure we emit s_mov_b32 with m0 as the direct result.
5547 
5548   // A Null SDValue creates a glue result.
5549   SDNode *M0 = DAG.getMachineNode(AMDGPU::SI_INIT_M0, DL, MVT::Other, MVT::Glue,
5550                                   V, Chain);
5551   return SDValue(M0, 0);
5552 }
5553 
5554 SDValue SITargetLowering::lowerImplicitZextParam(SelectionDAG &DAG,
5555                                                  SDValue Op,
5556                                                  MVT VT,
5557                                                  unsigned Offset) const {
5558   SDLoc SL(Op);
5559   SDValue Param = lowerKernargMemParameter(DAG, MVT::i32, MVT::i32, SL,
5560                                            DAG.getEntryNode(), Offset, 4, false);
5561   // The local size values will have the hi 16-bits as zero.
5562   return DAG.getNode(ISD::AssertZext, SL, MVT::i32, Param,
5563                      DAG.getValueType(VT));
5564 }
5565 
5566 static SDValue emitNonHSAIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5567                                         EVT VT) {
5568   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5569                                       "non-hsa intrinsic with hsa target",
5570                                       DL.getDebugLoc());
5571   DAG.getContext()->diagnose(BadIntrin);
5572   return DAG.getUNDEF(VT);
5573 }
5574 
5575 static SDValue emitRemovedIntrinsicError(SelectionDAG &DAG, const SDLoc &DL,
5576                                          EVT VT) {
5577   DiagnosticInfoUnsupported BadIntrin(DAG.getMachineFunction().getFunction(),
5578                                       "intrinsic not supported on subtarget",
5579                                       DL.getDebugLoc());
5580   DAG.getContext()->diagnose(BadIntrin);
5581   return DAG.getUNDEF(VT);
5582 }
5583 
5584 static SDValue getBuildDwordsVector(SelectionDAG &DAG, SDLoc DL,
5585                                     ArrayRef<SDValue> Elts) {
5586   assert(!Elts.empty());
5587   MVT Type;
5588   unsigned NumElts;
5589 
5590   if (Elts.size() == 1) {
5591     Type = MVT::f32;
5592     NumElts = 1;
5593   } else if (Elts.size() == 2) {
5594     Type = MVT::v2f32;
5595     NumElts = 2;
5596   } else if (Elts.size() == 3) {
5597     Type = MVT::v3f32;
5598     NumElts = 3;
5599   } else if (Elts.size() <= 4) {
5600     Type = MVT::v4f32;
5601     NumElts = 4;
5602   } else if (Elts.size() <= 8) {
5603     Type = MVT::v8f32;
5604     NumElts = 8;
5605   } else {
5606     assert(Elts.size() <= 16);
5607     Type = MVT::v16f32;
5608     NumElts = 16;
5609   }
5610 
5611   SmallVector<SDValue, 16> VecElts(NumElts);
5612   for (unsigned i = 0; i < Elts.size(); ++i) {
5613     SDValue Elt = Elts[i];
5614     if (Elt.getValueType() != MVT::f32)
5615       Elt = DAG.getBitcast(MVT::f32, Elt);
5616     VecElts[i] = Elt;
5617   }
5618   for (unsigned i = Elts.size(); i < NumElts; ++i)
5619     VecElts[i] = DAG.getUNDEF(MVT::f32);
5620 
5621   if (NumElts == 1)
5622     return VecElts[0];
5623   return DAG.getBuildVector(Type, DL, VecElts);
5624 }
5625 
5626 static bool parseCachePolicy(SDValue CachePolicy, SelectionDAG &DAG,
5627                              SDValue *GLC, SDValue *SLC, SDValue *DLC) {
5628   auto CachePolicyConst = cast<ConstantSDNode>(CachePolicy.getNode());
5629 
5630   uint64_t Value = CachePolicyConst->getZExtValue();
5631   SDLoc DL(CachePolicy);
5632   if (GLC) {
5633     *GLC = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5634     Value &= ~(uint64_t)0x1;
5635   }
5636   if (SLC) {
5637     *SLC = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5638     Value &= ~(uint64_t)0x2;
5639   }
5640   if (DLC) {
5641     *DLC = DAG.getTargetConstant((Value & 0x4) ? 1 : 0, DL, MVT::i32);
5642     Value &= ~(uint64_t)0x4;
5643   }
5644 
5645   return Value == 0;
5646 }
5647 
5648 static SDValue padEltsToUndef(SelectionDAG &DAG, const SDLoc &DL, EVT CastVT,
5649                               SDValue Src, int ExtraElts) {
5650   EVT SrcVT = Src.getValueType();
5651 
5652   SmallVector<SDValue, 8> Elts;
5653 
5654   if (SrcVT.isVector())
5655     DAG.ExtractVectorElements(Src, Elts);
5656   else
5657     Elts.push_back(Src);
5658 
5659   SDValue Undef = DAG.getUNDEF(SrcVT.getScalarType());
5660   while (ExtraElts--)
5661     Elts.push_back(Undef);
5662 
5663   return DAG.getBuildVector(CastVT, DL, Elts);
5664 }
5665 
5666 // Re-construct the required return value for a image load intrinsic.
5667 // This is more complicated due to the optional use TexFailCtrl which means the required
5668 // return type is an aggregate
5669 static SDValue constructRetValue(SelectionDAG &DAG,
5670                                  MachineSDNode *Result,
5671                                  ArrayRef<EVT> ResultTypes,
5672                                  bool IsTexFail, bool Unpacked, bool IsD16,
5673                                  int DMaskPop, int NumVDataDwords,
5674                                  const SDLoc &DL, LLVMContext &Context) {
5675   // Determine the required return type. This is the same regardless of IsTexFail flag
5676   EVT ReqRetVT = ResultTypes[0];
5677   int ReqRetNumElts = ReqRetVT.isVector() ? ReqRetVT.getVectorNumElements() : 1;
5678   int NumDataDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5679     ReqRetNumElts : (ReqRetNumElts + 1) / 2;
5680 
5681   int MaskPopDwords = (!IsD16 || (IsD16 && Unpacked)) ?
5682     DMaskPop : (DMaskPop + 1) / 2;
5683 
5684   MVT DataDwordVT = NumDataDwords == 1 ?
5685     MVT::i32 : MVT::getVectorVT(MVT::i32, NumDataDwords);
5686 
5687   MVT MaskPopVT = MaskPopDwords == 1 ?
5688     MVT::i32 : MVT::getVectorVT(MVT::i32, MaskPopDwords);
5689 
5690   SDValue Data(Result, 0);
5691   SDValue TexFail;
5692 
5693   if (IsTexFail) {
5694     SDValue ZeroIdx = DAG.getConstant(0, DL, MVT::i32);
5695     if (MaskPopVT.isVector()) {
5696       Data = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MaskPopVT,
5697                          SDValue(Result, 0), ZeroIdx);
5698     } else {
5699       Data = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MaskPopVT,
5700                          SDValue(Result, 0), ZeroIdx);
5701     }
5702 
5703     TexFail = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
5704                           SDValue(Result, 0),
5705                           DAG.getConstant(MaskPopDwords, DL, MVT::i32));
5706   }
5707 
5708   if (DataDwordVT.isVector())
5709     Data = padEltsToUndef(DAG, DL, DataDwordVT, Data,
5710                           NumDataDwords - MaskPopDwords);
5711 
5712   if (IsD16)
5713     Data = adjustLoadValueTypeImpl(Data, ReqRetVT, DL, DAG, Unpacked);
5714 
5715   if (!ReqRetVT.isVector())
5716     Data = DAG.getNode(ISD::TRUNCATE, DL, ReqRetVT.changeTypeToInteger(), Data);
5717 
5718   Data = DAG.getNode(ISD::BITCAST, DL, ReqRetVT, Data);
5719 
5720   if (TexFail)
5721     return DAG.getMergeValues({Data, TexFail, SDValue(Result, 1)}, DL);
5722 
5723   if (Result->getNumValues() == 1)
5724     return Data;
5725 
5726   return DAG.getMergeValues({Data, SDValue(Result, 1)}, DL);
5727 }
5728 
5729 static bool parseTexFail(SDValue TexFailCtrl, SelectionDAG &DAG, SDValue *TFE,
5730                          SDValue *LWE, bool &IsTexFail) {
5731   auto TexFailCtrlConst = cast<ConstantSDNode>(TexFailCtrl.getNode());
5732 
5733   uint64_t Value = TexFailCtrlConst->getZExtValue();
5734   if (Value) {
5735     IsTexFail = true;
5736   }
5737 
5738   SDLoc DL(TexFailCtrlConst);
5739   *TFE = DAG.getTargetConstant((Value & 0x1) ? 1 : 0, DL, MVT::i32);
5740   Value &= ~(uint64_t)0x1;
5741   *LWE = DAG.getTargetConstant((Value & 0x2) ? 1 : 0, DL, MVT::i32);
5742   Value &= ~(uint64_t)0x2;
5743 
5744   return Value == 0;
5745 }
5746 
5747 SDValue SITargetLowering::lowerImage(SDValue Op,
5748                                      const AMDGPU::ImageDimIntrinsicInfo *Intr,
5749                                      SelectionDAG &DAG) const {
5750   SDLoc DL(Op);
5751   MachineFunction &MF = DAG.getMachineFunction();
5752   const GCNSubtarget* ST = &MF.getSubtarget<GCNSubtarget>();
5753   const AMDGPU::MIMGBaseOpcodeInfo *BaseOpcode =
5754       AMDGPU::getMIMGBaseOpcodeInfo(Intr->BaseOpcode);
5755   const AMDGPU::MIMGDimInfo *DimInfo = AMDGPU::getMIMGDimInfo(Intr->Dim);
5756   const AMDGPU::MIMGLZMappingInfo *LZMappingInfo =
5757       AMDGPU::getMIMGLZMappingInfo(Intr->BaseOpcode);
5758   const AMDGPU::MIMGMIPMappingInfo *MIPMappingInfo =
5759       AMDGPU::getMIMGMIPMappingInfo(Intr->BaseOpcode);
5760   unsigned IntrOpcode = Intr->BaseOpcode;
5761   bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
5762 
5763   SmallVector<EVT, 3> ResultTypes(Op->value_begin(), Op->value_end());
5764   SmallVector<EVT, 3> OrigResultTypes(Op->value_begin(), Op->value_end());
5765   bool IsD16 = false;
5766   bool IsA16 = false;
5767   SDValue VData;
5768   int NumVDataDwords;
5769   bool AdjustRetType = false;
5770 
5771   unsigned AddrIdx; // Index of first address argument
5772   unsigned DMask;
5773   unsigned DMaskLanes = 0;
5774 
5775   if (BaseOpcode->Atomic) {
5776     VData = Op.getOperand(2);
5777 
5778     bool Is64Bit = VData.getValueType() == MVT::i64;
5779     if (BaseOpcode->AtomicX2) {
5780       SDValue VData2 = Op.getOperand(3);
5781       VData = DAG.getBuildVector(Is64Bit ? MVT::v2i64 : MVT::v2i32, DL,
5782                                  {VData, VData2});
5783       if (Is64Bit)
5784         VData = DAG.getBitcast(MVT::v4i32, VData);
5785 
5786       ResultTypes[0] = Is64Bit ? MVT::v2i64 : MVT::v2i32;
5787       DMask = Is64Bit ? 0xf : 0x3;
5788       NumVDataDwords = Is64Bit ? 4 : 2;
5789       AddrIdx = 4;
5790     } else {
5791       DMask = Is64Bit ? 0x3 : 0x1;
5792       NumVDataDwords = Is64Bit ? 2 : 1;
5793       AddrIdx = 3;
5794     }
5795   } else {
5796     unsigned DMaskIdx = BaseOpcode->Store ? 3 : isa<MemSDNode>(Op) ? 2 : 1;
5797     auto DMaskConst = cast<ConstantSDNode>(Op.getOperand(DMaskIdx));
5798     DMask = DMaskConst->getZExtValue();
5799     DMaskLanes = BaseOpcode->Gather4 ? 4 : countPopulation(DMask);
5800 
5801     if (BaseOpcode->Store) {
5802       VData = Op.getOperand(2);
5803 
5804       MVT StoreVT = VData.getSimpleValueType();
5805       if (StoreVT.getScalarType() == MVT::f16) {
5806         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5807           return Op; // D16 is unsupported for this instruction
5808 
5809         IsD16 = true;
5810         VData = handleD16VData(VData, DAG);
5811       }
5812 
5813       NumVDataDwords = (VData.getValueType().getSizeInBits() + 31) / 32;
5814     } else {
5815       // Work out the num dwords based on the dmask popcount and underlying type
5816       // and whether packing is supported.
5817       MVT LoadVT = ResultTypes[0].getSimpleVT();
5818       if (LoadVT.getScalarType() == MVT::f16) {
5819         if (!Subtarget->hasD16Images() || !BaseOpcode->HasD16)
5820           return Op; // D16 is unsupported for this instruction
5821 
5822         IsD16 = true;
5823       }
5824 
5825       // Confirm that the return type is large enough for the dmask specified
5826       if ((LoadVT.isVector() && LoadVT.getVectorNumElements() < DMaskLanes) ||
5827           (!LoadVT.isVector() && DMaskLanes > 1))
5828           return Op;
5829 
5830       if (IsD16 && !Subtarget->hasUnpackedD16VMem())
5831         NumVDataDwords = (DMaskLanes + 1) / 2;
5832       else
5833         NumVDataDwords = DMaskLanes;
5834 
5835       AdjustRetType = true;
5836     }
5837 
5838     AddrIdx = DMaskIdx + 1;
5839   }
5840 
5841   unsigned NumGradients = BaseOpcode->Gradients ? DimInfo->NumGradients : 0;
5842   unsigned NumCoords = BaseOpcode->Coordinates ? DimInfo->NumCoords : 0;
5843   unsigned NumLCM = BaseOpcode->LodOrClampOrMip ? 1 : 0;
5844   unsigned NumVAddrs = BaseOpcode->NumExtraArgs + NumGradients +
5845                        NumCoords + NumLCM;
5846   unsigned NumMIVAddrs = NumVAddrs;
5847 
5848   SmallVector<SDValue, 4> VAddrs;
5849 
5850   // Optimize _L to _LZ when _L is zero
5851   if (LZMappingInfo) {
5852     if (auto ConstantLod =
5853          dyn_cast<ConstantFPSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5854       if (ConstantLod->isZero() || ConstantLod->isNegative()) {
5855         IntrOpcode = LZMappingInfo->LZ;  // set new opcode to _lz variant of _l
5856         NumMIVAddrs--;               // remove 'lod'
5857       }
5858     }
5859   }
5860 
5861   // Optimize _mip away, when 'lod' is zero
5862   if (MIPMappingInfo) {
5863     if (auto ConstantLod =
5864          dyn_cast<ConstantSDNode>(Op.getOperand(AddrIdx+NumVAddrs-1))) {
5865       if (ConstantLod->isNullValue()) {
5866         IntrOpcode = MIPMappingInfo->NONMIP;  // set new opcode to variant without _mip
5867         NumMIVAddrs--;               // remove 'lod'
5868       }
5869     }
5870   }
5871 
5872   // Check for 16 bit addresses and pack if true.
5873   unsigned DimIdx = AddrIdx + BaseOpcode->NumExtraArgs;
5874   MVT VAddrVT = Op.getOperand(DimIdx).getSimpleValueType();
5875   const MVT VAddrScalarVT = VAddrVT.getScalarType();
5876   if (((VAddrScalarVT == MVT::f16) || (VAddrScalarVT == MVT::i16))) {
5877     // Illegal to use a16 images
5878     if (!ST->hasFeature(AMDGPU::FeatureR128A16) && !ST->hasFeature(AMDGPU::FeatureGFX10A16))
5879       return Op;
5880 
5881     IsA16 = true;
5882     const MVT VectorVT = VAddrScalarVT == MVT::f16 ? MVT::v2f16 : MVT::v2i16;
5883     for (unsigned i = AddrIdx; i < (AddrIdx + NumMIVAddrs); ++i) {
5884       SDValue AddrLo;
5885       // Push back extra arguments.
5886       if (i < DimIdx) {
5887         AddrLo = Op.getOperand(i);
5888       } else {
5889         // Dz/dh, dz/dv and the last odd coord are packed with undef. Also,
5890         // in 1D, derivatives dx/dh and dx/dv are packed with undef.
5891         if (((i + 1) >= (AddrIdx + NumMIVAddrs)) ||
5892             ((NumGradients / 2) % 2 == 1 &&
5893             (i == DimIdx + (NumGradients / 2) - 1 ||
5894              i == DimIdx + NumGradients - 1))) {
5895           AddrLo = Op.getOperand(i);
5896           if (AddrLo.getValueType() != MVT::i16)
5897             AddrLo = DAG.getBitcast(MVT::i16, Op.getOperand(i));
5898           AddrLo = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, AddrLo);
5899         } else {
5900           AddrLo = DAG.getBuildVector(VectorVT, DL,
5901                                       {Op.getOperand(i), Op.getOperand(i + 1)});
5902           i++;
5903         }
5904         AddrLo = DAG.getBitcast(MVT::f32, AddrLo);
5905       }
5906       VAddrs.push_back(AddrLo);
5907     }
5908   } else {
5909     for (unsigned i = 0; i < NumMIVAddrs; ++i)
5910       VAddrs.push_back(Op.getOperand(AddrIdx + i));
5911   }
5912 
5913   // If the register allocator cannot place the address registers contiguously
5914   // without introducing moves, then using the non-sequential address encoding
5915   // is always preferable, since it saves VALU instructions and is usually a
5916   // wash in terms of code size or even better.
5917   //
5918   // However, we currently have no way of hinting to the register allocator that
5919   // MIMG addresses should be placed contiguously when it is possible to do so,
5920   // so force non-NSA for the common 2-address case as a heuristic.
5921   //
5922   // SIShrinkInstructions will convert NSA encodings to non-NSA after register
5923   // allocation when possible.
5924   bool UseNSA =
5925       ST->hasFeature(AMDGPU::FeatureNSAEncoding) && VAddrs.size() >= 3;
5926   SDValue VAddr;
5927   if (!UseNSA)
5928     VAddr = getBuildDwordsVector(DAG, DL, VAddrs);
5929 
5930   SDValue True = DAG.getTargetConstant(1, DL, MVT::i1);
5931   SDValue False = DAG.getTargetConstant(0, DL, MVT::i1);
5932   unsigned CtrlIdx; // Index of texfailctrl argument
5933   SDValue Unorm;
5934   if (!BaseOpcode->Sampler) {
5935     Unorm = True;
5936     CtrlIdx = AddrIdx + NumVAddrs + 1;
5937   } else {
5938     auto UnormConst =
5939         cast<ConstantSDNode>(Op.getOperand(AddrIdx + NumVAddrs + 2));
5940 
5941     Unorm = UnormConst->getZExtValue() ? True : False;
5942     CtrlIdx = AddrIdx + NumVAddrs + 3;
5943   }
5944 
5945   SDValue TFE;
5946   SDValue LWE;
5947   SDValue TexFail = Op.getOperand(CtrlIdx);
5948   bool IsTexFail = false;
5949   if (!parseTexFail(TexFail, DAG, &TFE, &LWE, IsTexFail))
5950     return Op;
5951 
5952   if (IsTexFail) {
5953     if (!DMaskLanes) {
5954       // Expecting to get an error flag since TFC is on - and dmask is 0
5955       // Force dmask to be at least 1 otherwise the instruction will fail
5956       DMask = 0x1;
5957       DMaskLanes = 1;
5958       NumVDataDwords = 1;
5959     }
5960     NumVDataDwords += 1;
5961     AdjustRetType = true;
5962   }
5963 
5964   // Has something earlier tagged that the return type needs adjusting
5965   // This happens if the instruction is a load or has set TexFailCtrl flags
5966   if (AdjustRetType) {
5967     // NumVDataDwords reflects the true number of dwords required in the return type
5968     if (DMaskLanes == 0 && !BaseOpcode->Store) {
5969       // This is a no-op load. This can be eliminated
5970       SDValue Undef = DAG.getUNDEF(Op.getValueType());
5971       if (isa<MemSDNode>(Op))
5972         return DAG.getMergeValues({Undef, Op.getOperand(0)}, DL);
5973       return Undef;
5974     }
5975 
5976     EVT NewVT = NumVDataDwords > 1 ?
5977                   EVT::getVectorVT(*DAG.getContext(), MVT::i32, NumVDataDwords)
5978                 : MVT::i32;
5979 
5980     ResultTypes[0] = NewVT;
5981     if (ResultTypes.size() == 3) {
5982       // Original result was aggregate type used for TexFailCtrl results
5983       // The actual instruction returns as a vector type which has now been
5984       // created. Remove the aggregate result.
5985       ResultTypes.erase(&ResultTypes[1]);
5986     }
5987   }
5988 
5989   SDValue GLC;
5990   SDValue SLC;
5991   SDValue DLC;
5992   if (BaseOpcode->Atomic) {
5993     GLC = True; // TODO no-return optimization
5994     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, nullptr, &SLC,
5995                           IsGFX10 ? &DLC : nullptr))
5996       return Op;
5997   } else {
5998     if (!parseCachePolicy(Op.getOperand(CtrlIdx + 1), DAG, &GLC, &SLC,
5999                           IsGFX10 ? &DLC : nullptr))
6000       return Op;
6001   }
6002 
6003   SmallVector<SDValue, 26> Ops;
6004   if (BaseOpcode->Store || BaseOpcode->Atomic)
6005     Ops.push_back(VData); // vdata
6006   if (UseNSA) {
6007     for (const SDValue &Addr : VAddrs)
6008       Ops.push_back(Addr);
6009   } else {
6010     Ops.push_back(VAddr);
6011   }
6012   Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs)); // rsrc
6013   if (BaseOpcode->Sampler)
6014     Ops.push_back(Op.getOperand(AddrIdx + NumVAddrs + 1)); // sampler
6015   Ops.push_back(DAG.getTargetConstant(DMask, DL, MVT::i32));
6016   if (IsGFX10)
6017     Ops.push_back(DAG.getTargetConstant(DimInfo->Encoding, DL, MVT::i32));
6018   Ops.push_back(Unorm);
6019   if (IsGFX10)
6020     Ops.push_back(DLC);
6021   Ops.push_back(GLC);
6022   Ops.push_back(SLC);
6023   Ops.push_back(IsA16 &&  // r128, a16 for gfx9
6024                 ST->hasFeature(AMDGPU::FeatureR128A16) ? True : False);
6025   if (IsGFX10)
6026     Ops.push_back(IsA16 ? True : False);
6027   Ops.push_back(TFE);
6028   Ops.push_back(LWE);
6029   if (!IsGFX10)
6030     Ops.push_back(DimInfo->DA ? True : False);
6031   if (BaseOpcode->HasD16)
6032     Ops.push_back(IsD16 ? True : False);
6033   if (isa<MemSDNode>(Op))
6034     Ops.push_back(Op.getOperand(0)); // chain
6035 
6036   int NumVAddrDwords =
6037       UseNSA ? VAddrs.size() : VAddr.getValueType().getSizeInBits() / 32;
6038   int Opcode = -1;
6039 
6040   if (IsGFX10) {
6041     Opcode = AMDGPU::getMIMGOpcode(IntrOpcode,
6042                                    UseNSA ? AMDGPU::MIMGEncGfx10NSA
6043                                           : AMDGPU::MIMGEncGfx10Default,
6044                                    NumVDataDwords, NumVAddrDwords);
6045   } else {
6046     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6047       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx8,
6048                                      NumVDataDwords, NumVAddrDwords);
6049     if (Opcode == -1)
6050       Opcode = AMDGPU::getMIMGOpcode(IntrOpcode, AMDGPU::MIMGEncGfx6,
6051                                      NumVDataDwords, NumVAddrDwords);
6052   }
6053   assert(Opcode != -1);
6054 
6055   MachineSDNode *NewNode = DAG.getMachineNode(Opcode, DL, ResultTypes, Ops);
6056   if (auto MemOp = dyn_cast<MemSDNode>(Op)) {
6057     MachineMemOperand *MemRef = MemOp->getMemOperand();
6058     DAG.setNodeMemRefs(NewNode, {MemRef});
6059   }
6060 
6061   if (BaseOpcode->AtomicX2) {
6062     SmallVector<SDValue, 1> Elt;
6063     DAG.ExtractVectorElements(SDValue(NewNode, 0), Elt, 0, 1);
6064     return DAG.getMergeValues({Elt[0], SDValue(NewNode, 1)}, DL);
6065   } else if (!BaseOpcode->Store) {
6066     return constructRetValue(DAG, NewNode,
6067                              OrigResultTypes, IsTexFail,
6068                              Subtarget->hasUnpackedD16VMem(), IsD16,
6069                              DMaskLanes, NumVDataDwords, DL,
6070                              *DAG.getContext());
6071   }
6072 
6073   return SDValue(NewNode, 0);
6074 }
6075 
6076 SDValue SITargetLowering::lowerSBuffer(EVT VT, SDLoc DL, SDValue Rsrc,
6077                                        SDValue Offset, SDValue CachePolicy,
6078                                        SelectionDAG &DAG) const {
6079   MachineFunction &MF = DAG.getMachineFunction();
6080 
6081   const DataLayout &DataLayout = DAG.getDataLayout();
6082   Align Alignment =
6083       DataLayout.getABITypeAlign(VT.getTypeForEVT(*DAG.getContext()));
6084 
6085   MachineMemOperand *MMO = MF.getMachineMemOperand(
6086       MachinePointerInfo(),
6087       MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
6088           MachineMemOperand::MOInvariant,
6089       VT.getStoreSize(), Alignment);
6090 
6091   if (!Offset->isDivergent()) {
6092     SDValue Ops[] = {
6093         Rsrc,
6094         Offset, // Offset
6095         CachePolicy
6096     };
6097 
6098     // Widen vec3 load to vec4.
6099     if (VT.isVector() && VT.getVectorNumElements() == 3) {
6100       EVT WidenedVT =
6101           EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(), 4);
6102       auto WidenedOp = DAG.getMemIntrinsicNode(
6103           AMDGPUISD::SBUFFER_LOAD, DL, DAG.getVTList(WidenedVT), Ops, WidenedVT,
6104           MF.getMachineMemOperand(MMO, 0, WidenedVT.getStoreSize()));
6105       auto Subvector = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, WidenedOp,
6106                                    DAG.getVectorIdxConstant(0, DL));
6107       return Subvector;
6108     }
6109 
6110     return DAG.getMemIntrinsicNode(AMDGPUISD::SBUFFER_LOAD, DL,
6111                                    DAG.getVTList(VT), Ops, VT, MMO);
6112   }
6113 
6114   // We have a divergent offset. Emit a MUBUF buffer load instead. We can
6115   // assume that the buffer is unswizzled.
6116   SmallVector<SDValue, 4> Loads;
6117   unsigned NumLoads = 1;
6118   MVT LoadVT = VT.getSimpleVT();
6119   unsigned NumElts = LoadVT.isVector() ? LoadVT.getVectorNumElements() : 1;
6120   assert((LoadVT.getScalarType() == MVT::i32 ||
6121           LoadVT.getScalarType() == MVT::f32));
6122 
6123   if (NumElts == 8 || NumElts == 16) {
6124     NumLoads = NumElts / 4;
6125     LoadVT = MVT::getVectorVT(LoadVT.getScalarType(), 4);
6126   }
6127 
6128   SDVTList VTList = DAG.getVTList({LoadVT, MVT::Glue});
6129   SDValue Ops[] = {
6130       DAG.getEntryNode(),                               // Chain
6131       Rsrc,                                             // rsrc
6132       DAG.getConstant(0, DL, MVT::i32),                 // vindex
6133       {},                                               // voffset
6134       {},                                               // soffset
6135       {},                                               // offset
6136       CachePolicy,                                      // cachepolicy
6137       DAG.getTargetConstant(0, DL, MVT::i1),            // idxen
6138   };
6139 
6140   // Use the alignment to ensure that the required offsets will fit into the
6141   // immediate offsets.
6142   setBufferOffsets(Offset, DAG, &Ops[3], NumLoads > 1 ? 16 * NumLoads : 4);
6143 
6144   uint64_t InstOffset = cast<ConstantSDNode>(Ops[5])->getZExtValue();
6145   for (unsigned i = 0; i < NumLoads; ++i) {
6146     Ops[5] = DAG.getTargetConstant(InstOffset + 16 * i, DL, MVT::i32);
6147     Loads.push_back(getMemIntrinsicNode(AMDGPUISD::BUFFER_LOAD, DL, VTList, Ops,
6148                                         LoadVT, MMO, DAG));
6149   }
6150 
6151   if (NumElts == 8 || NumElts == 16)
6152     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Loads);
6153 
6154   return Loads[0];
6155 }
6156 
6157 SDValue SITargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
6158                                                   SelectionDAG &DAG) const {
6159   MachineFunction &MF = DAG.getMachineFunction();
6160   auto MFI = MF.getInfo<SIMachineFunctionInfo>();
6161 
6162   EVT VT = Op.getValueType();
6163   SDLoc DL(Op);
6164   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
6165 
6166   // TODO: Should this propagate fast-math-flags?
6167 
6168   switch (IntrinsicID) {
6169   case Intrinsic::amdgcn_implicit_buffer_ptr: {
6170     if (getSubtarget()->isAmdHsaOrMesa(MF.getFunction()))
6171       return emitNonHSAIntrinsicError(DAG, DL, VT);
6172     return getPreloadedValue(DAG, *MFI, VT,
6173                              AMDGPUFunctionArgInfo::IMPLICIT_BUFFER_PTR);
6174   }
6175   case Intrinsic::amdgcn_dispatch_ptr:
6176   case Intrinsic::amdgcn_queue_ptr: {
6177     if (!Subtarget->isAmdHsaOrMesa(MF.getFunction())) {
6178       DiagnosticInfoUnsupported BadIntrin(
6179           MF.getFunction(), "unsupported hsa intrinsic without hsa target",
6180           DL.getDebugLoc());
6181       DAG.getContext()->diagnose(BadIntrin);
6182       return DAG.getUNDEF(VT);
6183     }
6184 
6185     auto RegID = IntrinsicID == Intrinsic::amdgcn_dispatch_ptr ?
6186       AMDGPUFunctionArgInfo::DISPATCH_PTR : AMDGPUFunctionArgInfo::QUEUE_PTR;
6187     return getPreloadedValue(DAG, *MFI, VT, RegID);
6188   }
6189   case Intrinsic::amdgcn_implicitarg_ptr: {
6190     if (MFI->isEntryFunction())
6191       return getImplicitArgPtr(DAG, DL);
6192     return getPreloadedValue(DAG, *MFI, VT,
6193                              AMDGPUFunctionArgInfo::IMPLICIT_ARG_PTR);
6194   }
6195   case Intrinsic::amdgcn_kernarg_segment_ptr: {
6196     if (!AMDGPU::isKernel(MF.getFunction().getCallingConv())) {
6197       // This only makes sense to call in a kernel, so just lower to null.
6198       return DAG.getConstant(0, DL, VT);
6199     }
6200 
6201     return getPreloadedValue(DAG, *MFI, VT,
6202                              AMDGPUFunctionArgInfo::KERNARG_SEGMENT_PTR);
6203   }
6204   case Intrinsic::amdgcn_dispatch_id: {
6205     return getPreloadedValue(DAG, *MFI, VT, AMDGPUFunctionArgInfo::DISPATCH_ID);
6206   }
6207   case Intrinsic::amdgcn_rcp:
6208     return DAG.getNode(AMDGPUISD::RCP, DL, VT, Op.getOperand(1));
6209   case Intrinsic::amdgcn_rsq:
6210     return DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6211   case Intrinsic::amdgcn_rsq_legacy:
6212     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6213       return emitRemovedIntrinsicError(DAG, DL, VT);
6214     return SDValue();
6215   case Intrinsic::amdgcn_rcp_legacy:
6216     if (Subtarget->getGeneration() >= AMDGPUSubtarget::VOLCANIC_ISLANDS)
6217       return emitRemovedIntrinsicError(DAG, DL, VT);
6218     return DAG.getNode(AMDGPUISD::RCP_LEGACY, DL, VT, Op.getOperand(1));
6219   case Intrinsic::amdgcn_rsq_clamp: {
6220     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6221       return DAG.getNode(AMDGPUISD::RSQ_CLAMP, DL, VT, Op.getOperand(1));
6222 
6223     Type *Type = VT.getTypeForEVT(*DAG.getContext());
6224     APFloat Max = APFloat::getLargest(Type->getFltSemantics());
6225     APFloat Min = APFloat::getLargest(Type->getFltSemantics(), true);
6226 
6227     SDValue Rsq = DAG.getNode(AMDGPUISD::RSQ, DL, VT, Op.getOperand(1));
6228     SDValue Tmp = DAG.getNode(ISD::FMINNUM, DL, VT, Rsq,
6229                               DAG.getConstantFP(Max, DL, VT));
6230     return DAG.getNode(ISD::FMAXNUM, DL, VT, Tmp,
6231                        DAG.getConstantFP(Min, DL, VT));
6232   }
6233   case Intrinsic::r600_read_ngroups_x:
6234     if (Subtarget->isAmdHsaOS())
6235       return emitNonHSAIntrinsicError(DAG, DL, VT);
6236 
6237     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6238                                     SI::KernelInputOffsets::NGROUPS_X, 4, false);
6239   case Intrinsic::r600_read_ngroups_y:
6240     if (Subtarget->isAmdHsaOS())
6241       return emitNonHSAIntrinsicError(DAG, DL, VT);
6242 
6243     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6244                                     SI::KernelInputOffsets::NGROUPS_Y, 4, false);
6245   case Intrinsic::r600_read_ngroups_z:
6246     if (Subtarget->isAmdHsaOS())
6247       return emitNonHSAIntrinsicError(DAG, DL, VT);
6248 
6249     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6250                                     SI::KernelInputOffsets::NGROUPS_Z, 4, false);
6251   case Intrinsic::r600_read_global_size_x:
6252     if (Subtarget->isAmdHsaOS())
6253       return emitNonHSAIntrinsicError(DAG, DL, VT);
6254 
6255     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6256                                     SI::KernelInputOffsets::GLOBAL_SIZE_X, 4, false);
6257   case Intrinsic::r600_read_global_size_y:
6258     if (Subtarget->isAmdHsaOS())
6259       return emitNonHSAIntrinsicError(DAG, DL, VT);
6260 
6261     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6262                                     SI::KernelInputOffsets::GLOBAL_SIZE_Y, 4, false);
6263   case Intrinsic::r600_read_global_size_z:
6264     if (Subtarget->isAmdHsaOS())
6265       return emitNonHSAIntrinsicError(DAG, DL, VT);
6266 
6267     return lowerKernargMemParameter(DAG, VT, VT, DL, DAG.getEntryNode(),
6268                                     SI::KernelInputOffsets::GLOBAL_SIZE_Z, 4, false);
6269   case Intrinsic::r600_read_local_size_x:
6270     if (Subtarget->isAmdHsaOS())
6271       return emitNonHSAIntrinsicError(DAG, DL, VT);
6272 
6273     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6274                                   SI::KernelInputOffsets::LOCAL_SIZE_X);
6275   case Intrinsic::r600_read_local_size_y:
6276     if (Subtarget->isAmdHsaOS())
6277       return emitNonHSAIntrinsicError(DAG, DL, VT);
6278 
6279     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6280                                   SI::KernelInputOffsets::LOCAL_SIZE_Y);
6281   case Intrinsic::r600_read_local_size_z:
6282     if (Subtarget->isAmdHsaOS())
6283       return emitNonHSAIntrinsicError(DAG, DL, VT);
6284 
6285     return lowerImplicitZextParam(DAG, Op, MVT::i16,
6286                                   SI::KernelInputOffsets::LOCAL_SIZE_Z);
6287   case Intrinsic::amdgcn_workgroup_id_x:
6288     return getPreloadedValue(DAG, *MFI, VT,
6289                              AMDGPUFunctionArgInfo::WORKGROUP_ID_X);
6290   case Intrinsic::amdgcn_workgroup_id_y:
6291     return getPreloadedValue(DAG, *MFI, VT,
6292                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Y);
6293   case Intrinsic::amdgcn_workgroup_id_z:
6294     return getPreloadedValue(DAG, *MFI, VT,
6295                              AMDGPUFunctionArgInfo::WORKGROUP_ID_Z);
6296   case Intrinsic::amdgcn_workitem_id_x:
6297     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6298                           SDLoc(DAG.getEntryNode()),
6299                           MFI->getArgInfo().WorkItemIDX);
6300   case Intrinsic::amdgcn_workitem_id_y:
6301     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6302                           SDLoc(DAG.getEntryNode()),
6303                           MFI->getArgInfo().WorkItemIDY);
6304   case Intrinsic::amdgcn_workitem_id_z:
6305     return loadInputValue(DAG, &AMDGPU::VGPR_32RegClass, MVT::i32,
6306                           SDLoc(DAG.getEntryNode()),
6307                           MFI->getArgInfo().WorkItemIDZ);
6308   case Intrinsic::amdgcn_wavefrontsize:
6309     return DAG.getConstant(MF.getSubtarget<GCNSubtarget>().getWavefrontSize(),
6310                            SDLoc(Op), MVT::i32);
6311   case Intrinsic::amdgcn_s_buffer_load: {
6312     bool IsGFX10 = Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10;
6313     SDValue GLC;
6314     SDValue DLC = DAG.getTargetConstant(0, DL, MVT::i1);
6315     if (!parseCachePolicy(Op.getOperand(3), DAG, &GLC, nullptr,
6316                           IsGFX10 ? &DLC : nullptr))
6317       return Op;
6318     return lowerSBuffer(VT, DL, Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6319                         DAG);
6320   }
6321   case Intrinsic::amdgcn_fdiv_fast:
6322     return lowerFDIV_FAST(Op, DAG);
6323   case Intrinsic::amdgcn_sin:
6324     return DAG.getNode(AMDGPUISD::SIN_HW, DL, VT, Op.getOperand(1));
6325 
6326   case Intrinsic::amdgcn_cos:
6327     return DAG.getNode(AMDGPUISD::COS_HW, DL, VT, Op.getOperand(1));
6328 
6329   case Intrinsic::amdgcn_mul_u24:
6330     return DAG.getNode(AMDGPUISD::MUL_U24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6331   case Intrinsic::amdgcn_mul_i24:
6332     return DAG.getNode(AMDGPUISD::MUL_I24, DL, VT, Op.getOperand(1), Op.getOperand(2));
6333 
6334   case Intrinsic::amdgcn_log_clamp: {
6335     if (Subtarget->getGeneration() < AMDGPUSubtarget::VOLCANIC_ISLANDS)
6336       return SDValue();
6337 
6338     DiagnosticInfoUnsupported BadIntrin(
6339       MF.getFunction(), "intrinsic not supported on subtarget",
6340       DL.getDebugLoc());
6341       DAG.getContext()->diagnose(BadIntrin);
6342       return DAG.getUNDEF(VT);
6343   }
6344   case Intrinsic::amdgcn_ldexp:
6345     return DAG.getNode(AMDGPUISD::LDEXP, DL, VT,
6346                        Op.getOperand(1), Op.getOperand(2));
6347 
6348   case Intrinsic::amdgcn_fract:
6349     return DAG.getNode(AMDGPUISD::FRACT, DL, VT, Op.getOperand(1));
6350 
6351   case Intrinsic::amdgcn_class:
6352     return DAG.getNode(AMDGPUISD::FP_CLASS, DL, VT,
6353                        Op.getOperand(1), Op.getOperand(2));
6354   case Intrinsic::amdgcn_div_fmas:
6355     return DAG.getNode(AMDGPUISD::DIV_FMAS, DL, VT,
6356                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6357                        Op.getOperand(4));
6358 
6359   case Intrinsic::amdgcn_div_fixup:
6360     return DAG.getNode(AMDGPUISD::DIV_FIXUP, DL, VT,
6361                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6362 
6363   case Intrinsic::amdgcn_trig_preop:
6364     return DAG.getNode(AMDGPUISD::TRIG_PREOP, DL, VT,
6365                        Op.getOperand(1), Op.getOperand(2));
6366   case Intrinsic::amdgcn_div_scale: {
6367     const ConstantSDNode *Param = cast<ConstantSDNode>(Op.getOperand(3));
6368 
6369     // Translate to the operands expected by the machine instruction. The
6370     // first parameter must be the same as the first instruction.
6371     SDValue Numerator = Op.getOperand(1);
6372     SDValue Denominator = Op.getOperand(2);
6373 
6374     // Note this order is opposite of the machine instruction's operations,
6375     // which is s0.f = Quotient, s1.f = Denominator, s2.f = Numerator. The
6376     // intrinsic has the numerator as the first operand to match a normal
6377     // division operation.
6378 
6379     SDValue Src0 = Param->isAllOnesValue() ? Numerator : Denominator;
6380 
6381     return DAG.getNode(AMDGPUISD::DIV_SCALE, DL, Op->getVTList(), Src0,
6382                        Denominator, Numerator);
6383   }
6384   case Intrinsic::amdgcn_icmp: {
6385     // There is a Pat that handles this variant, so return it as-is.
6386     if (Op.getOperand(1).getValueType() == MVT::i1 &&
6387         Op.getConstantOperandVal(2) == 0 &&
6388         Op.getConstantOperandVal(3) == ICmpInst::Predicate::ICMP_NE)
6389       return Op;
6390     return lowerICMPIntrinsic(*this, Op.getNode(), DAG);
6391   }
6392   case Intrinsic::amdgcn_fcmp: {
6393     return lowerFCMPIntrinsic(*this, Op.getNode(), DAG);
6394   }
6395   case Intrinsic::amdgcn_ballot:
6396     return lowerBALLOTIntrinsic(*this, Op.getNode(), DAG);
6397   case Intrinsic::amdgcn_fmed3:
6398     return DAG.getNode(AMDGPUISD::FMED3, DL, VT,
6399                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6400   case Intrinsic::amdgcn_fdot2:
6401     return DAG.getNode(AMDGPUISD::FDOT2, DL, VT,
6402                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3),
6403                        Op.getOperand(4));
6404   case Intrinsic::amdgcn_fmul_legacy:
6405     return DAG.getNode(AMDGPUISD::FMUL_LEGACY, DL, VT,
6406                        Op.getOperand(1), Op.getOperand(2));
6407   case Intrinsic::amdgcn_sffbh:
6408     return DAG.getNode(AMDGPUISD::FFBH_I32, DL, VT, Op.getOperand(1));
6409   case Intrinsic::amdgcn_sbfe:
6410     return DAG.getNode(AMDGPUISD::BFE_I32, DL, VT,
6411                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6412   case Intrinsic::amdgcn_ubfe:
6413     return DAG.getNode(AMDGPUISD::BFE_U32, DL, VT,
6414                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6415   case Intrinsic::amdgcn_cvt_pkrtz:
6416   case Intrinsic::amdgcn_cvt_pknorm_i16:
6417   case Intrinsic::amdgcn_cvt_pknorm_u16:
6418   case Intrinsic::amdgcn_cvt_pk_i16:
6419   case Intrinsic::amdgcn_cvt_pk_u16: {
6420     // FIXME: Stop adding cast if v2f16/v2i16 are legal.
6421     EVT VT = Op.getValueType();
6422     unsigned Opcode;
6423 
6424     if (IntrinsicID == Intrinsic::amdgcn_cvt_pkrtz)
6425       Opcode = AMDGPUISD::CVT_PKRTZ_F16_F32;
6426     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_i16)
6427       Opcode = AMDGPUISD::CVT_PKNORM_I16_F32;
6428     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pknorm_u16)
6429       Opcode = AMDGPUISD::CVT_PKNORM_U16_F32;
6430     else if (IntrinsicID == Intrinsic::amdgcn_cvt_pk_i16)
6431       Opcode = AMDGPUISD::CVT_PK_I16_I32;
6432     else
6433       Opcode = AMDGPUISD::CVT_PK_U16_U32;
6434 
6435     if (isTypeLegal(VT))
6436       return DAG.getNode(Opcode, DL, VT, Op.getOperand(1), Op.getOperand(2));
6437 
6438     SDValue Node = DAG.getNode(Opcode, DL, MVT::i32,
6439                                Op.getOperand(1), Op.getOperand(2));
6440     return DAG.getNode(ISD::BITCAST, DL, VT, Node);
6441   }
6442   case Intrinsic::amdgcn_fmad_ftz:
6443     return DAG.getNode(AMDGPUISD::FMAD_FTZ, DL, VT, Op.getOperand(1),
6444                        Op.getOperand(2), Op.getOperand(3));
6445 
6446   case Intrinsic::amdgcn_if_break:
6447     return SDValue(DAG.getMachineNode(AMDGPU::SI_IF_BREAK, DL, VT,
6448                                       Op->getOperand(1), Op->getOperand(2)), 0);
6449 
6450   case Intrinsic::amdgcn_groupstaticsize: {
6451     Triple::OSType OS = getTargetMachine().getTargetTriple().getOS();
6452     if (OS == Triple::AMDHSA || OS == Triple::AMDPAL)
6453       return Op;
6454 
6455     const Module *M = MF.getFunction().getParent();
6456     const GlobalValue *GV =
6457         M->getNamedValue(Intrinsic::getName(Intrinsic::amdgcn_groupstaticsize));
6458     SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
6459                                             SIInstrInfo::MO_ABS32_LO);
6460     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6461   }
6462   case Intrinsic::amdgcn_is_shared:
6463   case Intrinsic::amdgcn_is_private: {
6464     SDLoc SL(Op);
6465     unsigned AS = (IntrinsicID == Intrinsic::amdgcn_is_shared) ?
6466       AMDGPUAS::LOCAL_ADDRESS : AMDGPUAS::PRIVATE_ADDRESS;
6467     SDValue Aperture = getSegmentAperture(AS, SL, DAG);
6468     SDValue SrcVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32,
6469                                  Op.getOperand(1));
6470 
6471     SDValue SrcHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, SrcVec,
6472                                 DAG.getConstant(1, SL, MVT::i32));
6473     return DAG.getSetCC(SL, MVT::i1, SrcHi, Aperture, ISD::SETEQ);
6474   }
6475   case Intrinsic::amdgcn_alignbit:
6476     return DAG.getNode(ISD::FSHR, DL, VT,
6477                        Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
6478   case Intrinsic::amdgcn_reloc_constant: {
6479     Module *M = const_cast<Module *>(MF.getFunction().getParent());
6480     const MDNode *Metadata = cast<MDNodeSDNode>(Op.getOperand(1))->getMD();
6481     auto SymbolName = cast<MDString>(Metadata->getOperand(0))->getString();
6482     auto RelocSymbol = cast<GlobalVariable>(
6483         M->getOrInsertGlobal(SymbolName, Type::getInt32Ty(M->getContext())));
6484     SDValue GA = DAG.getTargetGlobalAddress(RelocSymbol, DL, MVT::i32, 0,
6485                                             SIInstrInfo::MO_ABS32_LO);
6486     return {DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, GA), 0};
6487   }
6488   default:
6489     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
6490             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
6491       return lowerImage(Op, ImageDimIntr, DAG);
6492 
6493     return Op;
6494   }
6495 }
6496 
6497 // This function computes an appropriate offset to pass to
6498 // MachineMemOperand::setOffset() based on the offset inputs to
6499 // an intrinsic.  If any of the offsets are non-contstant or
6500 // if VIndex is non-zero then this function returns 0.  Otherwise,
6501 // it returns the sum of VOffset, SOffset, and Offset.
6502 static unsigned getBufferOffsetForMMO(SDValue VOffset,
6503                                       SDValue SOffset,
6504                                       SDValue Offset,
6505                                       SDValue VIndex = SDValue()) {
6506 
6507   if (!isa<ConstantSDNode>(VOffset) || !isa<ConstantSDNode>(SOffset) ||
6508       !isa<ConstantSDNode>(Offset))
6509     return 0;
6510 
6511   if (VIndex) {
6512     if (!isa<ConstantSDNode>(VIndex) || !cast<ConstantSDNode>(VIndex)->isNullValue())
6513       return 0;
6514   }
6515 
6516   return cast<ConstantSDNode>(VOffset)->getSExtValue() +
6517          cast<ConstantSDNode>(SOffset)->getSExtValue() +
6518          cast<ConstantSDNode>(Offset)->getSExtValue();
6519 }
6520 
6521 static unsigned getDSShaderTypeValue(const MachineFunction &MF) {
6522   switch (MF.getFunction().getCallingConv()) {
6523   case CallingConv::AMDGPU_PS:
6524     return 1;
6525   case CallingConv::AMDGPU_VS:
6526     return 2;
6527   case CallingConv::AMDGPU_GS:
6528     return 3;
6529   case CallingConv::AMDGPU_HS:
6530   case CallingConv::AMDGPU_LS:
6531   case CallingConv::AMDGPU_ES:
6532     report_fatal_error("ds_ordered_count unsupported for this calling conv");
6533   case CallingConv::AMDGPU_CS:
6534   case CallingConv::AMDGPU_KERNEL:
6535   case CallingConv::C:
6536   case CallingConv::Fast:
6537   default:
6538     // Assume other calling conventions are various compute callable functions
6539     return 0;
6540   }
6541 }
6542 
6543 SDValue SITargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
6544                                                  SelectionDAG &DAG) const {
6545   unsigned IntrID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
6546   SDLoc DL(Op);
6547 
6548   switch (IntrID) {
6549   case Intrinsic::amdgcn_ds_ordered_add:
6550   case Intrinsic::amdgcn_ds_ordered_swap: {
6551     MemSDNode *M = cast<MemSDNode>(Op);
6552     SDValue Chain = M->getOperand(0);
6553     SDValue M0 = M->getOperand(2);
6554     SDValue Value = M->getOperand(3);
6555     unsigned IndexOperand = M->getConstantOperandVal(7);
6556     unsigned WaveRelease = M->getConstantOperandVal(8);
6557     unsigned WaveDone = M->getConstantOperandVal(9);
6558 
6559     unsigned OrderedCountIndex = IndexOperand & 0x3f;
6560     IndexOperand &= ~0x3f;
6561     unsigned CountDw = 0;
6562 
6563     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10) {
6564       CountDw = (IndexOperand >> 24) & 0xf;
6565       IndexOperand &= ~(0xf << 24);
6566 
6567       if (CountDw < 1 || CountDw > 4) {
6568         report_fatal_error(
6569             "ds_ordered_count: dword count must be between 1 and 4");
6570       }
6571     }
6572 
6573     if (IndexOperand)
6574       report_fatal_error("ds_ordered_count: bad index operand");
6575 
6576     if (WaveDone && !WaveRelease)
6577       report_fatal_error("ds_ordered_count: wave_done requires wave_release");
6578 
6579     unsigned Instruction = IntrID == Intrinsic::amdgcn_ds_ordered_add ? 0 : 1;
6580     unsigned ShaderType = getDSShaderTypeValue(DAG.getMachineFunction());
6581     unsigned Offset0 = OrderedCountIndex << 2;
6582     unsigned Offset1 = WaveRelease | (WaveDone << 1) | (ShaderType << 2) |
6583                        (Instruction << 4);
6584 
6585     if (Subtarget->getGeneration() >= AMDGPUSubtarget::GFX10)
6586       Offset1 |= (CountDw - 1) << 6;
6587 
6588     unsigned Offset = Offset0 | (Offset1 << 8);
6589 
6590     SDValue Ops[] = {
6591       Chain,
6592       Value,
6593       DAG.getTargetConstant(Offset, DL, MVT::i16),
6594       copyToM0(DAG, Chain, DL, M0).getValue(1), // Glue
6595     };
6596     return DAG.getMemIntrinsicNode(AMDGPUISD::DS_ORDERED_COUNT, DL,
6597                                    M->getVTList(), Ops, M->getMemoryVT(),
6598                                    M->getMemOperand());
6599   }
6600   case Intrinsic::amdgcn_ds_fadd: {
6601     MemSDNode *M = cast<MemSDNode>(Op);
6602     unsigned Opc;
6603     switch (IntrID) {
6604     case Intrinsic::amdgcn_ds_fadd:
6605       Opc = ISD::ATOMIC_LOAD_FADD;
6606       break;
6607     }
6608 
6609     return DAG.getAtomic(Opc, SDLoc(Op), M->getMemoryVT(),
6610                          M->getOperand(0), M->getOperand(2), M->getOperand(3),
6611                          M->getMemOperand());
6612   }
6613   case Intrinsic::amdgcn_atomic_inc:
6614   case Intrinsic::amdgcn_atomic_dec:
6615   case Intrinsic::amdgcn_ds_fmin:
6616   case Intrinsic::amdgcn_ds_fmax: {
6617     MemSDNode *M = cast<MemSDNode>(Op);
6618     unsigned Opc;
6619     switch (IntrID) {
6620     case Intrinsic::amdgcn_atomic_inc:
6621       Opc = AMDGPUISD::ATOMIC_INC;
6622       break;
6623     case Intrinsic::amdgcn_atomic_dec:
6624       Opc = AMDGPUISD::ATOMIC_DEC;
6625       break;
6626     case Intrinsic::amdgcn_ds_fmin:
6627       Opc = AMDGPUISD::ATOMIC_LOAD_FMIN;
6628       break;
6629     case Intrinsic::amdgcn_ds_fmax:
6630       Opc = AMDGPUISD::ATOMIC_LOAD_FMAX;
6631       break;
6632     default:
6633       llvm_unreachable("Unknown intrinsic!");
6634     }
6635     SDValue Ops[] = {
6636       M->getOperand(0), // Chain
6637       M->getOperand(2), // Ptr
6638       M->getOperand(3)  // Value
6639     };
6640 
6641     return DAG.getMemIntrinsicNode(Opc, SDLoc(Op), M->getVTList(), Ops,
6642                                    M->getMemoryVT(), M->getMemOperand());
6643   }
6644   case Intrinsic::amdgcn_buffer_load:
6645   case Intrinsic::amdgcn_buffer_load_format: {
6646     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(5))->getZExtValue();
6647     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6648     unsigned IdxEn = 1;
6649     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6650       IdxEn = Idx->getZExtValue() != 0;
6651     SDValue Ops[] = {
6652       Op.getOperand(0), // Chain
6653       Op.getOperand(2), // rsrc
6654       Op.getOperand(3), // vindex
6655       SDValue(),        // voffset -- will be set by setBufferOffsets
6656       SDValue(),        // soffset -- will be set by setBufferOffsets
6657       SDValue(),        // offset -- will be set by setBufferOffsets
6658       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6659       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6660     };
6661 
6662     unsigned Offset = setBufferOffsets(Op.getOperand(4), DAG, &Ops[3]);
6663     // We don't know the offset if vindex is non-zero, so clear it.
6664     if (IdxEn)
6665       Offset = 0;
6666 
6667     unsigned Opc = (IntrID == Intrinsic::amdgcn_buffer_load) ?
6668         AMDGPUISD::BUFFER_LOAD : AMDGPUISD::BUFFER_LOAD_FORMAT;
6669 
6670     EVT VT = Op.getValueType();
6671     EVT IntVT = VT.changeTypeToInteger();
6672     auto *M = cast<MemSDNode>(Op);
6673     M->getMemOperand()->setOffset(Offset);
6674     EVT LoadVT = Op.getValueType();
6675 
6676     if (LoadVT.getScalarType() == MVT::f16)
6677       return adjustLoadValueType(AMDGPUISD::BUFFER_LOAD_FORMAT_D16,
6678                                  M, DAG, Ops);
6679 
6680     // Handle BUFFER_LOAD_BYTE/UBYTE/SHORT/USHORT overloaded intrinsics
6681     if (LoadVT.getScalarType() == MVT::i8 ||
6682         LoadVT.getScalarType() == MVT::i16)
6683       return handleByteShortBufferLoads(DAG, LoadVT, DL, Ops, M);
6684 
6685     return getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops, IntVT,
6686                                M->getMemOperand(), DAG);
6687   }
6688   case Intrinsic::amdgcn_raw_buffer_load:
6689   case Intrinsic::amdgcn_raw_buffer_load_format: {
6690     const bool IsFormat = IntrID == Intrinsic::amdgcn_raw_buffer_load_format;
6691 
6692     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6693     SDValue Ops[] = {
6694       Op.getOperand(0), // Chain
6695       Op.getOperand(2), // rsrc
6696       DAG.getConstant(0, DL, MVT::i32), // vindex
6697       Offsets.first,    // voffset
6698       Op.getOperand(4), // soffset
6699       Offsets.second,   // offset
6700       Op.getOperand(5), // cachepolicy, swizzled buffer
6701       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6702     };
6703 
6704     auto *M = cast<MemSDNode>(Op);
6705     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5]));
6706     return lowerIntrinsicLoad(M, IsFormat, DAG, Ops);
6707   }
6708   case Intrinsic::amdgcn_struct_buffer_load:
6709   case Intrinsic::amdgcn_struct_buffer_load_format: {
6710     const bool IsFormat = IntrID == Intrinsic::amdgcn_struct_buffer_load_format;
6711 
6712     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6713     SDValue Ops[] = {
6714       Op.getOperand(0), // Chain
6715       Op.getOperand(2), // rsrc
6716       Op.getOperand(3), // vindex
6717       Offsets.first,    // voffset
6718       Op.getOperand(5), // soffset
6719       Offsets.second,   // offset
6720       Op.getOperand(6), // cachepolicy, swizzled buffer
6721       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6722     };
6723 
6724     auto *M = cast<MemSDNode>(Op);
6725     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[3], Ops[4], Ops[5],
6726                                                         Ops[2]));
6727     return lowerIntrinsicLoad(cast<MemSDNode>(Op), IsFormat, DAG, Ops);
6728   }
6729   case Intrinsic::amdgcn_tbuffer_load: {
6730     MemSDNode *M = cast<MemSDNode>(Op);
6731     EVT LoadVT = Op.getValueType();
6732 
6733     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
6734     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
6735     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
6736     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
6737     unsigned IdxEn = 1;
6738     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(3)))
6739       IdxEn = Idx->getZExtValue() != 0;
6740     SDValue Ops[] = {
6741       Op.getOperand(0),  // Chain
6742       Op.getOperand(2),  // rsrc
6743       Op.getOperand(3),  // vindex
6744       Op.getOperand(4),  // voffset
6745       Op.getOperand(5),  // soffset
6746       Op.getOperand(6),  // offset
6747       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
6748       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
6749       DAG.getTargetConstant(IdxEn, DL, MVT::i1) // idxen
6750     };
6751 
6752     if (LoadVT.getScalarType() == MVT::f16)
6753       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6754                                  M, DAG, Ops);
6755     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6756                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6757                                DAG);
6758   }
6759   case Intrinsic::amdgcn_raw_tbuffer_load: {
6760     MemSDNode *M = cast<MemSDNode>(Op);
6761     EVT LoadVT = Op.getValueType();
6762     auto Offsets = splitBufferOffsets(Op.getOperand(3), DAG);
6763 
6764     SDValue Ops[] = {
6765       Op.getOperand(0),  // Chain
6766       Op.getOperand(2),  // rsrc
6767       DAG.getConstant(0, DL, MVT::i32), // vindex
6768       Offsets.first,     // voffset
6769       Op.getOperand(4),  // soffset
6770       Offsets.second,    // offset
6771       Op.getOperand(5),  // format
6772       Op.getOperand(6),  // cachepolicy, swizzled buffer
6773       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6774     };
6775 
6776     if (LoadVT.getScalarType() == MVT::f16)
6777       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6778                                  M, DAG, Ops);
6779     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6780                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6781                                DAG);
6782   }
6783   case Intrinsic::amdgcn_struct_tbuffer_load: {
6784     MemSDNode *M = cast<MemSDNode>(Op);
6785     EVT LoadVT = Op.getValueType();
6786     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6787 
6788     SDValue Ops[] = {
6789       Op.getOperand(0),  // Chain
6790       Op.getOperand(2),  // rsrc
6791       Op.getOperand(3),  // vindex
6792       Offsets.first,     // voffset
6793       Op.getOperand(5),  // soffset
6794       Offsets.second,    // offset
6795       Op.getOperand(6),  // format
6796       Op.getOperand(7),  // cachepolicy, swizzled buffer
6797       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6798     };
6799 
6800     if (LoadVT.getScalarType() == MVT::f16)
6801       return adjustLoadValueType(AMDGPUISD::TBUFFER_LOAD_FORMAT_D16,
6802                                  M, DAG, Ops);
6803     return getMemIntrinsicNode(AMDGPUISD::TBUFFER_LOAD_FORMAT, DL,
6804                                Op->getVTList(), Ops, LoadVT, M->getMemOperand(),
6805                                DAG);
6806   }
6807   case Intrinsic::amdgcn_buffer_atomic_swap:
6808   case Intrinsic::amdgcn_buffer_atomic_add:
6809   case Intrinsic::amdgcn_buffer_atomic_sub:
6810   case Intrinsic::amdgcn_buffer_atomic_smin:
6811   case Intrinsic::amdgcn_buffer_atomic_umin:
6812   case Intrinsic::amdgcn_buffer_atomic_smax:
6813   case Intrinsic::amdgcn_buffer_atomic_umax:
6814   case Intrinsic::amdgcn_buffer_atomic_and:
6815   case Intrinsic::amdgcn_buffer_atomic_or:
6816   case Intrinsic::amdgcn_buffer_atomic_xor: {
6817     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
6818     unsigned IdxEn = 1;
6819     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
6820       IdxEn = Idx->getZExtValue() != 0;
6821     SDValue Ops[] = {
6822       Op.getOperand(0), // Chain
6823       Op.getOperand(2), // vdata
6824       Op.getOperand(3), // rsrc
6825       Op.getOperand(4), // vindex
6826       SDValue(),        // voffset -- will be set by setBufferOffsets
6827       SDValue(),        // soffset -- will be set by setBufferOffsets
6828       SDValue(),        // offset -- will be set by setBufferOffsets
6829       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
6830       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
6831     };
6832     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
6833     // We don't know the offset if vindex is non-zero, so clear it.
6834     if (IdxEn)
6835       Offset = 0;
6836     EVT VT = Op.getValueType();
6837 
6838     auto *M = cast<MemSDNode>(Op);
6839     M->getMemOperand()->setOffset(Offset);
6840     unsigned Opcode = 0;
6841 
6842     switch (IntrID) {
6843     case Intrinsic::amdgcn_buffer_atomic_swap:
6844       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6845       break;
6846     case Intrinsic::amdgcn_buffer_atomic_add:
6847       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6848       break;
6849     case Intrinsic::amdgcn_buffer_atomic_sub:
6850       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6851       break;
6852     case Intrinsic::amdgcn_buffer_atomic_smin:
6853       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6854       break;
6855     case Intrinsic::amdgcn_buffer_atomic_umin:
6856       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6857       break;
6858     case Intrinsic::amdgcn_buffer_atomic_smax:
6859       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6860       break;
6861     case Intrinsic::amdgcn_buffer_atomic_umax:
6862       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6863       break;
6864     case Intrinsic::amdgcn_buffer_atomic_and:
6865       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6866       break;
6867     case Intrinsic::amdgcn_buffer_atomic_or:
6868       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6869       break;
6870     case Intrinsic::amdgcn_buffer_atomic_xor:
6871       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6872       break;
6873     default:
6874       llvm_unreachable("unhandled atomic opcode");
6875     }
6876 
6877     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6878                                    M->getMemOperand());
6879   }
6880   case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6881   case Intrinsic::amdgcn_raw_buffer_atomic_add:
6882   case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6883   case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6884   case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6885   case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6886   case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6887   case Intrinsic::amdgcn_raw_buffer_atomic_and:
6888   case Intrinsic::amdgcn_raw_buffer_atomic_or:
6889   case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6890   case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6891   case Intrinsic::amdgcn_raw_buffer_atomic_dec: {
6892     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
6893     SDValue Ops[] = {
6894       Op.getOperand(0), // Chain
6895       Op.getOperand(2), // vdata
6896       Op.getOperand(3), // rsrc
6897       DAG.getConstant(0, DL, MVT::i32), // vindex
6898       Offsets.first,    // voffset
6899       Op.getOperand(5), // soffset
6900       Offsets.second,   // offset
6901       Op.getOperand(6), // cachepolicy
6902       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
6903     };
6904     EVT VT = Op.getValueType();
6905 
6906     auto *M = cast<MemSDNode>(Op);
6907     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
6908     unsigned Opcode = 0;
6909 
6910     switch (IntrID) {
6911     case Intrinsic::amdgcn_raw_buffer_atomic_swap:
6912       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6913       break;
6914     case Intrinsic::amdgcn_raw_buffer_atomic_add:
6915       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6916       break;
6917     case Intrinsic::amdgcn_raw_buffer_atomic_sub:
6918       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6919       break;
6920     case Intrinsic::amdgcn_raw_buffer_atomic_smin:
6921       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6922       break;
6923     case Intrinsic::amdgcn_raw_buffer_atomic_umin:
6924       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
6925       break;
6926     case Intrinsic::amdgcn_raw_buffer_atomic_smax:
6927       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
6928       break;
6929     case Intrinsic::amdgcn_raw_buffer_atomic_umax:
6930       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
6931       break;
6932     case Intrinsic::amdgcn_raw_buffer_atomic_and:
6933       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
6934       break;
6935     case Intrinsic::amdgcn_raw_buffer_atomic_or:
6936       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
6937       break;
6938     case Intrinsic::amdgcn_raw_buffer_atomic_xor:
6939       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
6940       break;
6941     case Intrinsic::amdgcn_raw_buffer_atomic_inc:
6942       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
6943       break;
6944     case Intrinsic::amdgcn_raw_buffer_atomic_dec:
6945       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
6946       break;
6947     default:
6948       llvm_unreachable("unhandled atomic opcode");
6949     }
6950 
6951     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
6952                                    M->getMemOperand());
6953   }
6954   case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6955   case Intrinsic::amdgcn_struct_buffer_atomic_add:
6956   case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6957   case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6958   case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6959   case Intrinsic::amdgcn_struct_buffer_atomic_smax:
6960   case Intrinsic::amdgcn_struct_buffer_atomic_umax:
6961   case Intrinsic::amdgcn_struct_buffer_atomic_and:
6962   case Intrinsic::amdgcn_struct_buffer_atomic_or:
6963   case Intrinsic::amdgcn_struct_buffer_atomic_xor:
6964   case Intrinsic::amdgcn_struct_buffer_atomic_inc:
6965   case Intrinsic::amdgcn_struct_buffer_atomic_dec: {
6966     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
6967     SDValue Ops[] = {
6968       Op.getOperand(0), // Chain
6969       Op.getOperand(2), // vdata
6970       Op.getOperand(3), // rsrc
6971       Op.getOperand(4), // vindex
6972       Offsets.first,    // voffset
6973       Op.getOperand(6), // soffset
6974       Offsets.second,   // offset
6975       Op.getOperand(7), // cachepolicy
6976       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
6977     };
6978     EVT VT = Op.getValueType();
6979 
6980     auto *M = cast<MemSDNode>(Op);
6981     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
6982                                                         Ops[3]));
6983     unsigned Opcode = 0;
6984 
6985     switch (IntrID) {
6986     case Intrinsic::amdgcn_struct_buffer_atomic_swap:
6987       Opcode = AMDGPUISD::BUFFER_ATOMIC_SWAP;
6988       break;
6989     case Intrinsic::amdgcn_struct_buffer_atomic_add:
6990       Opcode = AMDGPUISD::BUFFER_ATOMIC_ADD;
6991       break;
6992     case Intrinsic::amdgcn_struct_buffer_atomic_sub:
6993       Opcode = AMDGPUISD::BUFFER_ATOMIC_SUB;
6994       break;
6995     case Intrinsic::amdgcn_struct_buffer_atomic_smin:
6996       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMIN;
6997       break;
6998     case Intrinsic::amdgcn_struct_buffer_atomic_umin:
6999       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMIN;
7000       break;
7001     case Intrinsic::amdgcn_struct_buffer_atomic_smax:
7002       Opcode = AMDGPUISD::BUFFER_ATOMIC_SMAX;
7003       break;
7004     case Intrinsic::amdgcn_struct_buffer_atomic_umax:
7005       Opcode = AMDGPUISD::BUFFER_ATOMIC_UMAX;
7006       break;
7007     case Intrinsic::amdgcn_struct_buffer_atomic_and:
7008       Opcode = AMDGPUISD::BUFFER_ATOMIC_AND;
7009       break;
7010     case Intrinsic::amdgcn_struct_buffer_atomic_or:
7011       Opcode = AMDGPUISD::BUFFER_ATOMIC_OR;
7012       break;
7013     case Intrinsic::amdgcn_struct_buffer_atomic_xor:
7014       Opcode = AMDGPUISD::BUFFER_ATOMIC_XOR;
7015       break;
7016     case Intrinsic::amdgcn_struct_buffer_atomic_inc:
7017       Opcode = AMDGPUISD::BUFFER_ATOMIC_INC;
7018       break;
7019     case Intrinsic::amdgcn_struct_buffer_atomic_dec:
7020       Opcode = AMDGPUISD::BUFFER_ATOMIC_DEC;
7021       break;
7022     default:
7023       llvm_unreachable("unhandled atomic opcode");
7024     }
7025 
7026     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7027                                    M->getMemOperand());
7028   }
7029   case Intrinsic::amdgcn_buffer_atomic_cmpswap: {
7030     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7031     unsigned IdxEn = 1;
7032     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(5)))
7033       IdxEn = Idx->getZExtValue() != 0;
7034     SDValue Ops[] = {
7035       Op.getOperand(0), // Chain
7036       Op.getOperand(2), // src
7037       Op.getOperand(3), // cmp
7038       Op.getOperand(4), // rsrc
7039       Op.getOperand(5), // vindex
7040       SDValue(),        // voffset -- will be set by setBufferOffsets
7041       SDValue(),        // soffset -- will be set by setBufferOffsets
7042       SDValue(),        // offset -- will be set by setBufferOffsets
7043       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7044       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7045     };
7046     unsigned Offset = setBufferOffsets(Op.getOperand(6), DAG, &Ops[5]);
7047     // We don't know the offset if vindex is non-zero, so clear it.
7048     if (IdxEn)
7049       Offset = 0;
7050     EVT VT = Op.getValueType();
7051     auto *M = cast<MemSDNode>(Op);
7052     M->getMemOperand()->setOffset(Offset);
7053 
7054     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7055                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7056   }
7057   case Intrinsic::amdgcn_raw_buffer_atomic_cmpswap: {
7058     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7059     SDValue Ops[] = {
7060       Op.getOperand(0), // Chain
7061       Op.getOperand(2), // src
7062       Op.getOperand(3), // cmp
7063       Op.getOperand(4), // rsrc
7064       DAG.getConstant(0, DL, MVT::i32), // vindex
7065       Offsets.first,    // voffset
7066       Op.getOperand(6), // soffset
7067       Offsets.second,   // offset
7068       Op.getOperand(7), // cachepolicy
7069       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7070     };
7071     EVT VT = Op.getValueType();
7072     auto *M = cast<MemSDNode>(Op);
7073     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7]));
7074 
7075     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7076                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7077   }
7078   case Intrinsic::amdgcn_struct_buffer_atomic_cmpswap: {
7079     auto Offsets = splitBufferOffsets(Op.getOperand(6), DAG);
7080     SDValue Ops[] = {
7081       Op.getOperand(0), // Chain
7082       Op.getOperand(2), // src
7083       Op.getOperand(3), // cmp
7084       Op.getOperand(4), // rsrc
7085       Op.getOperand(5), // vindex
7086       Offsets.first,    // voffset
7087       Op.getOperand(7), // soffset
7088       Offsets.second,   // offset
7089       Op.getOperand(8), // cachepolicy
7090       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7091     };
7092     EVT VT = Op.getValueType();
7093     auto *M = cast<MemSDNode>(Op);
7094     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[5], Ops[6], Ops[7],
7095                                                         Ops[4]));
7096 
7097     return DAG.getMemIntrinsicNode(AMDGPUISD::BUFFER_ATOMIC_CMPSWAP, DL,
7098                                    Op->getVTList(), Ops, VT, M->getMemOperand());
7099   }
7100 
7101   default:
7102     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7103             AMDGPU::getImageDimIntrinsicInfo(IntrID))
7104       return lowerImage(Op, ImageDimIntr, DAG);
7105 
7106     return SDValue();
7107   }
7108 }
7109 
7110 // Call DAG.getMemIntrinsicNode for a load, but first widen a dwordx3 type to
7111 // dwordx4 if on SI.
7112 SDValue SITargetLowering::getMemIntrinsicNode(unsigned Opcode, const SDLoc &DL,
7113                                               SDVTList VTList,
7114                                               ArrayRef<SDValue> Ops, EVT MemVT,
7115                                               MachineMemOperand *MMO,
7116                                               SelectionDAG &DAG) const {
7117   EVT VT = VTList.VTs[0];
7118   EVT WidenedVT = VT;
7119   EVT WidenedMemVT = MemVT;
7120   if (!Subtarget->hasDwordx3LoadStores() &&
7121       (WidenedVT == MVT::v3i32 || WidenedVT == MVT::v3f32)) {
7122     WidenedVT = EVT::getVectorVT(*DAG.getContext(),
7123                                  WidenedVT.getVectorElementType(), 4);
7124     WidenedMemVT = EVT::getVectorVT(*DAG.getContext(),
7125                                     WidenedMemVT.getVectorElementType(), 4);
7126     MMO = DAG.getMachineFunction().getMachineMemOperand(MMO, 0, 16);
7127   }
7128 
7129   assert(VTList.NumVTs == 2);
7130   SDVTList WidenedVTList = DAG.getVTList(WidenedVT, VTList.VTs[1]);
7131 
7132   auto NewOp = DAG.getMemIntrinsicNode(Opcode, DL, WidenedVTList, Ops,
7133                                        WidenedMemVT, MMO);
7134   if (WidenedVT != VT) {
7135     auto Extract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, NewOp,
7136                                DAG.getVectorIdxConstant(0, DL));
7137     NewOp = DAG.getMergeValues({ Extract, SDValue(NewOp.getNode(), 1) }, DL);
7138   }
7139   return NewOp;
7140 }
7141 
7142 SDValue SITargetLowering::handleD16VData(SDValue VData,
7143                                          SelectionDAG &DAG) const {
7144   EVT StoreVT = VData.getValueType();
7145 
7146   // No change for f16 and legal vector D16 types.
7147   if (!StoreVT.isVector())
7148     return VData;
7149 
7150   SDLoc DL(VData);
7151   assert((StoreVT.getVectorNumElements() != 3) && "Handle v3f16");
7152 
7153   if (Subtarget->hasUnpackedD16VMem()) {
7154     // We need to unpack the packed data to store.
7155     EVT IntStoreVT = StoreVT.changeTypeToInteger();
7156     SDValue IntVData = DAG.getNode(ISD::BITCAST, DL, IntStoreVT, VData);
7157 
7158     EVT EquivStoreVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
7159                                         StoreVT.getVectorNumElements());
7160     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, EquivStoreVT, IntVData);
7161     return DAG.UnrollVectorOp(ZExt.getNode());
7162   }
7163 
7164   assert(isTypeLegal(StoreVT));
7165   return VData;
7166 }
7167 
7168 SDValue SITargetLowering::LowerINTRINSIC_VOID(SDValue Op,
7169                                               SelectionDAG &DAG) const {
7170   SDLoc DL(Op);
7171   SDValue Chain = Op.getOperand(0);
7172   unsigned IntrinsicID = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
7173   MachineFunction &MF = DAG.getMachineFunction();
7174 
7175   switch (IntrinsicID) {
7176   case Intrinsic::amdgcn_exp_compr: {
7177     SDValue Src0 = Op.getOperand(4);
7178     SDValue Src1 = Op.getOperand(5);
7179     // Hack around illegal type on SI by directly selecting it.
7180     if (isTypeLegal(Src0.getValueType()))
7181       return SDValue();
7182 
7183     const ConstantSDNode *Done = cast<ConstantSDNode>(Op.getOperand(6));
7184     SDValue Undef = DAG.getUNDEF(MVT::f32);
7185     const SDValue Ops[] = {
7186       Op.getOperand(2), // tgt
7187       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src0), // src0
7188       DAG.getNode(ISD::BITCAST, DL, MVT::f32, Src1), // src1
7189       Undef, // src2
7190       Undef, // src3
7191       Op.getOperand(7), // vm
7192       DAG.getTargetConstant(1, DL, MVT::i1), // compr
7193       Op.getOperand(3), // en
7194       Op.getOperand(0) // Chain
7195     };
7196 
7197     unsigned Opc = Done->isNullValue() ? AMDGPU::EXP : AMDGPU::EXP_DONE;
7198     return SDValue(DAG.getMachineNode(Opc, DL, Op->getVTList(), Ops), 0);
7199   }
7200   case Intrinsic::amdgcn_s_barrier: {
7201     if (getTargetMachine().getOptLevel() > CodeGenOpt::None) {
7202       const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
7203       unsigned WGSize = ST.getFlatWorkGroupSizes(MF.getFunction()).second;
7204       if (WGSize <= ST.getWavefrontSize())
7205         return SDValue(DAG.getMachineNode(AMDGPU::WAVE_BARRIER, DL, MVT::Other,
7206                                           Op.getOperand(0)), 0);
7207     }
7208     return SDValue();
7209   };
7210   case Intrinsic::amdgcn_tbuffer_store: {
7211     SDValue VData = Op.getOperand(2);
7212     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7213     if (IsD16)
7214       VData = handleD16VData(VData, DAG);
7215     unsigned Dfmt = cast<ConstantSDNode>(Op.getOperand(8))->getZExtValue();
7216     unsigned Nfmt = cast<ConstantSDNode>(Op.getOperand(9))->getZExtValue();
7217     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(10))->getZExtValue();
7218     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(11))->getZExtValue();
7219     unsigned IdxEn = 1;
7220     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7221       IdxEn = Idx->getZExtValue() != 0;
7222     SDValue Ops[] = {
7223       Chain,
7224       VData,             // vdata
7225       Op.getOperand(3),  // rsrc
7226       Op.getOperand(4),  // vindex
7227       Op.getOperand(5),  // voffset
7228       Op.getOperand(6),  // soffset
7229       Op.getOperand(7),  // offset
7230       DAG.getTargetConstant(Dfmt | (Nfmt << 4), DL, MVT::i32), // format
7231       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7232       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idexen
7233     };
7234     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7235                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7236     MemSDNode *M = cast<MemSDNode>(Op);
7237     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7238                                    M->getMemoryVT(), M->getMemOperand());
7239   }
7240 
7241   case Intrinsic::amdgcn_struct_tbuffer_store: {
7242     SDValue VData = Op.getOperand(2);
7243     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7244     if (IsD16)
7245       VData = handleD16VData(VData, DAG);
7246     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7247     SDValue Ops[] = {
7248       Chain,
7249       VData,             // vdata
7250       Op.getOperand(3),  // rsrc
7251       Op.getOperand(4),  // vindex
7252       Offsets.first,     // voffset
7253       Op.getOperand(6),  // soffset
7254       Offsets.second,    // offset
7255       Op.getOperand(7),  // format
7256       Op.getOperand(8),  // cachepolicy, swizzled buffer
7257       DAG.getTargetConstant(1, DL, MVT::i1), // idexen
7258     };
7259     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7260                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7261     MemSDNode *M = cast<MemSDNode>(Op);
7262     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7263                                    M->getMemoryVT(), M->getMemOperand());
7264   }
7265 
7266   case Intrinsic::amdgcn_raw_tbuffer_store: {
7267     SDValue VData = Op.getOperand(2);
7268     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7269     if (IsD16)
7270       VData = handleD16VData(VData, DAG);
7271     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7272     SDValue Ops[] = {
7273       Chain,
7274       VData,             // vdata
7275       Op.getOperand(3),  // rsrc
7276       DAG.getConstant(0, DL, MVT::i32), // vindex
7277       Offsets.first,     // voffset
7278       Op.getOperand(5),  // soffset
7279       Offsets.second,    // offset
7280       Op.getOperand(6),  // format
7281       Op.getOperand(7),  // cachepolicy, swizzled buffer
7282       DAG.getTargetConstant(0, DL, MVT::i1), // idexen
7283     };
7284     unsigned Opc = IsD16 ? AMDGPUISD::TBUFFER_STORE_FORMAT_D16 :
7285                            AMDGPUISD::TBUFFER_STORE_FORMAT;
7286     MemSDNode *M = cast<MemSDNode>(Op);
7287     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7288                                    M->getMemoryVT(), M->getMemOperand());
7289   }
7290 
7291   case Intrinsic::amdgcn_buffer_store:
7292   case Intrinsic::amdgcn_buffer_store_format: {
7293     SDValue VData = Op.getOperand(2);
7294     bool IsD16 = (VData.getValueType().getScalarType() == MVT::f16);
7295     if (IsD16)
7296       VData = handleD16VData(VData, DAG);
7297     unsigned Glc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7298     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(7))->getZExtValue();
7299     unsigned IdxEn = 1;
7300     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7301       IdxEn = Idx->getZExtValue() != 0;
7302     SDValue Ops[] = {
7303       Chain,
7304       VData,
7305       Op.getOperand(3), // rsrc
7306       Op.getOperand(4), // vindex
7307       SDValue(), // voffset -- will be set by setBufferOffsets
7308       SDValue(), // soffset -- will be set by setBufferOffsets
7309       SDValue(), // offset -- will be set by setBufferOffsets
7310       DAG.getTargetConstant(Glc | (Slc << 1), DL, MVT::i32), // cachepolicy
7311       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7312     };
7313     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7314     // We don't know the offset if vindex is non-zero, so clear it.
7315     if (IdxEn)
7316       Offset = 0;
7317     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_buffer_store ?
7318                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7319     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7320     MemSDNode *M = cast<MemSDNode>(Op);
7321     M->getMemOperand()->setOffset(Offset);
7322 
7323     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7324     EVT VDataType = VData.getValueType().getScalarType();
7325     if (VDataType == MVT::i8 || VDataType == MVT::i16)
7326       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7327 
7328     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7329                                    M->getMemoryVT(), M->getMemOperand());
7330   }
7331 
7332   case Intrinsic::amdgcn_raw_buffer_store:
7333   case Intrinsic::amdgcn_raw_buffer_store_format: {
7334     const bool IsFormat =
7335         IntrinsicID == Intrinsic::amdgcn_raw_buffer_store_format;
7336 
7337     SDValue VData = Op.getOperand(2);
7338     EVT VDataVT = VData.getValueType();
7339     EVT EltType = VDataVT.getScalarType();
7340     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7341     if (IsD16)
7342       VData = handleD16VData(VData, DAG);
7343 
7344     if (!isTypeLegal(VDataVT)) {
7345       VData =
7346           DAG.getNode(ISD::BITCAST, DL,
7347                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7348     }
7349 
7350     auto Offsets = splitBufferOffsets(Op.getOperand(4), DAG);
7351     SDValue Ops[] = {
7352       Chain,
7353       VData,
7354       Op.getOperand(3), // rsrc
7355       DAG.getConstant(0, DL, MVT::i32), // vindex
7356       Offsets.first,    // voffset
7357       Op.getOperand(5), // soffset
7358       Offsets.second,   // offset
7359       Op.getOperand(6), // cachepolicy, swizzled buffer
7360       DAG.getTargetConstant(0, DL, MVT::i1), // idxen
7361     };
7362     unsigned Opc =
7363         IsFormat ? AMDGPUISD::BUFFER_STORE_FORMAT : AMDGPUISD::BUFFER_STORE;
7364     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7365     MemSDNode *M = cast<MemSDNode>(Op);
7366     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6]));
7367 
7368     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7369     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7370       return handleByteShortBufferStores(DAG, VDataVT, DL, Ops, M);
7371 
7372     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7373                                    M->getMemoryVT(), M->getMemOperand());
7374   }
7375 
7376   case Intrinsic::amdgcn_struct_buffer_store:
7377   case Intrinsic::amdgcn_struct_buffer_store_format: {
7378     const bool IsFormat =
7379         IntrinsicID == Intrinsic::amdgcn_struct_buffer_store_format;
7380 
7381     SDValue VData = Op.getOperand(2);
7382     EVT VDataVT = VData.getValueType();
7383     EVT EltType = VDataVT.getScalarType();
7384     bool IsD16 = IsFormat && (EltType.getSizeInBits() == 16);
7385 
7386     if (IsD16)
7387       VData = handleD16VData(VData, DAG);
7388 
7389     if (!isTypeLegal(VDataVT)) {
7390       VData =
7391           DAG.getNode(ISD::BITCAST, DL,
7392                       getEquivalentMemType(*DAG.getContext(), VDataVT), VData);
7393     }
7394 
7395     auto Offsets = splitBufferOffsets(Op.getOperand(5), DAG);
7396     SDValue Ops[] = {
7397       Chain,
7398       VData,
7399       Op.getOperand(3), // rsrc
7400       Op.getOperand(4), // vindex
7401       Offsets.first,    // voffset
7402       Op.getOperand(6), // soffset
7403       Offsets.second,   // offset
7404       Op.getOperand(7), // cachepolicy, swizzled buffer
7405       DAG.getTargetConstant(1, DL, MVT::i1), // idxen
7406     };
7407     unsigned Opc = IntrinsicID == Intrinsic::amdgcn_struct_buffer_store ?
7408                    AMDGPUISD::BUFFER_STORE : AMDGPUISD::BUFFER_STORE_FORMAT;
7409     Opc = IsD16 ? AMDGPUISD::BUFFER_STORE_FORMAT_D16 : Opc;
7410     MemSDNode *M = cast<MemSDNode>(Op);
7411     M->getMemOperand()->setOffset(getBufferOffsetForMMO(Ops[4], Ops[5], Ops[6],
7412                                                         Ops[3]));
7413 
7414     // Handle BUFFER_STORE_BYTE/SHORT overloaded intrinsics
7415     EVT VDataType = VData.getValueType().getScalarType();
7416     if (!IsD16 && !VDataVT.isVector() && EltType.getSizeInBits() < 32)
7417       return handleByteShortBufferStores(DAG, VDataType, DL, Ops, M);
7418 
7419     return DAG.getMemIntrinsicNode(Opc, DL, Op->getVTList(), Ops,
7420                                    M->getMemoryVT(), M->getMemOperand());
7421   }
7422 
7423   case Intrinsic::amdgcn_buffer_atomic_fadd: {
7424     unsigned Slc = cast<ConstantSDNode>(Op.getOperand(6))->getZExtValue();
7425     unsigned IdxEn = 1;
7426     if (auto Idx = dyn_cast<ConstantSDNode>(Op.getOperand(4)))
7427       IdxEn = Idx->getZExtValue() != 0;
7428     SDValue Ops[] = {
7429       Chain,
7430       Op.getOperand(2), // vdata
7431       Op.getOperand(3), // rsrc
7432       Op.getOperand(4), // vindex
7433       SDValue(),        // voffset -- will be set by setBufferOffsets
7434       SDValue(),        // soffset -- will be set by setBufferOffsets
7435       SDValue(),        // offset -- will be set by setBufferOffsets
7436       DAG.getTargetConstant(Slc << 1, DL, MVT::i32), // cachepolicy
7437       DAG.getTargetConstant(IdxEn, DL, MVT::i1), // idxen
7438     };
7439     unsigned Offset = setBufferOffsets(Op.getOperand(5), DAG, &Ops[4]);
7440     // We don't know the offset if vindex is non-zero, so clear it.
7441     if (IdxEn)
7442       Offset = 0;
7443     EVT VT = Op.getOperand(2).getValueType();
7444 
7445     auto *M = cast<MemSDNode>(Op);
7446     M->getMemOperand()->setOffset(Offset);
7447     unsigned Opcode = VT.isVector() ? AMDGPUISD::BUFFER_ATOMIC_PK_FADD
7448                                     : AMDGPUISD::BUFFER_ATOMIC_FADD;
7449 
7450     return DAG.getMemIntrinsicNode(Opcode, DL, Op->getVTList(), Ops, VT,
7451                                    M->getMemOperand());
7452   }
7453 
7454   case Intrinsic::amdgcn_global_atomic_fadd: {
7455     SDValue Ops[] = {
7456       Chain,
7457       Op.getOperand(2), // ptr
7458       Op.getOperand(3)  // vdata
7459     };
7460     EVT VT = Op.getOperand(3).getValueType();
7461 
7462     auto *M = cast<MemSDNode>(Op);
7463     if (VT.isVector()) {
7464       return DAG.getMemIntrinsicNode(
7465         AMDGPUISD::ATOMIC_PK_FADD, DL, Op->getVTList(), Ops, VT,
7466         M->getMemOperand());
7467     }
7468 
7469     return DAG.getAtomic(ISD::ATOMIC_LOAD_FADD, DL, VT,
7470                          DAG.getVTList(VT, MVT::Other), Ops,
7471                          M->getMemOperand()).getValue(1);
7472   }
7473   case Intrinsic::amdgcn_end_cf:
7474     return SDValue(DAG.getMachineNode(AMDGPU::SI_END_CF, DL, MVT::Other,
7475                                       Op->getOperand(2), Chain), 0);
7476 
7477   default: {
7478     if (const AMDGPU::ImageDimIntrinsicInfo *ImageDimIntr =
7479             AMDGPU::getImageDimIntrinsicInfo(IntrinsicID))
7480       return lowerImage(Op, ImageDimIntr, DAG);
7481 
7482     return Op;
7483   }
7484   }
7485 }
7486 
7487 // The raw.(t)buffer and struct.(t)buffer intrinsics have two offset args:
7488 // offset (the offset that is included in bounds checking and swizzling, to be
7489 // split between the instruction's voffset and immoffset fields) and soffset
7490 // (the offset that is excluded from bounds checking and swizzling, to go in
7491 // the instruction's soffset field).  This function takes the first kind of
7492 // offset and figures out how to split it between voffset and immoffset.
7493 std::pair<SDValue, SDValue> SITargetLowering::splitBufferOffsets(
7494     SDValue Offset, SelectionDAG &DAG) const {
7495   SDLoc DL(Offset);
7496   const unsigned MaxImm = 4095;
7497   SDValue N0 = Offset;
7498   ConstantSDNode *C1 = nullptr;
7499 
7500   if ((C1 = dyn_cast<ConstantSDNode>(N0)))
7501     N0 = SDValue();
7502   else if (DAG.isBaseWithConstantOffset(N0)) {
7503     C1 = cast<ConstantSDNode>(N0.getOperand(1));
7504     N0 = N0.getOperand(0);
7505   }
7506 
7507   if (C1) {
7508     unsigned ImmOffset = C1->getZExtValue();
7509     // If the immediate value is too big for the immoffset field, put the value
7510     // and -4096 into the immoffset field so that the value that is copied/added
7511     // for the voffset field is a multiple of 4096, and it stands more chance
7512     // of being CSEd with the copy/add for another similar load/store.
7513     // However, do not do that rounding down to a multiple of 4096 if that is a
7514     // negative number, as it appears to be illegal to have a negative offset
7515     // in the vgpr, even if adding the immediate offset makes it positive.
7516     unsigned Overflow = ImmOffset & ~MaxImm;
7517     ImmOffset -= Overflow;
7518     if ((int32_t)Overflow < 0) {
7519       Overflow += ImmOffset;
7520       ImmOffset = 0;
7521     }
7522     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(ImmOffset, DL, MVT::i32));
7523     if (Overflow) {
7524       auto OverflowVal = DAG.getConstant(Overflow, DL, MVT::i32);
7525       if (!N0)
7526         N0 = OverflowVal;
7527       else {
7528         SDValue Ops[] = { N0, OverflowVal };
7529         N0 = DAG.getNode(ISD::ADD, DL, MVT::i32, Ops);
7530       }
7531     }
7532   }
7533   if (!N0)
7534     N0 = DAG.getConstant(0, DL, MVT::i32);
7535   if (!C1)
7536     C1 = cast<ConstantSDNode>(DAG.getTargetConstant(0, DL, MVT::i32));
7537   return {N0, SDValue(C1, 0)};
7538 }
7539 
7540 // Analyze a combined offset from an amdgcn_buffer_ intrinsic and store the
7541 // three offsets (voffset, soffset and instoffset) into the SDValue[3] array
7542 // pointed to by Offsets.
7543 unsigned SITargetLowering::setBufferOffsets(SDValue CombinedOffset,
7544                                         SelectionDAG &DAG, SDValue *Offsets,
7545                                         unsigned Align) const {
7546   SDLoc DL(CombinedOffset);
7547   if (auto C = dyn_cast<ConstantSDNode>(CombinedOffset)) {
7548     uint32_t Imm = C->getZExtValue();
7549     uint32_t SOffset, ImmOffset;
7550     if (AMDGPU::splitMUBUFOffset(Imm, SOffset, ImmOffset, Subtarget, Align)) {
7551       Offsets[0] = DAG.getConstant(0, DL, MVT::i32);
7552       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7553       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7554       return SOffset + ImmOffset;
7555     }
7556   }
7557   if (DAG.isBaseWithConstantOffset(CombinedOffset)) {
7558     SDValue N0 = CombinedOffset.getOperand(0);
7559     SDValue N1 = CombinedOffset.getOperand(1);
7560     uint32_t SOffset, ImmOffset;
7561     int Offset = cast<ConstantSDNode>(N1)->getSExtValue();
7562     if (Offset >= 0 && AMDGPU::splitMUBUFOffset(Offset, SOffset, ImmOffset,
7563                                                 Subtarget, Align)) {
7564       Offsets[0] = N0;
7565       Offsets[1] = DAG.getConstant(SOffset, DL, MVT::i32);
7566       Offsets[2] = DAG.getTargetConstant(ImmOffset, DL, MVT::i32);
7567       return 0;
7568     }
7569   }
7570   Offsets[0] = CombinedOffset;
7571   Offsets[1] = DAG.getConstant(0, DL, MVT::i32);
7572   Offsets[2] = DAG.getTargetConstant(0, DL, MVT::i32);
7573   return 0;
7574 }
7575 
7576 // Handle 8 bit and 16 bit buffer loads
7577 SDValue SITargetLowering::handleByteShortBufferLoads(SelectionDAG &DAG,
7578                                                      EVT LoadVT, SDLoc DL,
7579                                                      ArrayRef<SDValue> Ops,
7580                                                      MemSDNode *M) const {
7581   EVT IntVT = LoadVT.changeTypeToInteger();
7582   unsigned Opc = (LoadVT.getScalarType() == MVT::i8) ?
7583          AMDGPUISD::BUFFER_LOAD_UBYTE : AMDGPUISD::BUFFER_LOAD_USHORT;
7584 
7585   SDVTList ResList = DAG.getVTList(MVT::i32, MVT::Other);
7586   SDValue BufferLoad = DAG.getMemIntrinsicNode(Opc, DL, ResList,
7587                                                Ops, IntVT,
7588                                                M->getMemOperand());
7589   SDValue LoadVal = DAG.getNode(ISD::TRUNCATE, DL, IntVT, BufferLoad);
7590   LoadVal = DAG.getNode(ISD::BITCAST, DL, LoadVT, LoadVal);
7591 
7592   return DAG.getMergeValues({LoadVal, BufferLoad.getValue(1)}, DL);
7593 }
7594 
7595 // Handle 8 bit and 16 bit buffer stores
7596 SDValue SITargetLowering::handleByteShortBufferStores(SelectionDAG &DAG,
7597                                                       EVT VDataType, SDLoc DL,
7598                                                       SDValue Ops[],
7599                                                       MemSDNode *M) const {
7600   if (VDataType == MVT::f16)
7601     Ops[1] = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Ops[1]);
7602 
7603   SDValue BufferStoreExt = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Ops[1]);
7604   Ops[1] = BufferStoreExt;
7605   unsigned Opc = (VDataType == MVT::i8) ? AMDGPUISD::BUFFER_STORE_BYTE :
7606                                  AMDGPUISD::BUFFER_STORE_SHORT;
7607   ArrayRef<SDValue> OpsRef = makeArrayRef(&Ops[0], 9);
7608   return DAG.getMemIntrinsicNode(Opc, DL, M->getVTList(), OpsRef, VDataType,
7609                                      M->getMemOperand());
7610 }
7611 
7612 static SDValue getLoadExtOrTrunc(SelectionDAG &DAG,
7613                                  ISD::LoadExtType ExtType, SDValue Op,
7614                                  const SDLoc &SL, EVT VT) {
7615   if (VT.bitsLT(Op.getValueType()))
7616     return DAG.getNode(ISD::TRUNCATE, SL, VT, Op);
7617 
7618   switch (ExtType) {
7619   case ISD::SEXTLOAD:
7620     return DAG.getNode(ISD::SIGN_EXTEND, SL, VT, Op);
7621   case ISD::ZEXTLOAD:
7622     return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, Op);
7623   case ISD::EXTLOAD:
7624     return DAG.getNode(ISD::ANY_EXTEND, SL, VT, Op);
7625   case ISD::NON_EXTLOAD:
7626     return Op;
7627   }
7628 
7629   llvm_unreachable("invalid ext type");
7630 }
7631 
7632 SDValue SITargetLowering::widenLoad(LoadSDNode *Ld, DAGCombinerInfo &DCI) const {
7633   SelectionDAG &DAG = DCI.DAG;
7634   if (Ld->getAlignment() < 4 || Ld->isDivergent())
7635     return SDValue();
7636 
7637   // FIXME: Constant loads should all be marked invariant.
7638   unsigned AS = Ld->getAddressSpace();
7639   if (AS != AMDGPUAS::CONSTANT_ADDRESS &&
7640       AS != AMDGPUAS::CONSTANT_ADDRESS_32BIT &&
7641       (AS != AMDGPUAS::GLOBAL_ADDRESS || !Ld->isInvariant()))
7642     return SDValue();
7643 
7644   // Don't do this early, since it may interfere with adjacent load merging for
7645   // illegal types. We can avoid losing alignment information for exotic types
7646   // pre-legalize.
7647   EVT MemVT = Ld->getMemoryVT();
7648   if ((MemVT.isSimple() && !DCI.isAfterLegalizeDAG()) ||
7649       MemVT.getSizeInBits() >= 32)
7650     return SDValue();
7651 
7652   SDLoc SL(Ld);
7653 
7654   assert((!MemVT.isVector() || Ld->getExtensionType() == ISD::NON_EXTLOAD) &&
7655          "unexpected vector extload");
7656 
7657   // TODO: Drop only high part of range.
7658   SDValue Ptr = Ld->getBasePtr();
7659   SDValue NewLoad = DAG.getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD,
7660                                 MVT::i32, SL, Ld->getChain(), Ptr,
7661                                 Ld->getOffset(),
7662                                 Ld->getPointerInfo(), MVT::i32,
7663                                 Ld->getAlignment(),
7664                                 Ld->getMemOperand()->getFlags(),
7665                                 Ld->getAAInfo(),
7666                                 nullptr); // Drop ranges
7667 
7668   EVT TruncVT = EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
7669   if (MemVT.isFloatingPoint()) {
7670     assert(Ld->getExtensionType() == ISD::NON_EXTLOAD &&
7671            "unexpected fp extload");
7672     TruncVT = MemVT.changeTypeToInteger();
7673   }
7674 
7675   SDValue Cvt = NewLoad;
7676   if (Ld->getExtensionType() == ISD::SEXTLOAD) {
7677     Cvt = DAG.getNode(ISD::SIGN_EXTEND_INREG, SL, MVT::i32, NewLoad,
7678                       DAG.getValueType(TruncVT));
7679   } else if (Ld->getExtensionType() == ISD::ZEXTLOAD ||
7680              Ld->getExtensionType() == ISD::NON_EXTLOAD) {
7681     Cvt = DAG.getZeroExtendInReg(NewLoad, SL, TruncVT);
7682   } else {
7683     assert(Ld->getExtensionType() == ISD::EXTLOAD);
7684   }
7685 
7686   EVT VT = Ld->getValueType(0);
7687   EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7688 
7689   DCI.AddToWorklist(Cvt.getNode());
7690 
7691   // We may need to handle exotic cases, such as i16->i64 extloads, so insert
7692   // the appropriate extension from the 32-bit load.
7693   Cvt = getLoadExtOrTrunc(DAG, Ld->getExtensionType(), Cvt, SL, IntVT);
7694   DCI.AddToWorklist(Cvt.getNode());
7695 
7696   // Handle conversion back to floating point if necessary.
7697   Cvt = DAG.getNode(ISD::BITCAST, SL, VT, Cvt);
7698 
7699   return DAG.getMergeValues({ Cvt, NewLoad.getValue(1) }, SL);
7700 }
7701 
7702 SDValue SITargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
7703   SDLoc DL(Op);
7704   LoadSDNode *Load = cast<LoadSDNode>(Op);
7705   ISD::LoadExtType ExtType = Load->getExtensionType();
7706   EVT MemVT = Load->getMemoryVT();
7707 
7708   if (ExtType == ISD::NON_EXTLOAD && MemVT.getSizeInBits() < 32) {
7709     if (MemVT == MVT::i16 && isTypeLegal(MVT::i16))
7710       return SDValue();
7711 
7712     // FIXME: Copied from PPC
7713     // First, load into 32 bits, then truncate to 1 bit.
7714 
7715     SDValue Chain = Load->getChain();
7716     SDValue BasePtr = Load->getBasePtr();
7717     MachineMemOperand *MMO = Load->getMemOperand();
7718 
7719     EVT RealMemVT = (MemVT == MVT::i1) ? MVT::i8 : MVT::i16;
7720 
7721     SDValue NewLD = DAG.getExtLoad(ISD::EXTLOAD, DL, MVT::i32, Chain,
7722                                    BasePtr, RealMemVT, MMO);
7723 
7724     if (!MemVT.isVector()) {
7725       SDValue Ops[] = {
7726         DAG.getNode(ISD::TRUNCATE, DL, MemVT, NewLD),
7727         NewLD.getValue(1)
7728       };
7729 
7730       return DAG.getMergeValues(Ops, DL);
7731     }
7732 
7733     SmallVector<SDValue, 3> Elts;
7734     for (unsigned I = 0, N = MemVT.getVectorNumElements(); I != N; ++I) {
7735       SDValue Elt = DAG.getNode(ISD::SRL, DL, MVT::i32, NewLD,
7736                                 DAG.getConstant(I, DL, MVT::i32));
7737 
7738       Elts.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Elt));
7739     }
7740 
7741     SDValue Ops[] = {
7742       DAG.getBuildVector(MemVT, DL, Elts),
7743       NewLD.getValue(1)
7744     };
7745 
7746     return DAG.getMergeValues(Ops, DL);
7747   }
7748 
7749   if (!MemVT.isVector())
7750     return SDValue();
7751 
7752   assert(Op.getValueType().getVectorElementType() == MVT::i32 &&
7753          "Custom lowering for non-i32 vectors hasn't been implemented.");
7754 
7755   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
7756                                       MemVT, *Load->getMemOperand())) {
7757     SDValue Ops[2];
7758     std::tie(Ops[0], Ops[1]) = expandUnalignedLoad(Load, DAG);
7759     return DAG.getMergeValues(Ops, DL);
7760   }
7761 
7762   unsigned Alignment = Load->getAlignment();
7763   unsigned AS = Load->getAddressSpace();
7764   if (Subtarget->hasLDSMisalignedBug() &&
7765       AS == AMDGPUAS::FLAT_ADDRESS &&
7766       Alignment < MemVT.getStoreSize() && MemVT.getSizeInBits() > 32) {
7767     return SplitVectorLoad(Op, DAG);
7768   }
7769 
7770   MachineFunction &MF = DAG.getMachineFunction();
7771   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
7772   // If there is a possibilty that flat instruction access scratch memory
7773   // then we need to use the same legalization rules we use for private.
7774   if (AS == AMDGPUAS::FLAT_ADDRESS &&
7775       !Subtarget->hasMultiDwordFlatScratchAddressing())
7776     AS = MFI->hasFlatScratchInit() ?
7777          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
7778 
7779   unsigned NumElements = MemVT.getVectorNumElements();
7780 
7781   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7782       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT) {
7783     if (!Op->isDivergent() && Alignment >= 4 && NumElements < 32) {
7784       if (MemVT.isPow2VectorType())
7785         return SDValue();
7786       if (NumElements == 3)
7787         return WidenVectorLoad(Op, DAG);
7788       return SplitVectorLoad(Op, DAG);
7789     }
7790     // Non-uniform loads will be selected to MUBUF instructions, so they
7791     // have the same legalization requirements as global and private
7792     // loads.
7793     //
7794   }
7795 
7796   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7797       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7798       AS == AMDGPUAS::GLOBAL_ADDRESS) {
7799     if (Subtarget->getScalarizeGlobalBehavior() && !Op->isDivergent() &&
7800         Load->isSimple() && isMemOpHasNoClobberedMemOperand(Load) &&
7801         Alignment >= 4 && NumElements < 32) {
7802       if (MemVT.isPow2VectorType())
7803         return SDValue();
7804       if (NumElements == 3)
7805         return WidenVectorLoad(Op, DAG);
7806       return SplitVectorLoad(Op, DAG);
7807     }
7808     // Non-uniform loads will be selected to MUBUF instructions, so they
7809     // have the same legalization requirements as global and private
7810     // loads.
7811     //
7812   }
7813   if (AS == AMDGPUAS::CONSTANT_ADDRESS ||
7814       AS == AMDGPUAS::CONSTANT_ADDRESS_32BIT ||
7815       AS == AMDGPUAS::GLOBAL_ADDRESS ||
7816       AS == AMDGPUAS::FLAT_ADDRESS) {
7817     if (NumElements > 4)
7818       return SplitVectorLoad(Op, DAG);
7819     // v3 loads not supported on SI.
7820     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7821       return WidenVectorLoad(Op, DAG);
7822     // v3 and v4 loads are supported for private and global memory.
7823     return SDValue();
7824   }
7825   if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
7826     // Depending on the setting of the private_element_size field in the
7827     // resource descriptor, we can only make private accesses up to a certain
7828     // size.
7829     switch (Subtarget->getMaxPrivateElementSize()) {
7830     case 4: {
7831       SDValue Ops[2];
7832       std::tie(Ops[0], Ops[1]) = scalarizeVectorLoad(Load, DAG);
7833       return DAG.getMergeValues(Ops, DL);
7834     }
7835     case 8:
7836       if (NumElements > 2)
7837         return SplitVectorLoad(Op, DAG);
7838       return SDValue();
7839     case 16:
7840       // Same as global/flat
7841       if (NumElements > 4)
7842         return SplitVectorLoad(Op, DAG);
7843       // v3 loads not supported on SI.
7844       if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
7845         return WidenVectorLoad(Op, DAG);
7846       return SDValue();
7847     default:
7848       llvm_unreachable("unsupported private_element_size");
7849     }
7850   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
7851     // Use ds_read_b128 if possible.
7852     if (Subtarget->useDS128() && Load->getAlignment() >= 16 &&
7853         MemVT.getStoreSize() == 16)
7854       return SDValue();
7855 
7856     if (NumElements > 2)
7857       return SplitVectorLoad(Op, DAG);
7858 
7859     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
7860     // address is negative, then the instruction is incorrectly treated as
7861     // out-of-bounds even if base + offsets is in bounds. Split vectorized
7862     // loads here to avoid emitting ds_read2_b32. We may re-combine the
7863     // load later in the SILoadStoreOptimizer.
7864     if (Subtarget->getGeneration() == AMDGPUSubtarget::SOUTHERN_ISLANDS &&
7865         NumElements == 2 && MemVT.getStoreSize() == 8 &&
7866         Load->getAlignment() < 8) {
7867       return SplitVectorLoad(Op, DAG);
7868     }
7869   }
7870   return SDValue();
7871 }
7872 
7873 SDValue SITargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
7874   EVT VT = Op.getValueType();
7875   assert(VT.getSizeInBits() == 64);
7876 
7877   SDLoc DL(Op);
7878   SDValue Cond = Op.getOperand(0);
7879 
7880   SDValue Zero = DAG.getConstant(0, DL, MVT::i32);
7881   SDValue One = DAG.getConstant(1, DL, MVT::i32);
7882 
7883   SDValue LHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(1));
7884   SDValue RHS = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Op.getOperand(2));
7885 
7886   SDValue Lo0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, Zero);
7887   SDValue Lo1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, Zero);
7888 
7889   SDValue Lo = DAG.getSelect(DL, MVT::i32, Cond, Lo0, Lo1);
7890 
7891   SDValue Hi0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, LHS, One);
7892   SDValue Hi1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32, RHS, One);
7893 
7894   SDValue Hi = DAG.getSelect(DL, MVT::i32, Cond, Hi0, Hi1);
7895 
7896   SDValue Res = DAG.getBuildVector(MVT::v2i32, DL, {Lo, Hi});
7897   return DAG.getNode(ISD::BITCAST, DL, VT, Res);
7898 }
7899 
7900 // Catch division cases where we can use shortcuts with rcp and rsq
7901 // instructions.
7902 SDValue SITargetLowering::lowerFastUnsafeFDIV(SDValue Op,
7903                                               SelectionDAG &DAG) const {
7904   SDLoc SL(Op);
7905   SDValue LHS = Op.getOperand(0);
7906   SDValue RHS = Op.getOperand(1);
7907   EVT VT = Op.getValueType();
7908   const SDNodeFlags Flags = Op->getFlags();
7909 
7910   bool AllowInaccurateRcp = DAG.getTarget().Options.UnsafeFPMath ||
7911                             Flags.hasApproximateFuncs();
7912 
7913   // Without !fpmath accuracy information, we can't do more because we don't
7914   // know exactly whether rcp is accurate enough to meet !fpmath requirement.
7915   if (!AllowInaccurateRcp)
7916     return SDValue();
7917 
7918   if (const ConstantFPSDNode *CLHS = dyn_cast<ConstantFPSDNode>(LHS)) {
7919     if (CLHS->isExactlyValue(1.0)) {
7920       // v_rcp_f32 and v_rsq_f32 do not support denormals, and according to
7921       // the CI documentation has a worst case error of 1 ulp.
7922       // OpenCL requires <= 2.5 ulp for 1.0 / x, so it should always be OK to
7923       // use it as long as we aren't trying to use denormals.
7924       //
7925       // v_rcp_f16 and v_rsq_f16 DO support denormals.
7926 
7927       // 1.0 / sqrt(x) -> rsq(x)
7928 
7929       // XXX - Is UnsafeFPMath sufficient to do this for f64? The maximum ULP
7930       // error seems really high at 2^29 ULP.
7931       if (RHS.getOpcode() == ISD::FSQRT)
7932         return DAG.getNode(AMDGPUISD::RSQ, SL, VT, RHS.getOperand(0));
7933 
7934       // 1.0 / x -> rcp(x)
7935       return DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7936     }
7937 
7938     // Same as for 1.0, but expand the sign out of the constant.
7939     if (CLHS->isExactlyValue(-1.0)) {
7940       // -1.0 / x -> rcp (fneg x)
7941       SDValue FNegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
7942       return DAG.getNode(AMDGPUISD::RCP, SL, VT, FNegRHS);
7943     }
7944   }
7945 
7946   // Turn into multiply by the reciprocal.
7947   // x / y -> x * (1.0 / y)
7948   SDValue Recip = DAG.getNode(AMDGPUISD::RCP, SL, VT, RHS);
7949   return DAG.getNode(ISD::FMUL, SL, VT, LHS, Recip, Flags);
7950 }
7951 
7952 static SDValue getFPBinOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7953                           EVT VT, SDValue A, SDValue B, SDValue GlueChain,
7954                           SDNodeFlags Flags) {
7955   if (GlueChain->getNumValues() <= 1) {
7956     return DAG.getNode(Opcode, SL, VT, A, B, Flags);
7957   }
7958 
7959   assert(GlueChain->getNumValues() == 3);
7960 
7961   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7962   switch (Opcode) {
7963   default: llvm_unreachable("no chain equivalent for opcode");
7964   case ISD::FMUL:
7965     Opcode = AMDGPUISD::FMUL_W_CHAIN;
7966     break;
7967   }
7968 
7969   return DAG.getNode(Opcode, SL, VTList,
7970                      {GlueChain.getValue(1), A, B, GlueChain.getValue(2)},
7971                      Flags);
7972 }
7973 
7974 static SDValue getFPTernOp(SelectionDAG &DAG, unsigned Opcode, const SDLoc &SL,
7975                            EVT VT, SDValue A, SDValue B, SDValue C,
7976                            SDValue GlueChain, SDNodeFlags Flags) {
7977   if (GlueChain->getNumValues() <= 1) {
7978     return DAG.getNode(Opcode, SL, VT, {A, B, C}, Flags);
7979   }
7980 
7981   assert(GlueChain->getNumValues() == 3);
7982 
7983   SDVTList VTList = DAG.getVTList(VT, MVT::Other, MVT::Glue);
7984   switch (Opcode) {
7985   default: llvm_unreachable("no chain equivalent for opcode");
7986   case ISD::FMA:
7987     Opcode = AMDGPUISD::FMA_W_CHAIN;
7988     break;
7989   }
7990 
7991   return DAG.getNode(Opcode, SL, VTList,
7992                      {GlueChain.getValue(1), A, B, C, GlueChain.getValue(2)},
7993                      Flags);
7994 }
7995 
7996 SDValue SITargetLowering::LowerFDIV16(SDValue Op, SelectionDAG &DAG) const {
7997   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
7998     return FastLowered;
7999 
8000   SDLoc SL(Op);
8001   SDValue Src0 = Op.getOperand(0);
8002   SDValue Src1 = Op.getOperand(1);
8003 
8004   SDValue CvtSrc0 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src0);
8005   SDValue CvtSrc1 = DAG.getNode(ISD::FP_EXTEND, SL, MVT::f32, Src1);
8006 
8007   SDValue RcpSrc1 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, CvtSrc1);
8008   SDValue Quot = DAG.getNode(ISD::FMUL, SL, MVT::f32, CvtSrc0, RcpSrc1);
8009 
8010   SDValue FPRoundFlag = DAG.getTargetConstant(0, SL, MVT::i32);
8011   SDValue BestQuot = DAG.getNode(ISD::FP_ROUND, SL, MVT::f16, Quot, FPRoundFlag);
8012 
8013   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f16, BestQuot, Src1, Src0);
8014 }
8015 
8016 // Faster 2.5 ULP division that does not support denormals.
8017 SDValue SITargetLowering::lowerFDIV_FAST(SDValue Op, SelectionDAG &DAG) const {
8018   SDLoc SL(Op);
8019   SDValue LHS = Op.getOperand(1);
8020   SDValue RHS = Op.getOperand(2);
8021 
8022   SDValue r1 = DAG.getNode(ISD::FABS, SL, MVT::f32, RHS);
8023 
8024   const APFloat K0Val(BitsToFloat(0x6f800000));
8025   const SDValue K0 = DAG.getConstantFP(K0Val, SL, MVT::f32);
8026 
8027   const APFloat K1Val(BitsToFloat(0x2f800000));
8028   const SDValue K1 = DAG.getConstantFP(K1Val, SL, MVT::f32);
8029 
8030   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8031 
8032   EVT SetCCVT =
8033     getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::f32);
8034 
8035   SDValue r2 = DAG.getSetCC(SL, SetCCVT, r1, K0, ISD::SETOGT);
8036 
8037   SDValue r3 = DAG.getNode(ISD::SELECT, SL, MVT::f32, r2, K1, One);
8038 
8039   // TODO: Should this propagate fast-math-flags?
8040   r1 = DAG.getNode(ISD::FMUL, SL, MVT::f32, RHS, r3);
8041 
8042   // rcp does not support denormals.
8043   SDValue r0 = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32, r1);
8044 
8045   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f32, LHS, r0);
8046 
8047   return DAG.getNode(ISD::FMUL, SL, MVT::f32, r3, Mul);
8048 }
8049 
8050 // Returns immediate value for setting the F32 denorm mode when using the
8051 // S_DENORM_MODE instruction.
8052 static const SDValue getSPDenormModeValue(int SPDenormMode, SelectionDAG &DAG,
8053                                           const SDLoc &SL, const GCNSubtarget *ST) {
8054   assert(ST->hasDenormModeInst() && "Requires S_DENORM_MODE");
8055   int DPDenormModeDefault = hasFP64FP16Denormals(DAG.getMachineFunction())
8056                                 ? FP_DENORM_FLUSH_NONE
8057                                 : FP_DENORM_FLUSH_IN_FLUSH_OUT;
8058 
8059   int Mode = SPDenormMode | (DPDenormModeDefault << 2);
8060   return DAG.getTargetConstant(Mode, SL, MVT::i32);
8061 }
8062 
8063 SDValue SITargetLowering::LowerFDIV32(SDValue Op, SelectionDAG &DAG) const {
8064   if (SDValue FastLowered = lowerFastUnsafeFDIV(Op, DAG))
8065     return FastLowered;
8066 
8067   // The selection matcher assumes anything with a chain selecting to a
8068   // mayRaiseFPException machine instruction. Since we're introducing a chain
8069   // here, we need to explicitly report nofpexcept for the regular fdiv
8070   // lowering.
8071   SDNodeFlags Flags = Op->getFlags();
8072   Flags.setNoFPExcept(true);
8073 
8074   SDLoc SL(Op);
8075   SDValue LHS = Op.getOperand(0);
8076   SDValue RHS = Op.getOperand(1);
8077 
8078   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f32);
8079 
8080   SDVTList ScaleVT = DAG.getVTList(MVT::f32, MVT::i1);
8081 
8082   SDValue DenominatorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8083                                           {RHS, RHS, LHS}, Flags);
8084   SDValue NumeratorScaled = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT,
8085                                         {LHS, RHS, LHS}, Flags);
8086 
8087   // Denominator is scaled to not be denormal, so using rcp is ok.
8088   SDValue ApproxRcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f32,
8089                                   DenominatorScaled, Flags);
8090   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f32,
8091                                      DenominatorScaled, Flags);
8092 
8093   const unsigned Denorm32Reg = AMDGPU::Hwreg::ID_MODE |
8094                                (4 << AMDGPU::Hwreg::OFFSET_SHIFT_) |
8095                                (1 << AMDGPU::Hwreg::WIDTH_M1_SHIFT_);
8096   const SDValue BitField = DAG.getTargetConstant(Denorm32Reg, SL, MVT::i32);
8097 
8098   const bool HasFP32Denormals = hasFP32Denormals(DAG.getMachineFunction());
8099 
8100   if (!HasFP32Denormals) {
8101     // Note we can't use the STRICT_FMA/STRICT_FMUL for the non-strict FDIV
8102     // lowering. The chain dependence is insufficient, and we need glue. We do
8103     // not need the glue variants in a strictfp function.
8104 
8105     SDVTList BindParamVTs = DAG.getVTList(MVT::Other, MVT::Glue);
8106 
8107     SDNode *EnableDenorm;
8108     if (Subtarget->hasDenormModeInst()) {
8109       const SDValue EnableDenormValue =
8110           getSPDenormModeValue(FP_DENORM_FLUSH_NONE, DAG, SL, Subtarget);
8111 
8112       EnableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, BindParamVTs,
8113                                  DAG.getEntryNode(), EnableDenormValue).getNode();
8114     } else {
8115       const SDValue EnableDenormValue = DAG.getConstant(FP_DENORM_FLUSH_NONE,
8116                                                         SL, MVT::i32);
8117       EnableDenorm =
8118           DAG.getMachineNode(AMDGPU::S_SETREG_B32, SL, BindParamVTs,
8119                              {EnableDenormValue, BitField, DAG.getEntryNode()});
8120     }
8121 
8122     SDValue Ops[3] = {
8123       NegDivScale0,
8124       SDValue(EnableDenorm, 0),
8125       SDValue(EnableDenorm, 1)
8126     };
8127 
8128     NegDivScale0 = DAG.getMergeValues(Ops, SL);
8129   }
8130 
8131   SDValue Fma0 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0,
8132                              ApproxRcp, One, NegDivScale0, Flags);
8133 
8134   SDValue Fma1 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, Fma0, ApproxRcp,
8135                              ApproxRcp, Fma0, Flags);
8136 
8137   SDValue Mul = getFPBinOp(DAG, ISD::FMUL, SL, MVT::f32, NumeratorScaled,
8138                            Fma1, Fma1, Flags);
8139 
8140   SDValue Fma2 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Mul,
8141                              NumeratorScaled, Mul, Flags);
8142 
8143   SDValue Fma3 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32,
8144                              Fma2, Fma1, Mul, Fma2, Flags);
8145 
8146   SDValue Fma4 = getFPTernOp(DAG, ISD::FMA, SL, MVT::f32, NegDivScale0, Fma3,
8147                              NumeratorScaled, Fma3, Flags);
8148 
8149   if (!HasFP32Denormals) {
8150     SDNode *DisableDenorm;
8151     if (Subtarget->hasDenormModeInst()) {
8152       const SDValue DisableDenormValue =
8153           getSPDenormModeValue(FP_DENORM_FLUSH_IN_FLUSH_OUT, DAG, SL, Subtarget);
8154 
8155       DisableDenorm = DAG.getNode(AMDGPUISD::DENORM_MODE, SL, MVT::Other,
8156                                   Fma4.getValue(1), DisableDenormValue,
8157                                   Fma4.getValue(2)).getNode();
8158     } else {
8159       const SDValue DisableDenormValue =
8160           DAG.getConstant(FP_DENORM_FLUSH_IN_FLUSH_OUT, SL, MVT::i32);
8161 
8162       DisableDenorm = DAG.getMachineNode(
8163           AMDGPU::S_SETREG_B32, SL, MVT::Other,
8164           {DisableDenormValue, BitField, Fma4.getValue(1), Fma4.getValue(2)});
8165     }
8166 
8167     SDValue OutputChain = DAG.getNode(ISD::TokenFactor, SL, MVT::Other,
8168                                       SDValue(DisableDenorm, 0), DAG.getRoot());
8169     DAG.setRoot(OutputChain);
8170   }
8171 
8172   SDValue Scale = NumeratorScaled.getValue(1);
8173   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f32,
8174                              {Fma4, Fma1, Fma3, Scale}, Flags);
8175 
8176   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f32, Fmas, RHS, LHS, Flags);
8177 }
8178 
8179 SDValue SITargetLowering::LowerFDIV64(SDValue Op, SelectionDAG &DAG) const {
8180   if (DAG.getTarget().Options.UnsafeFPMath)
8181     return lowerFastUnsafeFDIV(Op, DAG);
8182 
8183   SDLoc SL(Op);
8184   SDValue X = Op.getOperand(0);
8185   SDValue Y = Op.getOperand(1);
8186 
8187   const SDValue One = DAG.getConstantFP(1.0, SL, MVT::f64);
8188 
8189   SDVTList ScaleVT = DAG.getVTList(MVT::f64, MVT::i1);
8190 
8191   SDValue DivScale0 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, Y, Y, X);
8192 
8193   SDValue NegDivScale0 = DAG.getNode(ISD::FNEG, SL, MVT::f64, DivScale0);
8194 
8195   SDValue Rcp = DAG.getNode(AMDGPUISD::RCP, SL, MVT::f64, DivScale0);
8196 
8197   SDValue Fma0 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Rcp, One);
8198 
8199   SDValue Fma1 = DAG.getNode(ISD::FMA, SL, MVT::f64, Rcp, Fma0, Rcp);
8200 
8201   SDValue Fma2 = DAG.getNode(ISD::FMA, SL, MVT::f64, NegDivScale0, Fma1, One);
8202 
8203   SDValue DivScale1 = DAG.getNode(AMDGPUISD::DIV_SCALE, SL, ScaleVT, X, Y, X);
8204 
8205   SDValue Fma3 = DAG.getNode(ISD::FMA, SL, MVT::f64, Fma1, Fma2, Fma1);
8206   SDValue Mul = DAG.getNode(ISD::FMUL, SL, MVT::f64, DivScale1, Fma3);
8207 
8208   SDValue Fma4 = DAG.getNode(ISD::FMA, SL, MVT::f64,
8209                              NegDivScale0, Mul, DivScale1);
8210 
8211   SDValue Scale;
8212 
8213   if (!Subtarget->hasUsableDivScaleConditionOutput()) {
8214     // Workaround a hardware bug on SI where the condition output from div_scale
8215     // is not usable.
8216 
8217     const SDValue Hi = DAG.getConstant(1, SL, MVT::i32);
8218 
8219     // Figure out if the scale to use for div_fmas.
8220     SDValue NumBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, X);
8221     SDValue DenBC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, Y);
8222     SDValue Scale0BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale0);
8223     SDValue Scale1BC = DAG.getNode(ISD::BITCAST, SL, MVT::v2i32, DivScale1);
8224 
8225     SDValue NumHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, NumBC, Hi);
8226     SDValue DenHi = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, DenBC, Hi);
8227 
8228     SDValue Scale0Hi
8229       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale0BC, Hi);
8230     SDValue Scale1Hi
8231       = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Scale1BC, Hi);
8232 
8233     SDValue CmpDen = DAG.getSetCC(SL, MVT::i1, DenHi, Scale0Hi, ISD::SETEQ);
8234     SDValue CmpNum = DAG.getSetCC(SL, MVT::i1, NumHi, Scale1Hi, ISD::SETEQ);
8235     Scale = DAG.getNode(ISD::XOR, SL, MVT::i1, CmpNum, CmpDen);
8236   } else {
8237     Scale = DivScale1.getValue(1);
8238   }
8239 
8240   SDValue Fmas = DAG.getNode(AMDGPUISD::DIV_FMAS, SL, MVT::f64,
8241                              Fma4, Fma3, Mul, Scale);
8242 
8243   return DAG.getNode(AMDGPUISD::DIV_FIXUP, SL, MVT::f64, Fmas, Y, X);
8244 }
8245 
8246 SDValue SITargetLowering::LowerFDIV(SDValue Op, SelectionDAG &DAG) const {
8247   EVT VT = Op.getValueType();
8248 
8249   if (VT == MVT::f32)
8250     return LowerFDIV32(Op, DAG);
8251 
8252   if (VT == MVT::f64)
8253     return LowerFDIV64(Op, DAG);
8254 
8255   if (VT == MVT::f16)
8256     return LowerFDIV16(Op, DAG);
8257 
8258   llvm_unreachable("Unexpected type for fdiv");
8259 }
8260 
8261 SDValue SITargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
8262   SDLoc DL(Op);
8263   StoreSDNode *Store = cast<StoreSDNode>(Op);
8264   EVT VT = Store->getMemoryVT();
8265 
8266   if (VT == MVT::i1) {
8267     return DAG.getTruncStore(Store->getChain(), DL,
8268        DAG.getSExtOrTrunc(Store->getValue(), DL, MVT::i32),
8269        Store->getBasePtr(), MVT::i1, Store->getMemOperand());
8270   }
8271 
8272   assert(VT.isVector() &&
8273          Store->getValue().getValueType().getScalarType() == MVT::i32);
8274 
8275   if (!allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
8276                                       VT, *Store->getMemOperand())) {
8277     return expandUnalignedStore(Store, DAG);
8278   }
8279 
8280   unsigned AS = Store->getAddressSpace();
8281   if (Subtarget->hasLDSMisalignedBug() &&
8282       AS == AMDGPUAS::FLAT_ADDRESS &&
8283       Store->getAlignment() < VT.getStoreSize() && VT.getSizeInBits() > 32) {
8284     return SplitVectorStore(Op, DAG);
8285   }
8286 
8287   MachineFunction &MF = DAG.getMachineFunction();
8288   SIMachineFunctionInfo *MFI = MF.getInfo<SIMachineFunctionInfo>();
8289   // If there is a possibilty that flat instruction access scratch memory
8290   // then we need to use the same legalization rules we use for private.
8291   if (AS == AMDGPUAS::FLAT_ADDRESS &&
8292       !Subtarget->hasMultiDwordFlatScratchAddressing())
8293     AS = MFI->hasFlatScratchInit() ?
8294          AMDGPUAS::PRIVATE_ADDRESS : AMDGPUAS::GLOBAL_ADDRESS;
8295 
8296   unsigned NumElements = VT.getVectorNumElements();
8297   if (AS == AMDGPUAS::GLOBAL_ADDRESS ||
8298       AS == AMDGPUAS::FLAT_ADDRESS) {
8299     if (NumElements > 4)
8300       return SplitVectorStore(Op, DAG);
8301     // v3 stores not supported on SI.
8302     if (NumElements == 3 && !Subtarget->hasDwordx3LoadStores())
8303       return SplitVectorStore(Op, DAG);
8304     return SDValue();
8305   } else if (AS == AMDGPUAS::PRIVATE_ADDRESS) {
8306     switch (Subtarget->getMaxPrivateElementSize()) {
8307     case 4:
8308       return scalarizeVectorStore(Store, DAG);
8309     case 8:
8310       if (NumElements > 2)
8311         return SplitVectorStore(Op, DAG);
8312       return SDValue();
8313     case 16:
8314       if (NumElements > 4 || NumElements == 3)
8315         return SplitVectorStore(Op, DAG);
8316       return SDValue();
8317     default:
8318       llvm_unreachable("unsupported private_element_size");
8319     }
8320   } else if (AS == AMDGPUAS::LOCAL_ADDRESS || AS == AMDGPUAS::REGION_ADDRESS) {
8321     // Use ds_write_b128 if possible.
8322     if (Subtarget->useDS128() && Store->getAlignment() >= 16 &&
8323         VT.getStoreSize() == 16 && NumElements != 3)
8324       return SDValue();
8325 
8326     if (NumElements > 2)
8327       return SplitVectorStore(Op, DAG);
8328 
8329     // SI has a hardware bug in the LDS / GDS boounds checking: if the base
8330     // address is negative, then the instruction is incorrectly treated as
8331     // out-of-bounds even if base + offsets is in bounds. Split vectorized
8332     // stores here to avoid emitting ds_write2_b32. We may re-combine the
8333     // store later in the SILoadStoreOptimizer.
8334     if (!Subtarget->hasUsableDSOffset() &&
8335         NumElements == 2 && VT.getStoreSize() == 8 &&
8336         Store->getAlignment() < 8) {
8337       return SplitVectorStore(Op, DAG);
8338     }
8339 
8340     return SDValue();
8341   } else {
8342     llvm_unreachable("unhandled address space");
8343   }
8344 }
8345 
8346 SDValue SITargetLowering::LowerTrig(SDValue Op, SelectionDAG &DAG) const {
8347   SDLoc DL(Op);
8348   EVT VT = Op.getValueType();
8349   SDValue Arg = Op.getOperand(0);
8350   SDValue TrigVal;
8351 
8352   // Propagate fast-math flags so that the multiply we introduce can be folded
8353   // if Arg is already the result of a multiply by constant.
8354   auto Flags = Op->getFlags();
8355 
8356   SDValue OneOver2Pi = DAG.getConstantFP(0.5 * numbers::inv_pi, DL, VT);
8357 
8358   if (Subtarget->hasTrigReducedRange()) {
8359     SDValue MulVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8360     TrigVal = DAG.getNode(AMDGPUISD::FRACT, DL, VT, MulVal, Flags);
8361   } else {
8362     TrigVal = DAG.getNode(ISD::FMUL, DL, VT, Arg, OneOver2Pi, Flags);
8363   }
8364 
8365   switch (Op.getOpcode()) {
8366   case ISD::FCOS:
8367     return DAG.getNode(AMDGPUISD::COS_HW, SDLoc(Op), VT, TrigVal, Flags);
8368   case ISD::FSIN:
8369     return DAG.getNode(AMDGPUISD::SIN_HW, SDLoc(Op), VT, TrigVal, Flags);
8370   default:
8371     llvm_unreachable("Wrong trig opcode");
8372   }
8373 }
8374 
8375 SDValue SITargetLowering::LowerATOMIC_CMP_SWAP(SDValue Op, SelectionDAG &DAG) const {
8376   AtomicSDNode *AtomicNode = cast<AtomicSDNode>(Op);
8377   assert(AtomicNode->isCompareAndSwap());
8378   unsigned AS = AtomicNode->getAddressSpace();
8379 
8380   // No custom lowering required for local address space
8381   if (!isFlatGlobalAddrSpace(AS))
8382     return Op;
8383 
8384   // Non-local address space requires custom lowering for atomic compare
8385   // and swap; cmp and swap should be in a v2i32 or v2i64 in case of _X2
8386   SDLoc DL(Op);
8387   SDValue ChainIn = Op.getOperand(0);
8388   SDValue Addr = Op.getOperand(1);
8389   SDValue Old = Op.getOperand(2);
8390   SDValue New = Op.getOperand(3);
8391   EVT VT = Op.getValueType();
8392   MVT SimpleVT = VT.getSimpleVT();
8393   MVT VecType = MVT::getVectorVT(SimpleVT, 2);
8394 
8395   SDValue NewOld = DAG.getBuildVector(VecType, DL, {New, Old});
8396   SDValue Ops[] = { ChainIn, Addr, NewOld };
8397 
8398   return DAG.getMemIntrinsicNode(AMDGPUISD::ATOMIC_CMP_SWAP, DL, Op->getVTList(),
8399                                  Ops, VT, AtomicNode->getMemOperand());
8400 }
8401 
8402 //===----------------------------------------------------------------------===//
8403 // Custom DAG optimizations
8404 //===----------------------------------------------------------------------===//
8405 
8406 SDValue SITargetLowering::performUCharToFloatCombine(SDNode *N,
8407                                                      DAGCombinerInfo &DCI) const {
8408   EVT VT = N->getValueType(0);
8409   EVT ScalarVT = VT.getScalarType();
8410   if (ScalarVT != MVT::f32 && ScalarVT != MVT::f16)
8411     return SDValue();
8412 
8413   SelectionDAG &DAG = DCI.DAG;
8414   SDLoc DL(N);
8415 
8416   SDValue Src = N->getOperand(0);
8417   EVT SrcVT = Src.getValueType();
8418 
8419   // TODO: We could try to match extracting the higher bytes, which would be
8420   // easier if i8 vectors weren't promoted to i32 vectors, particularly after
8421   // types are legalized. v4i8 -> v4f32 is probably the only case to worry
8422   // about in practice.
8423   if (DCI.isAfterLegalizeDAG() && SrcVT == MVT::i32) {
8424     if (DAG.MaskedValueIsZero(Src, APInt::getHighBitsSet(32, 24))) {
8425       SDValue Cvt = DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0, DL, MVT::f32, Src);
8426       DCI.AddToWorklist(Cvt.getNode());
8427 
8428       // For the f16 case, fold to a cast to f32 and then cast back to f16.
8429       if (ScalarVT != MVT::f32) {
8430         Cvt = DAG.getNode(ISD::FP_ROUND, DL, VT, Cvt,
8431                           DAG.getTargetConstant(0, DL, MVT::i32));
8432       }
8433       return Cvt;
8434     }
8435   }
8436 
8437   return SDValue();
8438 }
8439 
8440 // (shl (add x, c1), c2) -> add (shl x, c2), (shl c1, c2)
8441 
8442 // This is a variant of
8443 // (mul (add x, c1), c2) -> add (mul x, c2), (mul c1, c2),
8444 //
8445 // The normal DAG combiner will do this, but only if the add has one use since
8446 // that would increase the number of instructions.
8447 //
8448 // This prevents us from seeing a constant offset that can be folded into a
8449 // memory instruction's addressing mode. If we know the resulting add offset of
8450 // a pointer can be folded into an addressing offset, we can replace the pointer
8451 // operand with the add of new constant offset. This eliminates one of the uses,
8452 // and may allow the remaining use to also be simplified.
8453 //
8454 SDValue SITargetLowering::performSHLPtrCombine(SDNode *N,
8455                                                unsigned AddrSpace,
8456                                                EVT MemVT,
8457                                                DAGCombinerInfo &DCI) const {
8458   SDValue N0 = N->getOperand(0);
8459   SDValue N1 = N->getOperand(1);
8460 
8461   // We only do this to handle cases where it's profitable when there are
8462   // multiple uses of the add, so defer to the standard combine.
8463   if ((N0.getOpcode() != ISD::ADD && N0.getOpcode() != ISD::OR) ||
8464       N0->hasOneUse())
8465     return SDValue();
8466 
8467   const ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(N1);
8468   if (!CN1)
8469     return SDValue();
8470 
8471   const ConstantSDNode *CAdd = dyn_cast<ConstantSDNode>(N0.getOperand(1));
8472   if (!CAdd)
8473     return SDValue();
8474 
8475   // If the resulting offset is too large, we can't fold it into the addressing
8476   // mode offset.
8477   APInt Offset = CAdd->getAPIntValue() << CN1->getAPIntValue();
8478   Type *Ty = MemVT.getTypeForEVT(*DCI.DAG.getContext());
8479 
8480   AddrMode AM;
8481   AM.HasBaseReg = true;
8482   AM.BaseOffs = Offset.getSExtValue();
8483   if (!isLegalAddressingMode(DCI.DAG.getDataLayout(), AM, Ty, AddrSpace))
8484     return SDValue();
8485 
8486   SelectionDAG &DAG = DCI.DAG;
8487   SDLoc SL(N);
8488   EVT VT = N->getValueType(0);
8489 
8490   SDValue ShlX = DAG.getNode(ISD::SHL, SL, VT, N0.getOperand(0), N1);
8491   SDValue COffset = DAG.getConstant(Offset, SL, MVT::i32);
8492 
8493   SDNodeFlags Flags;
8494   Flags.setNoUnsignedWrap(N->getFlags().hasNoUnsignedWrap() &&
8495                           (N0.getOpcode() == ISD::OR ||
8496                            N0->getFlags().hasNoUnsignedWrap()));
8497 
8498   return DAG.getNode(ISD::ADD, SL, VT, ShlX, COffset, Flags);
8499 }
8500 
8501 SDValue SITargetLowering::performMemSDNodeCombine(MemSDNode *N,
8502                                                   DAGCombinerInfo &DCI) const {
8503   SDValue Ptr = N->getBasePtr();
8504   SelectionDAG &DAG = DCI.DAG;
8505   SDLoc SL(N);
8506 
8507   // TODO: We could also do this for multiplies.
8508   if (Ptr.getOpcode() == ISD::SHL) {
8509     SDValue NewPtr = performSHLPtrCombine(Ptr.getNode(),  N->getAddressSpace(),
8510                                           N->getMemoryVT(), DCI);
8511     if (NewPtr) {
8512       SmallVector<SDValue, 8> NewOps(N->op_begin(), N->op_end());
8513 
8514       NewOps[N->getOpcode() == ISD::STORE ? 2 : 1] = NewPtr;
8515       return SDValue(DAG.UpdateNodeOperands(N, NewOps), 0);
8516     }
8517   }
8518 
8519   return SDValue();
8520 }
8521 
8522 static bool bitOpWithConstantIsReducible(unsigned Opc, uint32_t Val) {
8523   return (Opc == ISD::AND && (Val == 0 || Val == 0xffffffff)) ||
8524          (Opc == ISD::OR && (Val == 0xffffffff || Val == 0)) ||
8525          (Opc == ISD::XOR && Val == 0);
8526 }
8527 
8528 // Break up 64-bit bit operation of a constant into two 32-bit and/or/xor. This
8529 // will typically happen anyway for a VALU 64-bit and. This exposes other 32-bit
8530 // integer combine opportunities since most 64-bit operations are decomposed
8531 // this way.  TODO: We won't want this for SALU especially if it is an inline
8532 // immediate.
8533 SDValue SITargetLowering::splitBinaryBitConstantOp(
8534   DAGCombinerInfo &DCI,
8535   const SDLoc &SL,
8536   unsigned Opc, SDValue LHS,
8537   const ConstantSDNode *CRHS) const {
8538   uint64_t Val = CRHS->getZExtValue();
8539   uint32_t ValLo = Lo_32(Val);
8540   uint32_t ValHi = Hi_32(Val);
8541   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8542 
8543     if ((bitOpWithConstantIsReducible(Opc, ValLo) ||
8544          bitOpWithConstantIsReducible(Opc, ValHi)) ||
8545         (CRHS->hasOneUse() && !TII->isInlineConstant(CRHS->getAPIntValue()))) {
8546     // If we need to materialize a 64-bit immediate, it will be split up later
8547     // anyway. Avoid creating the harder to understand 64-bit immediate
8548     // materialization.
8549     return splitBinaryBitConstantOpImpl(DCI, SL, Opc, LHS, ValLo, ValHi);
8550   }
8551 
8552   return SDValue();
8553 }
8554 
8555 // Returns true if argument is a boolean value which is not serialized into
8556 // memory or argument and does not require v_cmdmask_b32 to be deserialized.
8557 static bool isBoolSGPR(SDValue V) {
8558   if (V.getValueType() != MVT::i1)
8559     return false;
8560   switch (V.getOpcode()) {
8561   default: break;
8562   case ISD::SETCC:
8563   case ISD::AND:
8564   case ISD::OR:
8565   case ISD::XOR:
8566   case AMDGPUISD::FP_CLASS:
8567     return true;
8568   }
8569   return false;
8570 }
8571 
8572 // If a constant has all zeroes or all ones within each byte return it.
8573 // Otherwise return 0.
8574 static uint32_t getConstantPermuteMask(uint32_t C) {
8575   // 0xff for any zero byte in the mask
8576   uint32_t ZeroByteMask = 0;
8577   if (!(C & 0x000000ff)) ZeroByteMask |= 0x000000ff;
8578   if (!(C & 0x0000ff00)) ZeroByteMask |= 0x0000ff00;
8579   if (!(C & 0x00ff0000)) ZeroByteMask |= 0x00ff0000;
8580   if (!(C & 0xff000000)) ZeroByteMask |= 0xff000000;
8581   uint32_t NonZeroByteMask = ~ZeroByteMask; // 0xff for any non-zero byte
8582   if ((NonZeroByteMask & C) != NonZeroByteMask)
8583     return 0; // Partial bytes selected.
8584   return C;
8585 }
8586 
8587 // Check if a node selects whole bytes from its operand 0 starting at a byte
8588 // boundary while masking the rest. Returns select mask as in the v_perm_b32
8589 // or -1 if not succeeded.
8590 // Note byte select encoding:
8591 // value 0-3 selects corresponding source byte;
8592 // value 0xc selects zero;
8593 // value 0xff selects 0xff.
8594 static uint32_t getPermuteMask(SelectionDAG &DAG, SDValue V) {
8595   assert(V.getValueSizeInBits() == 32);
8596 
8597   if (V.getNumOperands() != 2)
8598     return ~0;
8599 
8600   ConstantSDNode *N1 = dyn_cast<ConstantSDNode>(V.getOperand(1));
8601   if (!N1)
8602     return ~0;
8603 
8604   uint32_t C = N1->getZExtValue();
8605 
8606   switch (V.getOpcode()) {
8607   default:
8608     break;
8609   case ISD::AND:
8610     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8611       return (0x03020100 & ConstMask) | (0x0c0c0c0c & ~ConstMask);
8612     }
8613     break;
8614 
8615   case ISD::OR:
8616     if (uint32_t ConstMask = getConstantPermuteMask(C)) {
8617       return (0x03020100 & ~ConstMask) | ConstMask;
8618     }
8619     break;
8620 
8621   case ISD::SHL:
8622     if (C % 8)
8623       return ~0;
8624 
8625     return uint32_t((0x030201000c0c0c0cull << C) >> 32);
8626 
8627   case ISD::SRL:
8628     if (C % 8)
8629       return ~0;
8630 
8631     return uint32_t(0x0c0c0c0c03020100ull >> C);
8632   }
8633 
8634   return ~0;
8635 }
8636 
8637 SDValue SITargetLowering::performAndCombine(SDNode *N,
8638                                             DAGCombinerInfo &DCI) const {
8639   if (DCI.isBeforeLegalize())
8640     return SDValue();
8641 
8642   SelectionDAG &DAG = DCI.DAG;
8643   EVT VT = N->getValueType(0);
8644   SDValue LHS = N->getOperand(0);
8645   SDValue RHS = N->getOperand(1);
8646 
8647 
8648   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8649   if (VT == MVT::i64 && CRHS) {
8650     if (SDValue Split
8651         = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::AND, LHS, CRHS))
8652       return Split;
8653   }
8654 
8655   if (CRHS && VT == MVT::i32) {
8656     // and (srl x, c), mask => shl (bfe x, nb + c, mask >> nb), nb
8657     // nb = number of trailing zeroes in mask
8658     // It can be optimized out using SDWA for GFX8+ in the SDWA peephole pass,
8659     // given that we are selecting 8 or 16 bit fields starting at byte boundary.
8660     uint64_t Mask = CRHS->getZExtValue();
8661     unsigned Bits = countPopulation(Mask);
8662     if (getSubtarget()->hasSDWA() && LHS->getOpcode() == ISD::SRL &&
8663         (Bits == 8 || Bits == 16) && isShiftedMask_64(Mask) && !(Mask & 1)) {
8664       if (auto *CShift = dyn_cast<ConstantSDNode>(LHS->getOperand(1))) {
8665         unsigned Shift = CShift->getZExtValue();
8666         unsigned NB = CRHS->getAPIntValue().countTrailingZeros();
8667         unsigned Offset = NB + Shift;
8668         if ((Offset & (Bits - 1)) == 0) { // Starts at a byte or word boundary.
8669           SDLoc SL(N);
8670           SDValue BFE = DAG.getNode(AMDGPUISD::BFE_U32, SL, MVT::i32,
8671                                     LHS->getOperand(0),
8672                                     DAG.getConstant(Offset, SL, MVT::i32),
8673                                     DAG.getConstant(Bits, SL, MVT::i32));
8674           EVT NarrowVT = EVT::getIntegerVT(*DAG.getContext(), Bits);
8675           SDValue Ext = DAG.getNode(ISD::AssertZext, SL, VT, BFE,
8676                                     DAG.getValueType(NarrowVT));
8677           SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(LHS), VT, Ext,
8678                                     DAG.getConstant(NB, SDLoc(CRHS), MVT::i32));
8679           return Shl;
8680         }
8681       }
8682     }
8683 
8684     // and (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8685     if (LHS.hasOneUse() && LHS.getOpcode() == AMDGPUISD::PERM &&
8686         isa<ConstantSDNode>(LHS.getOperand(2))) {
8687       uint32_t Sel = getConstantPermuteMask(Mask);
8688       if (!Sel)
8689         return SDValue();
8690 
8691       // Select 0xc for all zero bytes
8692       Sel = (LHS.getConstantOperandVal(2) & Sel) | (~Sel & 0x0c0c0c0c);
8693       SDLoc DL(N);
8694       return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8695                          LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8696     }
8697   }
8698 
8699   // (and (fcmp ord x, x), (fcmp une (fabs x), inf)) ->
8700   // fp_class x, ~(s_nan | q_nan | n_infinity | p_infinity)
8701   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == ISD::SETCC) {
8702     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8703     ISD::CondCode RCC = cast<CondCodeSDNode>(RHS.getOperand(2))->get();
8704 
8705     SDValue X = LHS.getOperand(0);
8706     SDValue Y = RHS.getOperand(0);
8707     if (Y.getOpcode() != ISD::FABS || Y.getOperand(0) != X)
8708       return SDValue();
8709 
8710     if (LCC == ISD::SETO) {
8711       if (X != LHS.getOperand(1))
8712         return SDValue();
8713 
8714       if (RCC == ISD::SETUNE) {
8715         const ConstantFPSDNode *C1 = dyn_cast<ConstantFPSDNode>(RHS.getOperand(1));
8716         if (!C1 || !C1->isInfinity() || C1->isNegative())
8717           return SDValue();
8718 
8719         const uint32_t Mask = SIInstrFlags::N_NORMAL |
8720                               SIInstrFlags::N_SUBNORMAL |
8721                               SIInstrFlags::N_ZERO |
8722                               SIInstrFlags::P_ZERO |
8723                               SIInstrFlags::P_SUBNORMAL |
8724                               SIInstrFlags::P_NORMAL;
8725 
8726         static_assert(((~(SIInstrFlags::S_NAN |
8727                           SIInstrFlags::Q_NAN |
8728                           SIInstrFlags::N_INFINITY |
8729                           SIInstrFlags::P_INFINITY)) & 0x3ff) == Mask,
8730                       "mask not equal");
8731 
8732         SDLoc DL(N);
8733         return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8734                            X, DAG.getConstant(Mask, DL, MVT::i32));
8735       }
8736     }
8737   }
8738 
8739   if (RHS.getOpcode() == ISD::SETCC && LHS.getOpcode() == AMDGPUISD::FP_CLASS)
8740     std::swap(LHS, RHS);
8741 
8742   if (LHS.getOpcode() == ISD::SETCC && RHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8743       RHS.hasOneUse()) {
8744     ISD::CondCode LCC = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
8745     // and (fcmp seto), (fp_class x, mask) -> fp_class x, mask & ~(p_nan | n_nan)
8746     // and (fcmp setuo), (fp_class x, mask) -> fp_class x, mask & (p_nan | n_nan)
8747     const ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8748     if ((LCC == ISD::SETO || LCC == ISD::SETUO) && Mask &&
8749         (RHS.getOperand(0) == LHS.getOperand(0) &&
8750          LHS.getOperand(0) == LHS.getOperand(1))) {
8751       const unsigned OrdMask = SIInstrFlags::S_NAN | SIInstrFlags::Q_NAN;
8752       unsigned NewMask = LCC == ISD::SETO ?
8753         Mask->getZExtValue() & ~OrdMask :
8754         Mask->getZExtValue() & OrdMask;
8755 
8756       SDLoc DL(N);
8757       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1, RHS.getOperand(0),
8758                          DAG.getConstant(NewMask, DL, MVT::i32));
8759     }
8760   }
8761 
8762   if (VT == MVT::i32 &&
8763       (RHS.getOpcode() == ISD::SIGN_EXTEND || LHS.getOpcode() == ISD::SIGN_EXTEND)) {
8764     // and x, (sext cc from i1) => select cc, x, 0
8765     if (RHS.getOpcode() != ISD::SIGN_EXTEND)
8766       std::swap(LHS, RHS);
8767     if (isBoolSGPR(RHS.getOperand(0)))
8768       return DAG.getSelect(SDLoc(N), MVT::i32, RHS.getOperand(0),
8769                            LHS, DAG.getConstant(0, SDLoc(N), MVT::i32));
8770   }
8771 
8772   // and (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8773   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8774   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8775       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8776     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8777     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8778     if (LHSMask != ~0u && RHSMask != ~0u) {
8779       // Canonicalize the expression in an attempt to have fewer unique masks
8780       // and therefore fewer registers used to hold the masks.
8781       if (LHSMask > RHSMask) {
8782         std::swap(LHSMask, RHSMask);
8783         std::swap(LHS, RHS);
8784       }
8785 
8786       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8787       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8788       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8789       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8790 
8791       // Check of we need to combine values from two sources within a byte.
8792       if (!(LHSUsedLanes & RHSUsedLanes) &&
8793           // If we select high and lower word keep it for SDWA.
8794           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8795           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8796         // Each byte in each mask is either selector mask 0-3, or has higher
8797         // bits set in either of masks, which can be 0xff for 0xff or 0x0c for
8798         // zero. If 0x0c is in either mask it shall always be 0x0c. Otherwise
8799         // mask which is not 0xff wins. By anding both masks we have a correct
8800         // result except that 0x0c shall be corrected to give 0x0c only.
8801         uint32_t Mask = LHSMask & RHSMask;
8802         for (unsigned I = 0; I < 32; I += 8) {
8803           uint32_t ByteSel = 0xff << I;
8804           if ((LHSMask & ByteSel) == 0x0c || (RHSMask & ByteSel) == 0x0c)
8805             Mask &= (0x0c << I) & 0xffffffff;
8806         }
8807 
8808         // Add 4 to each active LHS lane. It will not affect any existing 0xff
8809         // or 0x0c.
8810         uint32_t Sel = Mask | (LHSUsedLanes & 0x04040404);
8811         SDLoc DL(N);
8812 
8813         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8814                            LHS.getOperand(0), RHS.getOperand(0),
8815                            DAG.getConstant(Sel, DL, MVT::i32));
8816       }
8817     }
8818   }
8819 
8820   return SDValue();
8821 }
8822 
8823 SDValue SITargetLowering::performOrCombine(SDNode *N,
8824                                            DAGCombinerInfo &DCI) const {
8825   SelectionDAG &DAG = DCI.DAG;
8826   SDValue LHS = N->getOperand(0);
8827   SDValue RHS = N->getOperand(1);
8828 
8829   EVT VT = N->getValueType(0);
8830   if (VT == MVT::i1) {
8831     // or (fp_class x, c1), (fp_class x, c2) -> fp_class x, (c1 | c2)
8832     if (LHS.getOpcode() == AMDGPUISD::FP_CLASS &&
8833         RHS.getOpcode() == AMDGPUISD::FP_CLASS) {
8834       SDValue Src = LHS.getOperand(0);
8835       if (Src != RHS.getOperand(0))
8836         return SDValue();
8837 
8838       const ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
8839       const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
8840       if (!CLHS || !CRHS)
8841         return SDValue();
8842 
8843       // Only 10 bits are used.
8844       static const uint32_t MaxMask = 0x3ff;
8845 
8846       uint32_t NewMask = (CLHS->getZExtValue() | CRHS->getZExtValue()) & MaxMask;
8847       SDLoc DL(N);
8848       return DAG.getNode(AMDGPUISD::FP_CLASS, DL, MVT::i1,
8849                          Src, DAG.getConstant(NewMask, DL, MVT::i32));
8850     }
8851 
8852     return SDValue();
8853   }
8854 
8855   // or (perm x, y, c1), c2 -> perm x, y, permute_mask(c1, c2)
8856   if (isa<ConstantSDNode>(RHS) && LHS.hasOneUse() &&
8857       LHS.getOpcode() == AMDGPUISD::PERM &&
8858       isa<ConstantSDNode>(LHS.getOperand(2))) {
8859     uint32_t Sel = getConstantPermuteMask(N->getConstantOperandVal(1));
8860     if (!Sel)
8861       return SDValue();
8862 
8863     Sel |= LHS.getConstantOperandVal(2);
8864     SDLoc DL(N);
8865     return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32, LHS.getOperand(0),
8866                        LHS.getOperand(1), DAG.getConstant(Sel, DL, MVT::i32));
8867   }
8868 
8869   // or (op x, c1), (op y, c2) -> perm x, y, permute_mask(c1, c2)
8870   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
8871   if (VT == MVT::i32 && LHS.hasOneUse() && RHS.hasOneUse() &&
8872       N->isDivergent() && TII->pseudoToMCOpcode(AMDGPU::V_PERM_B32) != -1) {
8873     uint32_t LHSMask = getPermuteMask(DAG, LHS);
8874     uint32_t RHSMask = getPermuteMask(DAG, RHS);
8875     if (LHSMask != ~0u && RHSMask != ~0u) {
8876       // Canonicalize the expression in an attempt to have fewer unique masks
8877       // and therefore fewer registers used to hold the masks.
8878       if (LHSMask > RHSMask) {
8879         std::swap(LHSMask, RHSMask);
8880         std::swap(LHS, RHS);
8881       }
8882 
8883       // Select 0xc for each lane used from source operand. Zero has 0xc mask
8884       // set, 0xff have 0xff in the mask, actual lanes are in the 0-3 range.
8885       uint32_t LHSUsedLanes = ~(LHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8886       uint32_t RHSUsedLanes = ~(RHSMask & 0x0c0c0c0c) & 0x0c0c0c0c;
8887 
8888       // Check of we need to combine values from two sources within a byte.
8889       if (!(LHSUsedLanes & RHSUsedLanes) &&
8890           // If we select high and lower word keep it for SDWA.
8891           // TODO: teach SDWA to work with v_perm_b32 and remove the check.
8892           !(LHSUsedLanes == 0x0c0c0000 && RHSUsedLanes == 0x00000c0c)) {
8893         // Kill zero bytes selected by other mask. Zero value is 0xc.
8894         LHSMask &= ~RHSUsedLanes;
8895         RHSMask &= ~LHSUsedLanes;
8896         // Add 4 to each active LHS lane
8897         LHSMask |= LHSUsedLanes & 0x04040404;
8898         // Combine masks
8899         uint32_t Sel = LHSMask | RHSMask;
8900         SDLoc DL(N);
8901 
8902         return DAG.getNode(AMDGPUISD::PERM, DL, MVT::i32,
8903                            LHS.getOperand(0), RHS.getOperand(0),
8904                            DAG.getConstant(Sel, DL, MVT::i32));
8905       }
8906     }
8907   }
8908 
8909   if (VT != MVT::i64)
8910     return SDValue();
8911 
8912   // TODO: This could be a generic combine with a predicate for extracting the
8913   // high half of an integer being free.
8914 
8915   // (or i64:x, (zero_extend i32:y)) ->
8916   //   i64 (bitcast (v2i32 build_vector (or i32:y, lo_32(x)), hi_32(x)))
8917   if (LHS.getOpcode() == ISD::ZERO_EXTEND &&
8918       RHS.getOpcode() != ISD::ZERO_EXTEND)
8919     std::swap(LHS, RHS);
8920 
8921   if (RHS.getOpcode() == ISD::ZERO_EXTEND) {
8922     SDValue ExtSrc = RHS.getOperand(0);
8923     EVT SrcVT = ExtSrc.getValueType();
8924     if (SrcVT == MVT::i32) {
8925       SDLoc SL(N);
8926       SDValue LowLHS, HiBits;
8927       std::tie(LowLHS, HiBits) = split64BitValue(LHS, DAG);
8928       SDValue LowOr = DAG.getNode(ISD::OR, SL, MVT::i32, LowLHS, ExtSrc);
8929 
8930       DCI.AddToWorklist(LowOr.getNode());
8931       DCI.AddToWorklist(HiBits.getNode());
8932 
8933       SDValue Vec = DAG.getNode(ISD::BUILD_VECTOR, SL, MVT::v2i32,
8934                                 LowOr, HiBits);
8935       return DAG.getNode(ISD::BITCAST, SL, MVT::i64, Vec);
8936     }
8937   }
8938 
8939   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(N->getOperand(1));
8940   if (CRHS) {
8941     if (SDValue Split
8942           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::OR, LHS, CRHS))
8943       return Split;
8944   }
8945 
8946   return SDValue();
8947 }
8948 
8949 SDValue SITargetLowering::performXorCombine(SDNode *N,
8950                                             DAGCombinerInfo &DCI) const {
8951   EVT VT = N->getValueType(0);
8952   if (VT != MVT::i64)
8953     return SDValue();
8954 
8955   SDValue LHS = N->getOperand(0);
8956   SDValue RHS = N->getOperand(1);
8957 
8958   const ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(RHS);
8959   if (CRHS) {
8960     if (SDValue Split
8961           = splitBinaryBitConstantOp(DCI, SDLoc(N), ISD::XOR, LHS, CRHS))
8962       return Split;
8963   }
8964 
8965   return SDValue();
8966 }
8967 
8968 // Instructions that will be lowered with a final instruction that zeros the
8969 // high result bits.
8970 // XXX - probably only need to list legal operations.
8971 static bool fp16SrcZerosHighBits(unsigned Opc) {
8972   switch (Opc) {
8973   case ISD::FADD:
8974   case ISD::FSUB:
8975   case ISD::FMUL:
8976   case ISD::FDIV:
8977   case ISD::FREM:
8978   case ISD::FMA:
8979   case ISD::FMAD:
8980   case ISD::FCANONICALIZE:
8981   case ISD::FP_ROUND:
8982   case ISD::UINT_TO_FP:
8983   case ISD::SINT_TO_FP:
8984   case ISD::FABS:
8985     // Fabs is lowered to a bit operation, but it's an and which will clear the
8986     // high bits anyway.
8987   case ISD::FSQRT:
8988   case ISD::FSIN:
8989   case ISD::FCOS:
8990   case ISD::FPOWI:
8991   case ISD::FPOW:
8992   case ISD::FLOG:
8993   case ISD::FLOG2:
8994   case ISD::FLOG10:
8995   case ISD::FEXP:
8996   case ISD::FEXP2:
8997   case ISD::FCEIL:
8998   case ISD::FTRUNC:
8999   case ISD::FRINT:
9000   case ISD::FNEARBYINT:
9001   case ISD::FROUND:
9002   case ISD::FFLOOR:
9003   case ISD::FMINNUM:
9004   case ISD::FMAXNUM:
9005   case AMDGPUISD::FRACT:
9006   case AMDGPUISD::CLAMP:
9007   case AMDGPUISD::COS_HW:
9008   case AMDGPUISD::SIN_HW:
9009   case AMDGPUISD::FMIN3:
9010   case AMDGPUISD::FMAX3:
9011   case AMDGPUISD::FMED3:
9012   case AMDGPUISD::FMAD_FTZ:
9013   case AMDGPUISD::RCP:
9014   case AMDGPUISD::RSQ:
9015   case AMDGPUISD::RCP_IFLAG:
9016   case AMDGPUISD::LDEXP:
9017     return true;
9018   default:
9019     // fcopysign, select and others may be lowered to 32-bit bit operations
9020     // which don't zero the high bits.
9021     return false;
9022   }
9023 }
9024 
9025 SDValue SITargetLowering::performZeroExtendCombine(SDNode *N,
9026                                                    DAGCombinerInfo &DCI) const {
9027   if (!Subtarget->has16BitInsts() ||
9028       DCI.getDAGCombineLevel() < AfterLegalizeDAG)
9029     return SDValue();
9030 
9031   EVT VT = N->getValueType(0);
9032   if (VT != MVT::i32)
9033     return SDValue();
9034 
9035   SDValue Src = N->getOperand(0);
9036   if (Src.getValueType() != MVT::i16)
9037     return SDValue();
9038 
9039   // (i32 zext (i16 (bitcast f16:$src))) -> fp16_zext $src
9040   // FIXME: It is not universally true that the high bits are zeroed on gfx9.
9041   if (Src.getOpcode() == ISD::BITCAST) {
9042     SDValue BCSrc = Src.getOperand(0);
9043     if (BCSrc.getValueType() == MVT::f16 &&
9044         fp16SrcZerosHighBits(BCSrc.getOpcode()))
9045       return DCI.DAG.getNode(AMDGPUISD::FP16_ZEXT, SDLoc(N), VT, BCSrc);
9046   }
9047 
9048   return SDValue();
9049 }
9050 
9051 SDValue SITargetLowering::performSignExtendInRegCombine(SDNode *N,
9052                                                         DAGCombinerInfo &DCI)
9053                                                         const {
9054   SDValue Src = N->getOperand(0);
9055   auto *VTSign = cast<VTSDNode>(N->getOperand(1));
9056 
9057   if (((Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE &&
9058       VTSign->getVT() == MVT::i8) ||
9059       (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_USHORT &&
9060       VTSign->getVT() == MVT::i16)) &&
9061       Src.hasOneUse()) {
9062     auto *M = cast<MemSDNode>(Src);
9063     SDValue Ops[] = {
9064       Src.getOperand(0), // Chain
9065       Src.getOperand(1), // rsrc
9066       Src.getOperand(2), // vindex
9067       Src.getOperand(3), // voffset
9068       Src.getOperand(4), // soffset
9069       Src.getOperand(5), // offset
9070       Src.getOperand(6),
9071       Src.getOperand(7)
9072     };
9073     // replace with BUFFER_LOAD_BYTE/SHORT
9074     SDVTList ResList = DCI.DAG.getVTList(MVT::i32,
9075                                          Src.getOperand(0).getValueType());
9076     unsigned Opc = (Src.getOpcode() == AMDGPUISD::BUFFER_LOAD_UBYTE) ?
9077                    AMDGPUISD::BUFFER_LOAD_BYTE : AMDGPUISD::BUFFER_LOAD_SHORT;
9078     SDValue BufferLoadSignExt = DCI.DAG.getMemIntrinsicNode(Opc, SDLoc(N),
9079                                                           ResList,
9080                                                           Ops, M->getMemoryVT(),
9081                                                           M->getMemOperand());
9082     return DCI.DAG.getMergeValues({BufferLoadSignExt,
9083                                   BufferLoadSignExt.getValue(1)}, SDLoc(N));
9084   }
9085   return SDValue();
9086 }
9087 
9088 SDValue SITargetLowering::performClassCombine(SDNode *N,
9089                                               DAGCombinerInfo &DCI) const {
9090   SelectionDAG &DAG = DCI.DAG;
9091   SDValue Mask = N->getOperand(1);
9092 
9093   // fp_class x, 0 -> false
9094   if (const ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(Mask)) {
9095     if (CMask->isNullValue())
9096       return DAG.getConstant(0, SDLoc(N), MVT::i1);
9097   }
9098 
9099   if (N->getOperand(0).isUndef())
9100     return DAG.getUNDEF(MVT::i1);
9101 
9102   return SDValue();
9103 }
9104 
9105 SDValue SITargetLowering::performRcpCombine(SDNode *N,
9106                                             DAGCombinerInfo &DCI) const {
9107   EVT VT = N->getValueType(0);
9108   SDValue N0 = N->getOperand(0);
9109 
9110   if (N0.isUndef())
9111     return N0;
9112 
9113   if (VT == MVT::f32 && (N0.getOpcode() == ISD::UINT_TO_FP ||
9114                          N0.getOpcode() == ISD::SINT_TO_FP)) {
9115     return DCI.DAG.getNode(AMDGPUISD::RCP_IFLAG, SDLoc(N), VT, N0,
9116                            N->getFlags());
9117   }
9118 
9119   if ((VT == MVT::f32 || VT == MVT::f16) && N0.getOpcode() == ISD::FSQRT) {
9120     return DCI.DAG.getNode(AMDGPUISD::RSQ, SDLoc(N), VT,
9121                            N0.getOperand(0), N->getFlags());
9122   }
9123 
9124   return AMDGPUTargetLowering::performRcpCombine(N, DCI);
9125 }
9126 
9127 bool SITargetLowering::isCanonicalized(SelectionDAG &DAG, SDValue Op,
9128                                        unsigned MaxDepth) const {
9129   unsigned Opcode = Op.getOpcode();
9130   if (Opcode == ISD::FCANONICALIZE)
9131     return true;
9132 
9133   if (auto *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9134     auto F = CFP->getValueAPF();
9135     if (F.isNaN() && F.isSignaling())
9136       return false;
9137     return !F.isDenormal() || denormalsEnabledForType(DAG, Op.getValueType());
9138   }
9139 
9140   // If source is a result of another standard FP operation it is already in
9141   // canonical form.
9142   if (MaxDepth == 0)
9143     return false;
9144 
9145   switch (Opcode) {
9146   // These will flush denorms if required.
9147   case ISD::FADD:
9148   case ISD::FSUB:
9149   case ISD::FMUL:
9150   case ISD::FCEIL:
9151   case ISD::FFLOOR:
9152   case ISD::FMA:
9153   case ISD::FMAD:
9154   case ISD::FSQRT:
9155   case ISD::FDIV:
9156   case ISD::FREM:
9157   case ISD::FP_ROUND:
9158   case ISD::FP_EXTEND:
9159   case AMDGPUISD::FMUL_LEGACY:
9160   case AMDGPUISD::FMAD_FTZ:
9161   case AMDGPUISD::RCP:
9162   case AMDGPUISD::RSQ:
9163   case AMDGPUISD::RSQ_CLAMP:
9164   case AMDGPUISD::RCP_LEGACY:
9165   case AMDGPUISD::RCP_IFLAG:
9166   case AMDGPUISD::TRIG_PREOP:
9167   case AMDGPUISD::DIV_SCALE:
9168   case AMDGPUISD::DIV_FMAS:
9169   case AMDGPUISD::DIV_FIXUP:
9170   case AMDGPUISD::FRACT:
9171   case AMDGPUISD::LDEXP:
9172   case AMDGPUISD::CVT_PKRTZ_F16_F32:
9173   case AMDGPUISD::CVT_F32_UBYTE0:
9174   case AMDGPUISD::CVT_F32_UBYTE1:
9175   case AMDGPUISD::CVT_F32_UBYTE2:
9176   case AMDGPUISD::CVT_F32_UBYTE3:
9177     return true;
9178 
9179   // It can/will be lowered or combined as a bit operation.
9180   // Need to check their input recursively to handle.
9181   case ISD::FNEG:
9182   case ISD::FABS:
9183   case ISD::FCOPYSIGN:
9184     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9185 
9186   case ISD::FSIN:
9187   case ISD::FCOS:
9188   case ISD::FSINCOS:
9189     return Op.getValueType().getScalarType() != MVT::f16;
9190 
9191   case ISD::FMINNUM:
9192   case ISD::FMAXNUM:
9193   case ISD::FMINNUM_IEEE:
9194   case ISD::FMAXNUM_IEEE:
9195   case AMDGPUISD::CLAMP:
9196   case AMDGPUISD::FMED3:
9197   case AMDGPUISD::FMAX3:
9198   case AMDGPUISD::FMIN3: {
9199     // FIXME: Shouldn't treat the generic operations different based these.
9200     // However, we aren't really required to flush the result from
9201     // minnum/maxnum..
9202 
9203     // snans will be quieted, so we only need to worry about denormals.
9204     if (Subtarget->supportsMinMaxDenormModes() ||
9205         denormalsEnabledForType(DAG, Op.getValueType()))
9206       return true;
9207 
9208     // Flushing may be required.
9209     // In pre-GFX9 targets V_MIN_F32 and others do not flush denorms. For such
9210     // targets need to check their input recursively.
9211 
9212     // FIXME: Does this apply with clamp? It's implemented with max.
9213     for (unsigned I = 0, E = Op.getNumOperands(); I != E; ++I) {
9214       if (!isCanonicalized(DAG, Op.getOperand(I), MaxDepth - 1))
9215         return false;
9216     }
9217 
9218     return true;
9219   }
9220   case ISD::SELECT: {
9221     return isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1) &&
9222            isCanonicalized(DAG, Op.getOperand(2), MaxDepth - 1);
9223   }
9224   case ISD::BUILD_VECTOR: {
9225     for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
9226       SDValue SrcOp = Op.getOperand(i);
9227       if (!isCanonicalized(DAG, SrcOp, MaxDepth - 1))
9228         return false;
9229     }
9230 
9231     return true;
9232   }
9233   case ISD::EXTRACT_VECTOR_ELT:
9234   case ISD::EXTRACT_SUBVECTOR: {
9235     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1);
9236   }
9237   case ISD::INSERT_VECTOR_ELT: {
9238     return isCanonicalized(DAG, Op.getOperand(0), MaxDepth - 1) &&
9239            isCanonicalized(DAG, Op.getOperand(1), MaxDepth - 1);
9240   }
9241   case ISD::UNDEF:
9242     // Could be anything.
9243     return false;
9244 
9245   case ISD::BITCAST: {
9246     // Hack round the mess we make when legalizing extract_vector_elt
9247     SDValue Src = Op.getOperand(0);
9248     if (Src.getValueType() == MVT::i16 &&
9249         Src.getOpcode() == ISD::TRUNCATE) {
9250       SDValue TruncSrc = Src.getOperand(0);
9251       if (TruncSrc.getValueType() == MVT::i32 &&
9252           TruncSrc.getOpcode() == ISD::BITCAST &&
9253           TruncSrc.getOperand(0).getValueType() == MVT::v2f16) {
9254         return isCanonicalized(DAG, TruncSrc.getOperand(0), MaxDepth - 1);
9255       }
9256     }
9257 
9258     return false;
9259   }
9260   case ISD::INTRINSIC_WO_CHAIN: {
9261     unsigned IntrinsicID
9262       = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
9263     // TODO: Handle more intrinsics
9264     switch (IntrinsicID) {
9265     case Intrinsic::amdgcn_cvt_pkrtz:
9266     case Intrinsic::amdgcn_cubeid:
9267     case Intrinsic::amdgcn_frexp_mant:
9268     case Intrinsic::amdgcn_fdot2:
9269     case Intrinsic::amdgcn_rcp:
9270     case Intrinsic::amdgcn_rsq:
9271     case Intrinsic::amdgcn_rsq_clamp:
9272     case Intrinsic::amdgcn_rcp_legacy:
9273     case Intrinsic::amdgcn_rsq_legacy:
9274       return true;
9275     default:
9276       break;
9277     }
9278 
9279     LLVM_FALLTHROUGH;
9280   }
9281   default:
9282     return denormalsEnabledForType(DAG, Op.getValueType()) &&
9283            DAG.isKnownNeverSNaN(Op);
9284   }
9285 
9286   llvm_unreachable("invalid operation");
9287 }
9288 
9289 // Constant fold canonicalize.
9290 SDValue SITargetLowering::getCanonicalConstantFP(
9291   SelectionDAG &DAG, const SDLoc &SL, EVT VT, const APFloat &C) const {
9292   // Flush denormals to 0 if not enabled.
9293   if (C.isDenormal() && !denormalsEnabledForType(DAG, VT))
9294     return DAG.getConstantFP(0.0, SL, VT);
9295 
9296   if (C.isNaN()) {
9297     APFloat CanonicalQNaN = APFloat::getQNaN(C.getSemantics());
9298     if (C.isSignaling()) {
9299       // Quiet a signaling NaN.
9300       // FIXME: Is this supposed to preserve payload bits?
9301       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9302     }
9303 
9304     // Make sure it is the canonical NaN bitpattern.
9305     //
9306     // TODO: Can we use -1 as the canonical NaN value since it's an inline
9307     // immediate?
9308     if (C.bitcastToAPInt() != CanonicalQNaN.bitcastToAPInt())
9309       return DAG.getConstantFP(CanonicalQNaN, SL, VT);
9310   }
9311 
9312   // Already canonical.
9313   return DAG.getConstantFP(C, SL, VT);
9314 }
9315 
9316 static bool vectorEltWillFoldAway(SDValue Op) {
9317   return Op.isUndef() || isa<ConstantFPSDNode>(Op);
9318 }
9319 
9320 SDValue SITargetLowering::performFCanonicalizeCombine(
9321   SDNode *N,
9322   DAGCombinerInfo &DCI) const {
9323   SelectionDAG &DAG = DCI.DAG;
9324   SDValue N0 = N->getOperand(0);
9325   EVT VT = N->getValueType(0);
9326 
9327   // fcanonicalize undef -> qnan
9328   if (N0.isUndef()) {
9329     APFloat QNaN = APFloat::getQNaN(SelectionDAG::EVTToAPFloatSemantics(VT));
9330     return DAG.getConstantFP(QNaN, SDLoc(N), VT);
9331   }
9332 
9333   if (ConstantFPSDNode *CFP = isConstOrConstSplatFP(N0)) {
9334     EVT VT = N->getValueType(0);
9335     return getCanonicalConstantFP(DAG, SDLoc(N), VT, CFP->getValueAPF());
9336   }
9337 
9338   // fcanonicalize (build_vector x, k) -> build_vector (fcanonicalize x),
9339   //                                                   (fcanonicalize k)
9340   //
9341   // fcanonicalize (build_vector x, undef) -> build_vector (fcanonicalize x), 0
9342 
9343   // TODO: This could be better with wider vectors that will be split to v2f16,
9344   // and to consider uses since there aren't that many packed operations.
9345   if (N0.getOpcode() == ISD::BUILD_VECTOR && VT == MVT::v2f16 &&
9346       isTypeLegal(MVT::v2f16)) {
9347     SDLoc SL(N);
9348     SDValue NewElts[2];
9349     SDValue Lo = N0.getOperand(0);
9350     SDValue Hi = N0.getOperand(1);
9351     EVT EltVT = Lo.getValueType();
9352 
9353     if (vectorEltWillFoldAway(Lo) || vectorEltWillFoldAway(Hi)) {
9354       for (unsigned I = 0; I != 2; ++I) {
9355         SDValue Op = N0.getOperand(I);
9356         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op)) {
9357           NewElts[I] = getCanonicalConstantFP(DAG, SL, EltVT,
9358                                               CFP->getValueAPF());
9359         } else if (Op.isUndef()) {
9360           // Handled below based on what the other operand is.
9361           NewElts[I] = Op;
9362         } else {
9363           NewElts[I] = DAG.getNode(ISD::FCANONICALIZE, SL, EltVT, Op);
9364         }
9365       }
9366 
9367       // If one half is undef, and one is constant, perfer a splat vector rather
9368       // than the normal qNaN. If it's a register, prefer 0.0 since that's
9369       // cheaper to use and may be free with a packed operation.
9370       if (NewElts[0].isUndef()) {
9371         if (isa<ConstantFPSDNode>(NewElts[1]))
9372           NewElts[0] = isa<ConstantFPSDNode>(NewElts[1]) ?
9373             NewElts[1]: DAG.getConstantFP(0.0f, SL, EltVT);
9374       }
9375 
9376       if (NewElts[1].isUndef()) {
9377         NewElts[1] = isa<ConstantFPSDNode>(NewElts[0]) ?
9378           NewElts[0] : DAG.getConstantFP(0.0f, SL, EltVT);
9379       }
9380 
9381       return DAG.getBuildVector(VT, SL, NewElts);
9382     }
9383   }
9384 
9385   unsigned SrcOpc = N0.getOpcode();
9386 
9387   // If it's free to do so, push canonicalizes further up the source, which may
9388   // find a canonical source.
9389   //
9390   // TODO: More opcodes. Note this is unsafe for the the _ieee minnum/maxnum for
9391   // sNaNs.
9392   if (SrcOpc == ISD::FMINNUM || SrcOpc == ISD::FMAXNUM) {
9393     auto *CRHS = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
9394     if (CRHS && N0.hasOneUse()) {
9395       SDLoc SL(N);
9396       SDValue Canon0 = DAG.getNode(ISD::FCANONICALIZE, SL, VT,
9397                                    N0.getOperand(0));
9398       SDValue Canon1 = getCanonicalConstantFP(DAG, SL, VT, CRHS->getValueAPF());
9399       DCI.AddToWorklist(Canon0.getNode());
9400 
9401       return DAG.getNode(N0.getOpcode(), SL, VT, Canon0, Canon1);
9402     }
9403   }
9404 
9405   return isCanonicalized(DAG, N0) ? N0 : SDValue();
9406 }
9407 
9408 static unsigned minMaxOpcToMin3Max3Opc(unsigned Opc) {
9409   switch (Opc) {
9410   case ISD::FMAXNUM:
9411   case ISD::FMAXNUM_IEEE:
9412     return AMDGPUISD::FMAX3;
9413   case ISD::SMAX:
9414     return AMDGPUISD::SMAX3;
9415   case ISD::UMAX:
9416     return AMDGPUISD::UMAX3;
9417   case ISD::FMINNUM:
9418   case ISD::FMINNUM_IEEE:
9419     return AMDGPUISD::FMIN3;
9420   case ISD::SMIN:
9421     return AMDGPUISD::SMIN3;
9422   case ISD::UMIN:
9423     return AMDGPUISD::UMIN3;
9424   default:
9425     llvm_unreachable("Not a min/max opcode");
9426   }
9427 }
9428 
9429 SDValue SITargetLowering::performIntMed3ImmCombine(
9430   SelectionDAG &DAG, const SDLoc &SL,
9431   SDValue Op0, SDValue Op1, bool Signed) const {
9432   ConstantSDNode *K1 = dyn_cast<ConstantSDNode>(Op1);
9433   if (!K1)
9434     return SDValue();
9435 
9436   ConstantSDNode *K0 = dyn_cast<ConstantSDNode>(Op0.getOperand(1));
9437   if (!K0)
9438     return SDValue();
9439 
9440   if (Signed) {
9441     if (K0->getAPIntValue().sge(K1->getAPIntValue()))
9442       return SDValue();
9443   } else {
9444     if (K0->getAPIntValue().uge(K1->getAPIntValue()))
9445       return SDValue();
9446   }
9447 
9448   EVT VT = K0->getValueType(0);
9449   unsigned Med3Opc = Signed ? AMDGPUISD::SMED3 : AMDGPUISD::UMED3;
9450   if (VT == MVT::i32 || (VT == MVT::i16 && Subtarget->hasMed3_16())) {
9451     return DAG.getNode(Med3Opc, SL, VT,
9452                        Op0.getOperand(0), SDValue(K0, 0), SDValue(K1, 0));
9453   }
9454 
9455   // If there isn't a 16-bit med3 operation, convert to 32-bit.
9456   MVT NVT = MVT::i32;
9457   unsigned ExtOp = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
9458 
9459   SDValue Tmp1 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(0));
9460   SDValue Tmp2 = DAG.getNode(ExtOp, SL, NVT, Op0->getOperand(1));
9461   SDValue Tmp3 = DAG.getNode(ExtOp, SL, NVT, Op1);
9462 
9463   SDValue Med3 = DAG.getNode(Med3Opc, SL, NVT, Tmp1, Tmp2, Tmp3);
9464   return DAG.getNode(ISD::TRUNCATE, SL, VT, Med3);
9465 }
9466 
9467 static ConstantFPSDNode *getSplatConstantFP(SDValue Op) {
9468   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
9469     return C;
9470 
9471   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op)) {
9472     if (ConstantFPSDNode *C = BV->getConstantFPSplatNode())
9473       return C;
9474   }
9475 
9476   return nullptr;
9477 }
9478 
9479 SDValue SITargetLowering::performFPMed3ImmCombine(SelectionDAG &DAG,
9480                                                   const SDLoc &SL,
9481                                                   SDValue Op0,
9482                                                   SDValue Op1) const {
9483   ConstantFPSDNode *K1 = getSplatConstantFP(Op1);
9484   if (!K1)
9485     return SDValue();
9486 
9487   ConstantFPSDNode *K0 = getSplatConstantFP(Op0.getOperand(1));
9488   if (!K0)
9489     return SDValue();
9490 
9491   // Ordered >= (although NaN inputs should have folded away by now).
9492   if (K0->getValueAPF() > K1->getValueAPF())
9493     return SDValue();
9494 
9495   const MachineFunction &MF = DAG.getMachineFunction();
9496   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9497 
9498   // TODO: Check IEEE bit enabled?
9499   EVT VT = Op0.getValueType();
9500   if (Info->getMode().DX10Clamp) {
9501     // If dx10_clamp is enabled, NaNs clamp to 0.0. This is the same as the
9502     // hardware fmed3 behavior converting to a min.
9503     // FIXME: Should this be allowing -0.0?
9504     if (K1->isExactlyValue(1.0) && K0->isExactlyValue(0.0))
9505       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Op0.getOperand(0));
9506   }
9507 
9508   // med3 for f16 is only available on gfx9+, and not available for v2f16.
9509   if (VT == MVT::f32 || (VT == MVT::f16 && Subtarget->hasMed3_16())) {
9510     // This isn't safe with signaling NaNs because in IEEE mode, min/max on a
9511     // signaling NaN gives a quiet NaN. The quiet NaN input to the min would
9512     // then give the other result, which is different from med3 with a NaN
9513     // input.
9514     SDValue Var = Op0.getOperand(0);
9515     if (!DAG.isKnownNeverSNaN(Var))
9516       return SDValue();
9517 
9518     const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
9519 
9520     if ((!K0->hasOneUse() ||
9521          TII->isInlineConstant(K0->getValueAPF().bitcastToAPInt())) &&
9522         (!K1->hasOneUse() ||
9523          TII->isInlineConstant(K1->getValueAPF().bitcastToAPInt()))) {
9524       return DAG.getNode(AMDGPUISD::FMED3, SL, K0->getValueType(0),
9525                          Var, SDValue(K0, 0), SDValue(K1, 0));
9526     }
9527   }
9528 
9529   return SDValue();
9530 }
9531 
9532 SDValue SITargetLowering::performMinMaxCombine(SDNode *N,
9533                                                DAGCombinerInfo &DCI) const {
9534   SelectionDAG &DAG = DCI.DAG;
9535 
9536   EVT VT = N->getValueType(0);
9537   unsigned Opc = N->getOpcode();
9538   SDValue Op0 = N->getOperand(0);
9539   SDValue Op1 = N->getOperand(1);
9540 
9541   // Only do this if the inner op has one use since this will just increases
9542   // register pressure for no benefit.
9543 
9544   if (Opc != AMDGPUISD::FMIN_LEGACY && Opc != AMDGPUISD::FMAX_LEGACY &&
9545       !VT.isVector() &&
9546       (VT == MVT::i32 || VT == MVT::f32 ||
9547        ((VT == MVT::f16 || VT == MVT::i16) && Subtarget->hasMin3Max3_16()))) {
9548     // max(max(a, b), c) -> max3(a, b, c)
9549     // min(min(a, b), c) -> min3(a, b, c)
9550     if (Op0.getOpcode() == Opc && Op0.hasOneUse()) {
9551       SDLoc DL(N);
9552       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9553                          DL,
9554                          N->getValueType(0),
9555                          Op0.getOperand(0),
9556                          Op0.getOperand(1),
9557                          Op1);
9558     }
9559 
9560     // Try commuted.
9561     // max(a, max(b, c)) -> max3(a, b, c)
9562     // min(a, min(b, c)) -> min3(a, b, c)
9563     if (Op1.getOpcode() == Opc && Op1.hasOneUse()) {
9564       SDLoc DL(N);
9565       return DAG.getNode(minMaxOpcToMin3Max3Opc(Opc),
9566                          DL,
9567                          N->getValueType(0),
9568                          Op0,
9569                          Op1.getOperand(0),
9570                          Op1.getOperand(1));
9571     }
9572   }
9573 
9574   // min(max(x, K0), K1), K0 < K1 -> med3(x, K0, K1)
9575   if (Opc == ISD::SMIN && Op0.getOpcode() == ISD::SMAX && Op0.hasOneUse()) {
9576     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, true))
9577       return Med3;
9578   }
9579 
9580   if (Opc == ISD::UMIN && Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
9581     if (SDValue Med3 = performIntMed3ImmCombine(DAG, SDLoc(N), Op0, Op1, false))
9582       return Med3;
9583   }
9584 
9585   // fminnum(fmaxnum(x, K0), K1), K0 < K1 && !is_snan(x) -> fmed3(x, K0, K1)
9586   if (((Opc == ISD::FMINNUM && Op0.getOpcode() == ISD::FMAXNUM) ||
9587        (Opc == ISD::FMINNUM_IEEE && Op0.getOpcode() == ISD::FMAXNUM_IEEE) ||
9588        (Opc == AMDGPUISD::FMIN_LEGACY &&
9589         Op0.getOpcode() == AMDGPUISD::FMAX_LEGACY)) &&
9590       (VT == MVT::f32 || VT == MVT::f64 ||
9591        (VT == MVT::f16 && Subtarget->has16BitInsts()) ||
9592        (VT == MVT::v2f16 && Subtarget->hasVOP3PInsts())) &&
9593       Op0.hasOneUse()) {
9594     if (SDValue Res = performFPMed3ImmCombine(DAG, SDLoc(N), Op0, Op1))
9595       return Res;
9596   }
9597 
9598   return SDValue();
9599 }
9600 
9601 static bool isClampZeroToOne(SDValue A, SDValue B) {
9602   if (ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A)) {
9603     if (ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B)) {
9604       // FIXME: Should this be allowing -0.0?
9605       return (CA->isExactlyValue(0.0) && CB->isExactlyValue(1.0)) ||
9606              (CA->isExactlyValue(1.0) && CB->isExactlyValue(0.0));
9607     }
9608   }
9609 
9610   return false;
9611 }
9612 
9613 // FIXME: Should only worry about snans for version with chain.
9614 SDValue SITargetLowering::performFMed3Combine(SDNode *N,
9615                                               DAGCombinerInfo &DCI) const {
9616   EVT VT = N->getValueType(0);
9617   // v_med3_f32 and v_max_f32 behave identically wrt denorms, exceptions and
9618   // NaNs. With a NaN input, the order of the operands may change the result.
9619 
9620   SelectionDAG &DAG = DCI.DAG;
9621   SDLoc SL(N);
9622 
9623   SDValue Src0 = N->getOperand(0);
9624   SDValue Src1 = N->getOperand(1);
9625   SDValue Src2 = N->getOperand(2);
9626 
9627   if (isClampZeroToOne(Src0, Src1)) {
9628     // const_a, const_b, x -> clamp is safe in all cases including signaling
9629     // nans.
9630     // FIXME: Should this be allowing -0.0?
9631     return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src2);
9632   }
9633 
9634   const MachineFunction &MF = DAG.getMachineFunction();
9635   const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
9636 
9637   // FIXME: dx10_clamp behavior assumed in instcombine. Should we really bother
9638   // handling no dx10-clamp?
9639   if (Info->getMode().DX10Clamp) {
9640     // If NaNs is clamped to 0, we are free to reorder the inputs.
9641 
9642     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9643       std::swap(Src0, Src1);
9644 
9645     if (isa<ConstantFPSDNode>(Src1) && !isa<ConstantFPSDNode>(Src2))
9646       std::swap(Src1, Src2);
9647 
9648     if (isa<ConstantFPSDNode>(Src0) && !isa<ConstantFPSDNode>(Src1))
9649       std::swap(Src0, Src1);
9650 
9651     if (isClampZeroToOne(Src1, Src2))
9652       return DAG.getNode(AMDGPUISD::CLAMP, SL, VT, Src0);
9653   }
9654 
9655   return SDValue();
9656 }
9657 
9658 SDValue SITargetLowering::performCvtPkRTZCombine(SDNode *N,
9659                                                  DAGCombinerInfo &DCI) const {
9660   SDValue Src0 = N->getOperand(0);
9661   SDValue Src1 = N->getOperand(1);
9662   if (Src0.isUndef() && Src1.isUndef())
9663     return DCI.DAG.getUNDEF(N->getValueType(0));
9664   return SDValue();
9665 }
9666 
9667 // Check if EXTRACT_VECTOR_ELT/INSERT_VECTOR_ELT (<n x e>, var-idx) should be
9668 // expanded into a set of cmp/select instructions.
9669 bool SITargetLowering::shouldExpandVectorDynExt(unsigned EltSize,
9670                                                 unsigned NumElem,
9671                                                 bool IsDivergentIdx) {
9672   if (UseDivergentRegisterIndexing)
9673     return false;
9674 
9675   unsigned VecSize = EltSize * NumElem;
9676 
9677   // Sub-dword vectors of size 2 dword or less have better implementation.
9678   if (VecSize <= 64 && EltSize < 32)
9679     return false;
9680 
9681   // Always expand the rest of sub-dword instructions, otherwise it will be
9682   // lowered via memory.
9683   if (EltSize < 32)
9684     return true;
9685 
9686   // Always do this if var-idx is divergent, otherwise it will become a loop.
9687   if (IsDivergentIdx)
9688     return true;
9689 
9690   // Large vectors would yield too many compares and v_cndmask_b32 instructions.
9691   unsigned NumInsts = NumElem /* Number of compares */ +
9692                       ((EltSize + 31) / 32) * NumElem /* Number of cndmasks */;
9693   return NumInsts <= 16;
9694 }
9695 
9696 static bool shouldExpandVectorDynExt(SDNode *N) {
9697   SDValue Idx = N->getOperand(N->getNumOperands() - 1);
9698   if (isa<ConstantSDNode>(Idx))
9699     return false;
9700 
9701   SDValue Vec = N->getOperand(0);
9702   EVT VecVT = Vec.getValueType();
9703   EVT EltVT = VecVT.getVectorElementType();
9704   unsigned EltSize = EltVT.getSizeInBits();
9705   unsigned NumElem = VecVT.getVectorNumElements();
9706 
9707   return SITargetLowering::shouldExpandVectorDynExt(EltSize, NumElem,
9708                                                     Idx->isDivergent());
9709 }
9710 
9711 SDValue SITargetLowering::performExtractVectorEltCombine(
9712   SDNode *N, DAGCombinerInfo &DCI) const {
9713   SDValue Vec = N->getOperand(0);
9714   SelectionDAG &DAG = DCI.DAG;
9715 
9716   EVT VecVT = Vec.getValueType();
9717   EVT EltVT = VecVT.getVectorElementType();
9718 
9719   if ((Vec.getOpcode() == ISD::FNEG ||
9720        Vec.getOpcode() == ISD::FABS) && allUsesHaveSourceMods(N)) {
9721     SDLoc SL(N);
9722     EVT EltVT = N->getValueType(0);
9723     SDValue Idx = N->getOperand(1);
9724     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9725                               Vec.getOperand(0), Idx);
9726     return DAG.getNode(Vec.getOpcode(), SL, EltVT, Elt);
9727   }
9728 
9729   // ScalarRes = EXTRACT_VECTOR_ELT ((vector-BINOP Vec1, Vec2), Idx)
9730   //    =>
9731   // Vec1Elt = EXTRACT_VECTOR_ELT(Vec1, Idx)
9732   // Vec2Elt = EXTRACT_VECTOR_ELT(Vec2, Idx)
9733   // ScalarRes = scalar-BINOP Vec1Elt, Vec2Elt
9734   if (Vec.hasOneUse() && DCI.isBeforeLegalize()) {
9735     SDLoc SL(N);
9736     EVT EltVT = N->getValueType(0);
9737     SDValue Idx = N->getOperand(1);
9738     unsigned Opc = Vec.getOpcode();
9739 
9740     switch(Opc) {
9741     default:
9742       break;
9743       // TODO: Support other binary operations.
9744     case ISD::FADD:
9745     case ISD::FSUB:
9746     case ISD::FMUL:
9747     case ISD::ADD:
9748     case ISD::UMIN:
9749     case ISD::UMAX:
9750     case ISD::SMIN:
9751     case ISD::SMAX:
9752     case ISD::FMAXNUM:
9753     case ISD::FMINNUM:
9754     case ISD::FMAXNUM_IEEE:
9755     case ISD::FMINNUM_IEEE: {
9756       SDValue Elt0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9757                                  Vec.getOperand(0), Idx);
9758       SDValue Elt1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
9759                                  Vec.getOperand(1), Idx);
9760 
9761       DCI.AddToWorklist(Elt0.getNode());
9762       DCI.AddToWorklist(Elt1.getNode());
9763       return DAG.getNode(Opc, SL, EltVT, Elt0, Elt1, Vec->getFlags());
9764     }
9765     }
9766   }
9767 
9768   unsigned VecSize = VecVT.getSizeInBits();
9769   unsigned EltSize = EltVT.getSizeInBits();
9770 
9771   // EXTRACT_VECTOR_ELT (<n x e>, var-idx) => n x select (e, const-idx)
9772   if (::shouldExpandVectorDynExt(N)) {
9773     SDLoc SL(N);
9774     SDValue Idx = N->getOperand(1);
9775     SDValue V;
9776     for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9777       SDValue IC = DAG.getVectorIdxConstant(I, SL);
9778       SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9779       if (I == 0)
9780         V = Elt;
9781       else
9782         V = DAG.getSelectCC(SL, Idx, IC, Elt, V, ISD::SETEQ);
9783     }
9784     return V;
9785   }
9786 
9787   if (!DCI.isBeforeLegalize())
9788     return SDValue();
9789 
9790   // Try to turn sub-dword accesses of vectors into accesses of the same 32-bit
9791   // elements. This exposes more load reduction opportunities by replacing
9792   // multiple small extract_vector_elements with a single 32-bit extract.
9793   auto *Idx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9794   if (isa<MemSDNode>(Vec) &&
9795       EltSize <= 16 &&
9796       EltVT.isByteSized() &&
9797       VecSize > 32 &&
9798       VecSize % 32 == 0 &&
9799       Idx) {
9800     EVT NewVT = getEquivalentMemType(*DAG.getContext(), VecVT);
9801 
9802     unsigned BitIndex = Idx->getZExtValue() * EltSize;
9803     unsigned EltIdx = BitIndex / 32;
9804     unsigned LeftoverBitIdx = BitIndex % 32;
9805     SDLoc SL(N);
9806 
9807     SDValue Cast = DAG.getNode(ISD::BITCAST, SL, NewVT, Vec);
9808     DCI.AddToWorklist(Cast.getNode());
9809 
9810     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, MVT::i32, Cast,
9811                               DAG.getConstant(EltIdx, SL, MVT::i32));
9812     DCI.AddToWorklist(Elt.getNode());
9813     SDValue Srl = DAG.getNode(ISD::SRL, SL, MVT::i32, Elt,
9814                               DAG.getConstant(LeftoverBitIdx, SL, MVT::i32));
9815     DCI.AddToWorklist(Srl.getNode());
9816 
9817     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, EltVT.changeTypeToInteger(), Srl);
9818     DCI.AddToWorklist(Trunc.getNode());
9819     return DAG.getNode(ISD::BITCAST, SL, EltVT, Trunc);
9820   }
9821 
9822   return SDValue();
9823 }
9824 
9825 SDValue
9826 SITargetLowering::performInsertVectorEltCombine(SDNode *N,
9827                                                 DAGCombinerInfo &DCI) const {
9828   SDValue Vec = N->getOperand(0);
9829   SDValue Idx = N->getOperand(2);
9830   EVT VecVT = Vec.getValueType();
9831   EVT EltVT = VecVT.getVectorElementType();
9832 
9833   // INSERT_VECTOR_ELT (<n x e>, var-idx)
9834   // => BUILD_VECTOR n x select (e, const-idx)
9835   if (!::shouldExpandVectorDynExt(N))
9836     return SDValue();
9837 
9838   SelectionDAG &DAG = DCI.DAG;
9839   SDLoc SL(N);
9840   SDValue Ins = N->getOperand(1);
9841   EVT IdxVT = Idx.getValueType();
9842 
9843   SmallVector<SDValue, 16> Ops;
9844   for (unsigned I = 0, E = VecVT.getVectorNumElements(); I < E; ++I) {
9845     SDValue IC = DAG.getConstant(I, SL, IdxVT);
9846     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT, Vec, IC);
9847     SDValue V = DAG.getSelectCC(SL, Idx, IC, Ins, Elt, ISD::SETEQ);
9848     Ops.push_back(V);
9849   }
9850 
9851   return DAG.getBuildVector(VecVT, SL, Ops);
9852 }
9853 
9854 unsigned SITargetLowering::getFusedOpcode(const SelectionDAG &DAG,
9855                                           const SDNode *N0,
9856                                           const SDNode *N1) const {
9857   EVT VT = N0->getValueType(0);
9858 
9859   // Only do this if we are not trying to support denormals. v_mad_f32 does not
9860   // support denormals ever.
9861   if (((VT == MVT::f32 && !hasFP32Denormals(DAG.getMachineFunction())) ||
9862        (VT == MVT::f16 && !hasFP64FP16Denormals(DAG.getMachineFunction()) &&
9863         getSubtarget()->hasMadF16())) &&
9864        isOperationLegal(ISD::FMAD, VT))
9865     return ISD::FMAD;
9866 
9867   const TargetOptions &Options = DAG.getTarget().Options;
9868   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
9869        (N0->getFlags().hasAllowContract() &&
9870         N1->getFlags().hasAllowContract())) &&
9871       isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT)) {
9872     return ISD::FMA;
9873   }
9874 
9875   return 0;
9876 }
9877 
9878 // For a reassociatable opcode perform:
9879 // op x, (op y, z) -> op (op x, z), y, if x and z are uniform
9880 SDValue SITargetLowering::reassociateScalarOps(SDNode *N,
9881                                                SelectionDAG &DAG) const {
9882   EVT VT = N->getValueType(0);
9883   if (VT != MVT::i32 && VT != MVT::i64)
9884     return SDValue();
9885 
9886   unsigned Opc = N->getOpcode();
9887   SDValue Op0 = N->getOperand(0);
9888   SDValue Op1 = N->getOperand(1);
9889 
9890   if (!(Op0->isDivergent() ^ Op1->isDivergent()))
9891     return SDValue();
9892 
9893   if (Op0->isDivergent())
9894     std::swap(Op0, Op1);
9895 
9896   if (Op1.getOpcode() != Opc || !Op1.hasOneUse())
9897     return SDValue();
9898 
9899   SDValue Op2 = Op1.getOperand(1);
9900   Op1 = Op1.getOperand(0);
9901   if (!(Op1->isDivergent() ^ Op2->isDivergent()))
9902     return SDValue();
9903 
9904   if (Op1->isDivergent())
9905     std::swap(Op1, Op2);
9906 
9907   // If either operand is constant this will conflict with
9908   // DAGCombiner::ReassociateOps().
9909   if (DAG.isConstantIntBuildVectorOrConstantInt(Op0) ||
9910       DAG.isConstantIntBuildVectorOrConstantInt(Op1))
9911     return SDValue();
9912 
9913   SDLoc SL(N);
9914   SDValue Add1 = DAG.getNode(Opc, SL, VT, Op0, Op1);
9915   return DAG.getNode(Opc, SL, VT, Add1, Op2);
9916 }
9917 
9918 static SDValue getMad64_32(SelectionDAG &DAG, const SDLoc &SL,
9919                            EVT VT,
9920                            SDValue N0, SDValue N1, SDValue N2,
9921                            bool Signed) {
9922   unsigned MadOpc = Signed ? AMDGPUISD::MAD_I64_I32 : AMDGPUISD::MAD_U64_U32;
9923   SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i1);
9924   SDValue Mad = DAG.getNode(MadOpc, SL, VTs, N0, N1, N2);
9925   return DAG.getNode(ISD::TRUNCATE, SL, VT, Mad);
9926 }
9927 
9928 SDValue SITargetLowering::performAddCombine(SDNode *N,
9929                                             DAGCombinerInfo &DCI) const {
9930   SelectionDAG &DAG = DCI.DAG;
9931   EVT VT = N->getValueType(0);
9932   SDLoc SL(N);
9933   SDValue LHS = N->getOperand(0);
9934   SDValue RHS = N->getOperand(1);
9935 
9936   if ((LHS.getOpcode() == ISD::MUL || RHS.getOpcode() == ISD::MUL)
9937       && Subtarget->hasMad64_32() &&
9938       !VT.isVector() && VT.getScalarSizeInBits() > 32 &&
9939       VT.getScalarSizeInBits() <= 64) {
9940     if (LHS.getOpcode() != ISD::MUL)
9941       std::swap(LHS, RHS);
9942 
9943     SDValue MulLHS = LHS.getOperand(0);
9944     SDValue MulRHS = LHS.getOperand(1);
9945     SDValue AddRHS = RHS;
9946 
9947     // TODO: Maybe restrict if SGPR inputs.
9948     if (numBitsUnsigned(MulLHS, DAG) <= 32 &&
9949         numBitsUnsigned(MulRHS, DAG) <= 32) {
9950       MulLHS = DAG.getZExtOrTrunc(MulLHS, SL, MVT::i32);
9951       MulRHS = DAG.getZExtOrTrunc(MulRHS, SL, MVT::i32);
9952       AddRHS = DAG.getZExtOrTrunc(AddRHS, SL, MVT::i64);
9953       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, false);
9954     }
9955 
9956     if (numBitsSigned(MulLHS, DAG) < 32 && numBitsSigned(MulRHS, DAG) < 32) {
9957       MulLHS = DAG.getSExtOrTrunc(MulLHS, SL, MVT::i32);
9958       MulRHS = DAG.getSExtOrTrunc(MulRHS, SL, MVT::i32);
9959       AddRHS = DAG.getSExtOrTrunc(AddRHS, SL, MVT::i64);
9960       return getMad64_32(DAG, SL, VT, MulLHS, MulRHS, AddRHS, true);
9961     }
9962 
9963     return SDValue();
9964   }
9965 
9966   if (SDValue V = reassociateScalarOps(N, DAG)) {
9967     return V;
9968   }
9969 
9970   if (VT != MVT::i32 || !DCI.isAfterLegalizeDAG())
9971     return SDValue();
9972 
9973   // add x, zext (setcc) => addcarry x, 0, setcc
9974   // add x, sext (setcc) => subcarry x, 0, setcc
9975   unsigned Opc = LHS.getOpcode();
9976   if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND ||
9977       Opc == ISD::ANY_EXTEND || Opc == ISD::ADDCARRY)
9978     std::swap(RHS, LHS);
9979 
9980   Opc = RHS.getOpcode();
9981   switch (Opc) {
9982   default: break;
9983   case ISD::ZERO_EXTEND:
9984   case ISD::SIGN_EXTEND:
9985   case ISD::ANY_EXTEND: {
9986     auto Cond = RHS.getOperand(0);
9987     // If this won't be a real VOPC output, we would still need to insert an
9988     // extra instruction anyway.
9989     if (!isBoolSGPR(Cond))
9990       break;
9991     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
9992     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
9993     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::SUBCARRY : ISD::ADDCARRY;
9994     return DAG.getNode(Opc, SL, VTList, Args);
9995   }
9996   case ISD::ADDCARRY: {
9997     // add x, (addcarry y, 0, cc) => addcarry x, y, cc
9998     auto C = dyn_cast<ConstantSDNode>(RHS.getOperand(1));
9999     if (!C || C->getZExtValue() != 0) break;
10000     SDValue Args[] = { LHS, RHS.getOperand(0), RHS.getOperand(2) };
10001     return DAG.getNode(ISD::ADDCARRY, SDLoc(N), RHS->getVTList(), Args);
10002   }
10003   }
10004   return SDValue();
10005 }
10006 
10007 SDValue SITargetLowering::performSubCombine(SDNode *N,
10008                                             DAGCombinerInfo &DCI) const {
10009   SelectionDAG &DAG = DCI.DAG;
10010   EVT VT = N->getValueType(0);
10011 
10012   if (VT != MVT::i32)
10013     return SDValue();
10014 
10015   SDLoc SL(N);
10016   SDValue LHS = N->getOperand(0);
10017   SDValue RHS = N->getOperand(1);
10018 
10019   // sub x, zext (setcc) => subcarry x, 0, setcc
10020   // sub x, sext (setcc) => addcarry x, 0, setcc
10021   unsigned Opc = RHS.getOpcode();
10022   switch (Opc) {
10023   default: break;
10024   case ISD::ZERO_EXTEND:
10025   case ISD::SIGN_EXTEND:
10026   case ISD::ANY_EXTEND: {
10027     auto Cond = RHS.getOperand(0);
10028     // If this won't be a real VOPC output, we would still need to insert an
10029     // extra instruction anyway.
10030     if (!isBoolSGPR(Cond))
10031       break;
10032     SDVTList VTList = DAG.getVTList(MVT::i32, MVT::i1);
10033     SDValue Args[] = { LHS, DAG.getConstant(0, SL, MVT::i32), Cond };
10034     Opc = (Opc == ISD::SIGN_EXTEND) ? ISD::ADDCARRY : ISD::SUBCARRY;
10035     return DAG.getNode(Opc, SL, VTList, Args);
10036   }
10037   }
10038 
10039   if (LHS.getOpcode() == ISD::SUBCARRY) {
10040     // sub (subcarry x, 0, cc), y => subcarry x, y, cc
10041     auto C = dyn_cast<ConstantSDNode>(LHS.getOperand(1));
10042     if (!C || !C->isNullValue())
10043       return SDValue();
10044     SDValue Args[] = { LHS.getOperand(0), RHS, LHS.getOperand(2) };
10045     return DAG.getNode(ISD::SUBCARRY, SDLoc(N), LHS->getVTList(), Args);
10046   }
10047   return SDValue();
10048 }
10049 
10050 SDValue SITargetLowering::performAddCarrySubCarryCombine(SDNode *N,
10051   DAGCombinerInfo &DCI) const {
10052 
10053   if (N->getValueType(0) != MVT::i32)
10054     return SDValue();
10055 
10056   auto C = dyn_cast<ConstantSDNode>(N->getOperand(1));
10057   if (!C || C->getZExtValue() != 0)
10058     return SDValue();
10059 
10060   SelectionDAG &DAG = DCI.DAG;
10061   SDValue LHS = N->getOperand(0);
10062 
10063   // addcarry (add x, y), 0, cc => addcarry x, y, cc
10064   // subcarry (sub x, y), 0, cc => subcarry x, y, cc
10065   unsigned LHSOpc = LHS.getOpcode();
10066   unsigned Opc = N->getOpcode();
10067   if ((LHSOpc == ISD::ADD && Opc == ISD::ADDCARRY) ||
10068       (LHSOpc == ISD::SUB && Opc == ISD::SUBCARRY)) {
10069     SDValue Args[] = { LHS.getOperand(0), LHS.getOperand(1), N->getOperand(2) };
10070     return DAG.getNode(Opc, SDLoc(N), N->getVTList(), Args);
10071   }
10072   return SDValue();
10073 }
10074 
10075 SDValue SITargetLowering::performFAddCombine(SDNode *N,
10076                                              DAGCombinerInfo &DCI) const {
10077   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10078     return SDValue();
10079 
10080   SelectionDAG &DAG = DCI.DAG;
10081   EVT VT = N->getValueType(0);
10082 
10083   SDLoc SL(N);
10084   SDValue LHS = N->getOperand(0);
10085   SDValue RHS = N->getOperand(1);
10086 
10087   // These should really be instruction patterns, but writing patterns with
10088   // source modiifiers is a pain.
10089 
10090   // fadd (fadd (a, a), b) -> mad 2.0, a, b
10091   if (LHS.getOpcode() == ISD::FADD) {
10092     SDValue A = LHS.getOperand(0);
10093     if (A == LHS.getOperand(1)) {
10094       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10095       if (FusedOp != 0) {
10096         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10097         return DAG.getNode(FusedOp, SL, VT, A, Two, RHS);
10098       }
10099     }
10100   }
10101 
10102   // fadd (b, fadd (a, a)) -> mad 2.0, a, b
10103   if (RHS.getOpcode() == ISD::FADD) {
10104     SDValue A = RHS.getOperand(0);
10105     if (A == RHS.getOperand(1)) {
10106       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10107       if (FusedOp != 0) {
10108         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10109         return DAG.getNode(FusedOp, SL, VT, A, Two, LHS);
10110       }
10111     }
10112   }
10113 
10114   return SDValue();
10115 }
10116 
10117 SDValue SITargetLowering::performFSubCombine(SDNode *N,
10118                                              DAGCombinerInfo &DCI) const {
10119   if (DCI.getDAGCombineLevel() < AfterLegalizeDAG)
10120     return SDValue();
10121 
10122   SelectionDAG &DAG = DCI.DAG;
10123   SDLoc SL(N);
10124   EVT VT = N->getValueType(0);
10125   assert(!VT.isVector());
10126 
10127   // Try to get the fneg to fold into the source modifier. This undoes generic
10128   // DAG combines and folds them into the mad.
10129   //
10130   // Only do this if we are not trying to support denormals. v_mad_f32 does
10131   // not support denormals ever.
10132   SDValue LHS = N->getOperand(0);
10133   SDValue RHS = N->getOperand(1);
10134   if (LHS.getOpcode() == ISD::FADD) {
10135     // (fsub (fadd a, a), c) -> mad 2.0, a, (fneg c)
10136     SDValue A = LHS.getOperand(0);
10137     if (A == LHS.getOperand(1)) {
10138       unsigned FusedOp = getFusedOpcode(DAG, N, LHS.getNode());
10139       if (FusedOp != 0){
10140         const SDValue Two = DAG.getConstantFP(2.0, SL, VT);
10141         SDValue NegRHS = DAG.getNode(ISD::FNEG, SL, VT, RHS);
10142 
10143         return DAG.getNode(FusedOp, SL, VT, A, Two, NegRHS);
10144       }
10145     }
10146   }
10147 
10148   if (RHS.getOpcode() == ISD::FADD) {
10149     // (fsub c, (fadd a, a)) -> mad -2.0, a, c
10150 
10151     SDValue A = RHS.getOperand(0);
10152     if (A == RHS.getOperand(1)) {
10153       unsigned FusedOp = getFusedOpcode(DAG, N, RHS.getNode());
10154       if (FusedOp != 0){
10155         const SDValue NegTwo = DAG.getConstantFP(-2.0, SL, VT);
10156         return DAG.getNode(FusedOp, SL, VT, A, NegTwo, LHS);
10157       }
10158     }
10159   }
10160 
10161   return SDValue();
10162 }
10163 
10164 SDValue SITargetLowering::performFMACombine(SDNode *N,
10165                                             DAGCombinerInfo &DCI) const {
10166   SelectionDAG &DAG = DCI.DAG;
10167   EVT VT = N->getValueType(0);
10168   SDLoc SL(N);
10169 
10170   if (!Subtarget->hasDot2Insts() || VT != MVT::f32)
10171     return SDValue();
10172 
10173   // FMA((F32)S0.x, (F32)S1. x, FMA((F32)S0.y, (F32)S1.y, (F32)z)) ->
10174   //   FDOT2((V2F16)S0, (V2F16)S1, (F32)z))
10175   SDValue Op1 = N->getOperand(0);
10176   SDValue Op2 = N->getOperand(1);
10177   SDValue FMA = N->getOperand(2);
10178 
10179   if (FMA.getOpcode() != ISD::FMA ||
10180       Op1.getOpcode() != ISD::FP_EXTEND ||
10181       Op2.getOpcode() != ISD::FP_EXTEND)
10182     return SDValue();
10183 
10184   // fdot2_f32_f16 always flushes fp32 denormal operand and output to zero,
10185   // regardless of the denorm mode setting. Therefore, unsafe-fp-math/fp-contract
10186   // is sufficient to allow generaing fdot2.
10187   const TargetOptions &Options = DAG.getTarget().Options;
10188   if (Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
10189       (N->getFlags().hasAllowContract() &&
10190        FMA->getFlags().hasAllowContract())) {
10191     Op1 = Op1.getOperand(0);
10192     Op2 = Op2.getOperand(0);
10193     if (Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10194         Op2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10195       return SDValue();
10196 
10197     SDValue Vec1 = Op1.getOperand(0);
10198     SDValue Idx1 = Op1.getOperand(1);
10199     SDValue Vec2 = Op2.getOperand(0);
10200 
10201     SDValue FMAOp1 = FMA.getOperand(0);
10202     SDValue FMAOp2 = FMA.getOperand(1);
10203     SDValue FMAAcc = FMA.getOperand(2);
10204 
10205     if (FMAOp1.getOpcode() != ISD::FP_EXTEND ||
10206         FMAOp2.getOpcode() != ISD::FP_EXTEND)
10207       return SDValue();
10208 
10209     FMAOp1 = FMAOp1.getOperand(0);
10210     FMAOp2 = FMAOp2.getOperand(0);
10211     if (FMAOp1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10212         FMAOp2.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
10213       return SDValue();
10214 
10215     SDValue Vec3 = FMAOp1.getOperand(0);
10216     SDValue Vec4 = FMAOp2.getOperand(0);
10217     SDValue Idx2 = FMAOp1.getOperand(1);
10218 
10219     if (Idx1 != Op2.getOperand(1) || Idx2 != FMAOp2.getOperand(1) ||
10220         // Idx1 and Idx2 cannot be the same.
10221         Idx1 == Idx2)
10222       return SDValue();
10223 
10224     if (Vec1 == Vec2 || Vec3 == Vec4)
10225       return SDValue();
10226 
10227     if (Vec1.getValueType() != MVT::v2f16 || Vec2.getValueType() != MVT::v2f16)
10228       return SDValue();
10229 
10230     if ((Vec1 == Vec3 && Vec2 == Vec4) ||
10231         (Vec1 == Vec4 && Vec2 == Vec3)) {
10232       return DAG.getNode(AMDGPUISD::FDOT2, SL, MVT::f32, Vec1, Vec2, FMAAcc,
10233                          DAG.getTargetConstant(0, SL, MVT::i1));
10234     }
10235   }
10236   return SDValue();
10237 }
10238 
10239 SDValue SITargetLowering::performSetCCCombine(SDNode *N,
10240                                               DAGCombinerInfo &DCI) const {
10241   SelectionDAG &DAG = DCI.DAG;
10242   SDLoc SL(N);
10243 
10244   SDValue LHS = N->getOperand(0);
10245   SDValue RHS = N->getOperand(1);
10246   EVT VT = LHS.getValueType();
10247   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
10248 
10249   auto CRHS = dyn_cast<ConstantSDNode>(RHS);
10250   if (!CRHS) {
10251     CRHS = dyn_cast<ConstantSDNode>(LHS);
10252     if (CRHS) {
10253       std::swap(LHS, RHS);
10254       CC = getSetCCSwappedOperands(CC);
10255     }
10256   }
10257 
10258   if (CRHS) {
10259     if (VT == MVT::i32 && LHS.getOpcode() == ISD::SIGN_EXTEND &&
10260         isBoolSGPR(LHS.getOperand(0))) {
10261       // setcc (sext from i1 cc), -1, ne|sgt|ult) => not cc => xor cc, -1
10262       // setcc (sext from i1 cc), -1, eq|sle|uge) => cc
10263       // setcc (sext from i1 cc),  0, eq|sge|ule) => not cc => xor cc, -1
10264       // setcc (sext from i1 cc),  0, ne|ugt|slt) => cc
10265       if ((CRHS->isAllOnesValue() &&
10266            (CC == ISD::SETNE || CC == ISD::SETGT || CC == ISD::SETULT)) ||
10267           (CRHS->isNullValue() &&
10268            (CC == ISD::SETEQ || CC == ISD::SETGE || CC == ISD::SETULE)))
10269         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10270                            DAG.getConstant(-1, SL, MVT::i1));
10271       if ((CRHS->isAllOnesValue() &&
10272            (CC == ISD::SETEQ || CC == ISD::SETLE || CC == ISD::SETUGE)) ||
10273           (CRHS->isNullValue() &&
10274            (CC == ISD::SETNE || CC == ISD::SETUGT || CC == ISD::SETLT)))
10275         return LHS.getOperand(0);
10276     }
10277 
10278     uint64_t CRHSVal = CRHS->getZExtValue();
10279     if ((CC == ISD::SETEQ || CC == ISD::SETNE) &&
10280         LHS.getOpcode() == ISD::SELECT &&
10281         isa<ConstantSDNode>(LHS.getOperand(1)) &&
10282         isa<ConstantSDNode>(LHS.getOperand(2)) &&
10283         LHS.getConstantOperandVal(1) != LHS.getConstantOperandVal(2) &&
10284         isBoolSGPR(LHS.getOperand(0))) {
10285       // Given CT != FT:
10286       // setcc (select cc, CT, CF), CF, eq => xor cc, -1
10287       // setcc (select cc, CT, CF), CF, ne => cc
10288       // setcc (select cc, CT, CF), CT, ne => xor cc, -1
10289       // setcc (select cc, CT, CF), CT, eq => cc
10290       uint64_t CT = LHS.getConstantOperandVal(1);
10291       uint64_t CF = LHS.getConstantOperandVal(2);
10292 
10293       if ((CF == CRHSVal && CC == ISD::SETEQ) ||
10294           (CT == CRHSVal && CC == ISD::SETNE))
10295         return DAG.getNode(ISD::XOR, SL, MVT::i1, LHS.getOperand(0),
10296                            DAG.getConstant(-1, SL, MVT::i1));
10297       if ((CF == CRHSVal && CC == ISD::SETNE) ||
10298           (CT == CRHSVal && CC == ISD::SETEQ))
10299         return LHS.getOperand(0);
10300     }
10301   }
10302 
10303   if (VT != MVT::f32 && VT != MVT::f64 && (Subtarget->has16BitInsts() &&
10304                                            VT != MVT::f16))
10305     return SDValue();
10306 
10307   // Match isinf/isfinite pattern
10308   // (fcmp oeq (fabs x), inf) -> (fp_class x, (p_infinity | n_infinity))
10309   // (fcmp one (fabs x), inf) -> (fp_class x,
10310   // (p_normal | n_normal | p_subnormal | n_subnormal | p_zero | n_zero)
10311   if ((CC == ISD::SETOEQ || CC == ISD::SETONE) && LHS.getOpcode() == ISD::FABS) {
10312     const ConstantFPSDNode *CRHS = dyn_cast<ConstantFPSDNode>(RHS);
10313     if (!CRHS)
10314       return SDValue();
10315 
10316     const APFloat &APF = CRHS->getValueAPF();
10317     if (APF.isInfinity() && !APF.isNegative()) {
10318       const unsigned IsInfMask = SIInstrFlags::P_INFINITY |
10319                                  SIInstrFlags::N_INFINITY;
10320       const unsigned IsFiniteMask = SIInstrFlags::N_ZERO |
10321                                     SIInstrFlags::P_ZERO |
10322                                     SIInstrFlags::N_NORMAL |
10323                                     SIInstrFlags::P_NORMAL |
10324                                     SIInstrFlags::N_SUBNORMAL |
10325                                     SIInstrFlags::P_SUBNORMAL;
10326       unsigned Mask = CC == ISD::SETOEQ ? IsInfMask : IsFiniteMask;
10327       return DAG.getNode(AMDGPUISD::FP_CLASS, SL, MVT::i1, LHS.getOperand(0),
10328                          DAG.getConstant(Mask, SL, MVT::i32));
10329     }
10330   }
10331 
10332   return SDValue();
10333 }
10334 
10335 SDValue SITargetLowering::performCvtF32UByteNCombine(SDNode *N,
10336                                                      DAGCombinerInfo &DCI) const {
10337   SelectionDAG &DAG = DCI.DAG;
10338   SDLoc SL(N);
10339   unsigned Offset = N->getOpcode() - AMDGPUISD::CVT_F32_UBYTE0;
10340 
10341   SDValue Src = N->getOperand(0);
10342   SDValue Shift = N->getOperand(0);
10343 
10344   // TODO: Extend type shouldn't matter (assuming legal types).
10345   if (Shift.getOpcode() == ISD::ZERO_EXTEND)
10346     Shift = Shift.getOperand(0);
10347 
10348   if (Shift.getOpcode() == ISD::SRL || Shift.getOpcode() == ISD::SHL) {
10349     // cvt_f32_ubyte1 (shl x,  8) -> cvt_f32_ubyte0 x
10350     // cvt_f32_ubyte3 (shl x, 16) -> cvt_f32_ubyte1 x
10351     // cvt_f32_ubyte0 (srl x, 16) -> cvt_f32_ubyte2 x
10352     // cvt_f32_ubyte1 (srl x, 16) -> cvt_f32_ubyte3 x
10353     // cvt_f32_ubyte0 (srl x,  8) -> cvt_f32_ubyte1 x
10354     if (auto *C = dyn_cast<ConstantSDNode>(Shift.getOperand(1))) {
10355       Shift = DAG.getZExtOrTrunc(Shift.getOperand(0),
10356                                  SDLoc(Shift.getOperand(0)), MVT::i32);
10357 
10358       unsigned ShiftOffset = 8 * Offset;
10359       if (Shift.getOpcode() == ISD::SHL)
10360         ShiftOffset -= C->getZExtValue();
10361       else
10362         ShiftOffset += C->getZExtValue();
10363 
10364       if (ShiftOffset < 32 && (ShiftOffset % 8) == 0) {
10365         return DAG.getNode(AMDGPUISD::CVT_F32_UBYTE0 + ShiftOffset / 8, SL,
10366                            MVT::f32, Shift);
10367       }
10368     }
10369   }
10370 
10371   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
10372   APInt DemandedBits = APInt::getBitsSet(32, 8 * Offset, 8 * Offset + 8);
10373   if (TLI.SimplifyDemandedBits(Src, DemandedBits, DCI)) {
10374     // We simplified Src. If this node is not dead, visit it again so it is
10375     // folded properly.
10376     if (N->getOpcode() != ISD::DELETED_NODE)
10377       DCI.AddToWorklist(N);
10378     return SDValue(N, 0);
10379   }
10380 
10381   // Handle (or x, (srl y, 8)) pattern when known bits are zero.
10382   if (SDValue DemandedSrc =
10383           TLI.SimplifyMultipleUseDemandedBits(Src, DemandedBits, DAG))
10384     return DAG.getNode(N->getOpcode(), SL, MVT::f32, DemandedSrc);
10385 
10386   return SDValue();
10387 }
10388 
10389 SDValue SITargetLowering::performClampCombine(SDNode *N,
10390                                               DAGCombinerInfo &DCI) const {
10391   ConstantFPSDNode *CSrc = dyn_cast<ConstantFPSDNode>(N->getOperand(0));
10392   if (!CSrc)
10393     return SDValue();
10394 
10395   const MachineFunction &MF = DCI.DAG.getMachineFunction();
10396   const APFloat &F = CSrc->getValueAPF();
10397   APFloat Zero = APFloat::getZero(F.getSemantics());
10398   if (F < Zero ||
10399       (F.isNaN() && MF.getInfo<SIMachineFunctionInfo>()->getMode().DX10Clamp)) {
10400     return DCI.DAG.getConstantFP(Zero, SDLoc(N), N->getValueType(0));
10401   }
10402 
10403   APFloat One(F.getSemantics(), "1.0");
10404   if (F > One)
10405     return DCI.DAG.getConstantFP(One, SDLoc(N), N->getValueType(0));
10406 
10407   return SDValue(CSrc, 0);
10408 }
10409 
10410 
10411 SDValue SITargetLowering::PerformDAGCombine(SDNode *N,
10412                                             DAGCombinerInfo &DCI) const {
10413   if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
10414     return SDValue();
10415   switch (N->getOpcode()) {
10416   default:
10417     return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10418   case ISD::ADD:
10419     return performAddCombine(N, DCI);
10420   case ISD::SUB:
10421     return performSubCombine(N, DCI);
10422   case ISD::ADDCARRY:
10423   case ISD::SUBCARRY:
10424     return performAddCarrySubCarryCombine(N, DCI);
10425   case ISD::FADD:
10426     return performFAddCombine(N, DCI);
10427   case ISD::FSUB:
10428     return performFSubCombine(N, DCI);
10429   case ISD::SETCC:
10430     return performSetCCCombine(N, DCI);
10431   case ISD::FMAXNUM:
10432   case ISD::FMINNUM:
10433   case ISD::FMAXNUM_IEEE:
10434   case ISD::FMINNUM_IEEE:
10435   case ISD::SMAX:
10436   case ISD::SMIN:
10437   case ISD::UMAX:
10438   case ISD::UMIN:
10439   case AMDGPUISD::FMIN_LEGACY:
10440   case AMDGPUISD::FMAX_LEGACY:
10441     return performMinMaxCombine(N, DCI);
10442   case ISD::FMA:
10443     return performFMACombine(N, DCI);
10444   case ISD::LOAD: {
10445     if (SDValue Widended = widenLoad(cast<LoadSDNode>(N), DCI))
10446       return Widended;
10447     LLVM_FALLTHROUGH;
10448   }
10449   case ISD::STORE:
10450   case ISD::ATOMIC_LOAD:
10451   case ISD::ATOMIC_STORE:
10452   case ISD::ATOMIC_CMP_SWAP:
10453   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
10454   case ISD::ATOMIC_SWAP:
10455   case ISD::ATOMIC_LOAD_ADD:
10456   case ISD::ATOMIC_LOAD_SUB:
10457   case ISD::ATOMIC_LOAD_AND:
10458   case ISD::ATOMIC_LOAD_OR:
10459   case ISD::ATOMIC_LOAD_XOR:
10460   case ISD::ATOMIC_LOAD_NAND:
10461   case ISD::ATOMIC_LOAD_MIN:
10462   case ISD::ATOMIC_LOAD_MAX:
10463   case ISD::ATOMIC_LOAD_UMIN:
10464   case ISD::ATOMIC_LOAD_UMAX:
10465   case ISD::ATOMIC_LOAD_FADD:
10466   case AMDGPUISD::ATOMIC_INC:
10467   case AMDGPUISD::ATOMIC_DEC:
10468   case AMDGPUISD::ATOMIC_LOAD_FMIN:
10469   case AMDGPUISD::ATOMIC_LOAD_FMAX: // TODO: Target mem intrinsics.
10470     if (DCI.isBeforeLegalize())
10471       break;
10472     return performMemSDNodeCombine(cast<MemSDNode>(N), DCI);
10473   case ISD::AND:
10474     return performAndCombine(N, DCI);
10475   case ISD::OR:
10476     return performOrCombine(N, DCI);
10477   case ISD::XOR:
10478     return performXorCombine(N, DCI);
10479   case ISD::ZERO_EXTEND:
10480     return performZeroExtendCombine(N, DCI);
10481   case ISD::SIGN_EXTEND_INREG:
10482     return performSignExtendInRegCombine(N , DCI);
10483   case AMDGPUISD::FP_CLASS:
10484     return performClassCombine(N, DCI);
10485   case ISD::FCANONICALIZE:
10486     return performFCanonicalizeCombine(N, DCI);
10487   case AMDGPUISD::RCP:
10488     return performRcpCombine(N, DCI);
10489   case AMDGPUISD::FRACT:
10490   case AMDGPUISD::RSQ:
10491   case AMDGPUISD::RCP_LEGACY:
10492   case AMDGPUISD::RCP_IFLAG:
10493   case AMDGPUISD::RSQ_CLAMP:
10494   case AMDGPUISD::LDEXP: {
10495     // FIXME: This is probably wrong. If src is an sNaN, it won't be quieted
10496     SDValue Src = N->getOperand(0);
10497     if (Src.isUndef())
10498       return Src;
10499     break;
10500   }
10501   case ISD::SINT_TO_FP:
10502   case ISD::UINT_TO_FP:
10503     return performUCharToFloatCombine(N, DCI);
10504   case AMDGPUISD::CVT_F32_UBYTE0:
10505   case AMDGPUISD::CVT_F32_UBYTE1:
10506   case AMDGPUISD::CVT_F32_UBYTE2:
10507   case AMDGPUISD::CVT_F32_UBYTE3:
10508     return performCvtF32UByteNCombine(N, DCI);
10509   case AMDGPUISD::FMED3:
10510     return performFMed3Combine(N, DCI);
10511   case AMDGPUISD::CVT_PKRTZ_F16_F32:
10512     return performCvtPkRTZCombine(N, DCI);
10513   case AMDGPUISD::CLAMP:
10514     return performClampCombine(N, DCI);
10515   case ISD::SCALAR_TO_VECTOR: {
10516     SelectionDAG &DAG = DCI.DAG;
10517     EVT VT = N->getValueType(0);
10518 
10519     // v2i16 (scalar_to_vector i16:x) -> v2i16 (bitcast (any_extend i16:x))
10520     if (VT == MVT::v2i16 || VT == MVT::v2f16) {
10521       SDLoc SL(N);
10522       SDValue Src = N->getOperand(0);
10523       EVT EltVT = Src.getValueType();
10524       if (EltVT == MVT::f16)
10525         Src = DAG.getNode(ISD::BITCAST, SL, MVT::i16, Src);
10526 
10527       SDValue Ext = DAG.getNode(ISD::ANY_EXTEND, SL, MVT::i32, Src);
10528       return DAG.getNode(ISD::BITCAST, SL, VT, Ext);
10529     }
10530 
10531     break;
10532   }
10533   case ISD::EXTRACT_VECTOR_ELT:
10534     return performExtractVectorEltCombine(N, DCI);
10535   case ISD::INSERT_VECTOR_ELT:
10536     return performInsertVectorEltCombine(N, DCI);
10537   }
10538   return AMDGPUTargetLowering::PerformDAGCombine(N, DCI);
10539 }
10540 
10541 /// Helper function for adjustWritemask
10542 static unsigned SubIdx2Lane(unsigned Idx) {
10543   switch (Idx) {
10544   default: return 0;
10545   case AMDGPU::sub0: return 0;
10546   case AMDGPU::sub1: return 1;
10547   case AMDGPU::sub2: return 2;
10548   case AMDGPU::sub3: return 3;
10549   case AMDGPU::sub4: return 4; // Possible with TFE/LWE
10550   }
10551 }
10552 
10553 /// Adjust the writemask of MIMG instructions
10554 SDNode *SITargetLowering::adjustWritemask(MachineSDNode *&Node,
10555                                           SelectionDAG &DAG) const {
10556   unsigned Opcode = Node->getMachineOpcode();
10557 
10558   // Subtract 1 because the vdata output is not a MachineSDNode operand.
10559   int D16Idx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::d16) - 1;
10560   if (D16Idx >= 0 && Node->getConstantOperandVal(D16Idx))
10561     return Node; // not implemented for D16
10562 
10563   SDNode *Users[5] = { nullptr };
10564   unsigned Lane = 0;
10565   unsigned DmaskIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::dmask) - 1;
10566   unsigned OldDmask = Node->getConstantOperandVal(DmaskIdx);
10567   unsigned NewDmask = 0;
10568   unsigned TFEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::tfe) - 1;
10569   unsigned LWEIdx = AMDGPU::getNamedOperandIdx(Opcode, AMDGPU::OpName::lwe) - 1;
10570   bool UsesTFC = (Node->getConstantOperandVal(TFEIdx) ||
10571                   Node->getConstantOperandVal(LWEIdx)) ? 1 : 0;
10572   unsigned TFCLane = 0;
10573   bool HasChain = Node->getNumValues() > 1;
10574 
10575   if (OldDmask == 0) {
10576     // These are folded out, but on the chance it happens don't assert.
10577     return Node;
10578   }
10579 
10580   unsigned OldBitsSet = countPopulation(OldDmask);
10581   // Work out which is the TFE/LWE lane if that is enabled.
10582   if (UsesTFC) {
10583     TFCLane = OldBitsSet;
10584   }
10585 
10586   // Try to figure out the used register components
10587   for (SDNode::use_iterator I = Node->use_begin(), E = Node->use_end();
10588        I != E; ++I) {
10589 
10590     // Don't look at users of the chain.
10591     if (I.getUse().getResNo() != 0)
10592       continue;
10593 
10594     // Abort if we can't understand the usage
10595     if (!I->isMachineOpcode() ||
10596         I->getMachineOpcode() != TargetOpcode::EXTRACT_SUBREG)
10597       return Node;
10598 
10599     // Lane means which subreg of %vgpra_vgprb_vgprc_vgprd is used.
10600     // Note that subregs are packed, i.e. Lane==0 is the first bit set
10601     // in OldDmask, so it can be any of X,Y,Z,W; Lane==1 is the second bit
10602     // set, etc.
10603     Lane = SubIdx2Lane(I->getConstantOperandVal(1));
10604 
10605     // Check if the use is for the TFE/LWE generated result at VGPRn+1.
10606     if (UsesTFC && Lane == TFCLane) {
10607       Users[Lane] = *I;
10608     } else {
10609       // Set which texture component corresponds to the lane.
10610       unsigned Comp;
10611       for (unsigned i = 0, Dmask = OldDmask; (i <= Lane) && (Dmask != 0); i++) {
10612         Comp = countTrailingZeros(Dmask);
10613         Dmask &= ~(1 << Comp);
10614       }
10615 
10616       // Abort if we have more than one user per component.
10617       if (Users[Lane])
10618         return Node;
10619 
10620       Users[Lane] = *I;
10621       NewDmask |= 1 << Comp;
10622     }
10623   }
10624 
10625   // Don't allow 0 dmask, as hardware assumes one channel enabled.
10626   bool NoChannels = !NewDmask;
10627   if (NoChannels) {
10628     if (!UsesTFC) {
10629       // No uses of the result and not using TFC. Then do nothing.
10630       return Node;
10631     }
10632     // If the original dmask has one channel - then nothing to do
10633     if (OldBitsSet == 1)
10634       return Node;
10635     // Use an arbitrary dmask - required for the instruction to work
10636     NewDmask = 1;
10637   }
10638   // Abort if there's no change
10639   if (NewDmask == OldDmask)
10640     return Node;
10641 
10642   unsigned BitsSet = countPopulation(NewDmask);
10643 
10644   // Check for TFE or LWE - increase the number of channels by one to account
10645   // for the extra return value
10646   // This will need adjustment for D16 if this is also included in
10647   // adjustWriteMask (this function) but at present D16 are excluded.
10648   unsigned NewChannels = BitsSet + UsesTFC;
10649 
10650   int NewOpcode =
10651       AMDGPU::getMaskedMIMGOp(Node->getMachineOpcode(), NewChannels);
10652   assert(NewOpcode != -1 &&
10653          NewOpcode != static_cast<int>(Node->getMachineOpcode()) &&
10654          "failed to find equivalent MIMG op");
10655 
10656   // Adjust the writemask in the node
10657   SmallVector<SDValue, 12> Ops;
10658   Ops.insert(Ops.end(), Node->op_begin(), Node->op_begin() + DmaskIdx);
10659   Ops.push_back(DAG.getTargetConstant(NewDmask, SDLoc(Node), MVT::i32));
10660   Ops.insert(Ops.end(), Node->op_begin() + DmaskIdx + 1, Node->op_end());
10661 
10662   MVT SVT = Node->getValueType(0).getVectorElementType().getSimpleVT();
10663 
10664   MVT ResultVT = NewChannels == 1 ?
10665     SVT : MVT::getVectorVT(SVT, NewChannels == 3 ? 4 :
10666                            NewChannels == 5 ? 8 : NewChannels);
10667   SDVTList NewVTList = HasChain ?
10668     DAG.getVTList(ResultVT, MVT::Other) : DAG.getVTList(ResultVT);
10669 
10670 
10671   MachineSDNode *NewNode = DAG.getMachineNode(NewOpcode, SDLoc(Node),
10672                                               NewVTList, Ops);
10673 
10674   if (HasChain) {
10675     // Update chain.
10676     DAG.setNodeMemRefs(NewNode, Node->memoperands());
10677     DAG.ReplaceAllUsesOfValueWith(SDValue(Node, 1), SDValue(NewNode, 1));
10678   }
10679 
10680   if (NewChannels == 1) {
10681     assert(Node->hasNUsesOfValue(1, 0));
10682     SDNode *Copy = DAG.getMachineNode(TargetOpcode::COPY,
10683                                       SDLoc(Node), Users[Lane]->getValueType(0),
10684                                       SDValue(NewNode, 0));
10685     DAG.ReplaceAllUsesWith(Users[Lane], Copy);
10686     return nullptr;
10687   }
10688 
10689   // Update the users of the node with the new indices
10690   for (unsigned i = 0, Idx = AMDGPU::sub0; i < 5; ++i) {
10691     SDNode *User = Users[i];
10692     if (!User) {
10693       // Handle the special case of NoChannels. We set NewDmask to 1 above, but
10694       // Users[0] is still nullptr because channel 0 doesn't really have a use.
10695       if (i || !NoChannels)
10696         continue;
10697     } else {
10698       SDValue Op = DAG.getTargetConstant(Idx, SDLoc(User), MVT::i32);
10699       DAG.UpdateNodeOperands(User, SDValue(NewNode, 0), Op);
10700     }
10701 
10702     switch (Idx) {
10703     default: break;
10704     case AMDGPU::sub0: Idx = AMDGPU::sub1; break;
10705     case AMDGPU::sub1: Idx = AMDGPU::sub2; break;
10706     case AMDGPU::sub2: Idx = AMDGPU::sub3; break;
10707     case AMDGPU::sub3: Idx = AMDGPU::sub4; break;
10708     }
10709   }
10710 
10711   DAG.RemoveDeadNode(Node);
10712   return nullptr;
10713 }
10714 
10715 static bool isFrameIndexOp(SDValue Op) {
10716   if (Op.getOpcode() == ISD::AssertZext)
10717     Op = Op.getOperand(0);
10718 
10719   return isa<FrameIndexSDNode>(Op);
10720 }
10721 
10722 /// Legalize target independent instructions (e.g. INSERT_SUBREG)
10723 /// with frame index operands.
10724 /// LLVM assumes that inputs are to these instructions are registers.
10725 SDNode *SITargetLowering::legalizeTargetIndependentNode(SDNode *Node,
10726                                                         SelectionDAG &DAG) const {
10727   if (Node->getOpcode() == ISD::CopyToReg) {
10728     RegisterSDNode *DestReg = cast<RegisterSDNode>(Node->getOperand(1));
10729     SDValue SrcVal = Node->getOperand(2);
10730 
10731     // Insert a copy to a VReg_1 virtual register so LowerI1Copies doesn't have
10732     // to try understanding copies to physical registers.
10733     if (SrcVal.getValueType() == MVT::i1 &&
10734         Register::isPhysicalRegister(DestReg->getReg())) {
10735       SDLoc SL(Node);
10736       MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10737       SDValue VReg = DAG.getRegister(
10738         MRI.createVirtualRegister(&AMDGPU::VReg_1RegClass), MVT::i1);
10739 
10740       SDNode *Glued = Node->getGluedNode();
10741       SDValue ToVReg
10742         = DAG.getCopyToReg(Node->getOperand(0), SL, VReg, SrcVal,
10743                          SDValue(Glued, Glued ? Glued->getNumValues() - 1 : 0));
10744       SDValue ToResultReg
10745         = DAG.getCopyToReg(ToVReg, SL, SDValue(DestReg, 0),
10746                            VReg, ToVReg.getValue(1));
10747       DAG.ReplaceAllUsesWith(Node, ToResultReg.getNode());
10748       DAG.RemoveDeadNode(Node);
10749       return ToResultReg.getNode();
10750     }
10751   }
10752 
10753   SmallVector<SDValue, 8> Ops;
10754   for (unsigned i = 0; i < Node->getNumOperands(); ++i) {
10755     if (!isFrameIndexOp(Node->getOperand(i))) {
10756       Ops.push_back(Node->getOperand(i));
10757       continue;
10758     }
10759 
10760     SDLoc DL(Node);
10761     Ops.push_back(SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL,
10762                                      Node->getOperand(i).getValueType(),
10763                                      Node->getOperand(i)), 0));
10764   }
10765 
10766   return DAG.UpdateNodeOperands(Node, Ops);
10767 }
10768 
10769 /// Fold the instructions after selecting them.
10770 /// Returns null if users were already updated.
10771 SDNode *SITargetLowering::PostISelFolding(MachineSDNode *Node,
10772                                           SelectionDAG &DAG) const {
10773   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10774   unsigned Opcode = Node->getMachineOpcode();
10775 
10776   if (TII->isMIMG(Opcode) && !TII->get(Opcode).mayStore() &&
10777       !TII->isGather4(Opcode)) {
10778     return adjustWritemask(Node, DAG);
10779   }
10780 
10781   if (Opcode == AMDGPU::INSERT_SUBREG ||
10782       Opcode == AMDGPU::REG_SEQUENCE) {
10783     legalizeTargetIndependentNode(Node, DAG);
10784     return Node;
10785   }
10786 
10787   switch (Opcode) {
10788   case AMDGPU::V_DIV_SCALE_F32:
10789   case AMDGPU::V_DIV_SCALE_F64: {
10790     // Satisfy the operand register constraint when one of the inputs is
10791     // undefined. Ordinarily each undef value will have its own implicit_def of
10792     // a vreg, so force these to use a single register.
10793     SDValue Src0 = Node->getOperand(0);
10794     SDValue Src1 = Node->getOperand(1);
10795     SDValue Src2 = Node->getOperand(2);
10796 
10797     if ((Src0.isMachineOpcode() &&
10798          Src0.getMachineOpcode() != AMDGPU::IMPLICIT_DEF) &&
10799         (Src0 == Src1 || Src0 == Src2))
10800       break;
10801 
10802     MVT VT = Src0.getValueType().getSimpleVT();
10803     const TargetRegisterClass *RC =
10804         getRegClassFor(VT, Src0.getNode()->isDivergent());
10805 
10806     MachineRegisterInfo &MRI = DAG.getMachineFunction().getRegInfo();
10807     SDValue UndefReg = DAG.getRegister(MRI.createVirtualRegister(RC), VT);
10808 
10809     SDValue ImpDef = DAG.getCopyToReg(DAG.getEntryNode(), SDLoc(Node),
10810                                       UndefReg, Src0, SDValue());
10811 
10812     // src0 must be the same register as src1 or src2, even if the value is
10813     // undefined, so make sure we don't violate this constraint.
10814     if (Src0.isMachineOpcode() &&
10815         Src0.getMachineOpcode() == AMDGPU::IMPLICIT_DEF) {
10816       if (Src1.isMachineOpcode() &&
10817           Src1.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10818         Src0 = Src1;
10819       else if (Src2.isMachineOpcode() &&
10820                Src2.getMachineOpcode() != AMDGPU::IMPLICIT_DEF)
10821         Src0 = Src2;
10822       else {
10823         assert(Src1.getMachineOpcode() == AMDGPU::IMPLICIT_DEF);
10824         Src0 = UndefReg;
10825         Src1 = UndefReg;
10826       }
10827     } else
10828       break;
10829 
10830     SmallVector<SDValue, 4> Ops = { Src0, Src1, Src2 };
10831     for (unsigned I = 3, N = Node->getNumOperands(); I != N; ++I)
10832       Ops.push_back(Node->getOperand(I));
10833 
10834     Ops.push_back(ImpDef.getValue(1));
10835     return DAG.getMachineNode(Opcode, SDLoc(Node), Node->getVTList(), Ops);
10836   }
10837   default:
10838     break;
10839   }
10840 
10841   return Node;
10842 }
10843 
10844 /// Assign the register class depending on the number of
10845 /// bits set in the writemask
10846 void SITargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
10847                                                      SDNode *Node) const {
10848   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10849 
10850   MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo();
10851 
10852   if (TII->isVOP3(MI.getOpcode())) {
10853     // Make sure constant bus requirements are respected.
10854     TII->legalizeOperandsVOP3(MRI, MI);
10855 
10856     // Prefer VGPRs over AGPRs in mAI instructions where possible.
10857     // This saves a chain-copy of registers and better ballance register
10858     // use between vgpr and agpr as agpr tuples tend to be big.
10859     if (const MCOperandInfo *OpInfo = MI.getDesc().OpInfo) {
10860       unsigned Opc = MI.getOpcode();
10861       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
10862       for (auto I : { AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src0),
10863                       AMDGPU::getNamedOperandIdx(Opc, AMDGPU::OpName::src1) }) {
10864         if (I == -1)
10865           break;
10866         MachineOperand &Op = MI.getOperand(I);
10867         if ((OpInfo[I].RegClass != llvm::AMDGPU::AV_64RegClassID &&
10868              OpInfo[I].RegClass != llvm::AMDGPU::AV_32RegClassID) ||
10869             !Register::isVirtualRegister(Op.getReg()) ||
10870             !TRI->isAGPR(MRI, Op.getReg()))
10871           continue;
10872         auto *Src = MRI.getUniqueVRegDef(Op.getReg());
10873         if (!Src || !Src->isCopy() ||
10874             !TRI->isSGPRReg(MRI, Src->getOperand(1).getReg()))
10875           continue;
10876         auto *RC = TRI->getRegClassForReg(MRI, Op.getReg());
10877         auto *NewRC = TRI->getEquivalentVGPRClass(RC);
10878         // All uses of agpr64 and agpr32 can also accept vgpr except for
10879         // v_accvgpr_read, but we do not produce agpr reads during selection,
10880         // so no use checks are needed.
10881         MRI.setRegClass(Op.getReg(), NewRC);
10882       }
10883     }
10884 
10885     return;
10886   }
10887 
10888   // Replace unused atomics with the no return version.
10889   int NoRetAtomicOp = AMDGPU::getAtomicNoRetOp(MI.getOpcode());
10890   if (NoRetAtomicOp != -1) {
10891     if (!Node->hasAnyUseOfValue(0)) {
10892       MI.setDesc(TII->get(NoRetAtomicOp));
10893       MI.RemoveOperand(0);
10894       return;
10895     }
10896 
10897     // For mubuf_atomic_cmpswap, we need to have tablegen use an extract_subreg
10898     // instruction, because the return type of these instructions is a vec2 of
10899     // the memory type, so it can be tied to the input operand.
10900     // This means these instructions always have a use, so we need to add a
10901     // special case to check if the atomic has only one extract_subreg use,
10902     // which itself has no uses.
10903     if ((Node->hasNUsesOfValue(1, 0) &&
10904          Node->use_begin()->isMachineOpcode() &&
10905          Node->use_begin()->getMachineOpcode() == AMDGPU::EXTRACT_SUBREG &&
10906          !Node->use_begin()->hasAnyUseOfValue(0))) {
10907       Register Def = MI.getOperand(0).getReg();
10908 
10909       // Change this into a noret atomic.
10910       MI.setDesc(TII->get(NoRetAtomicOp));
10911       MI.RemoveOperand(0);
10912 
10913       // If we only remove the def operand from the atomic instruction, the
10914       // extract_subreg will be left with a use of a vreg without a def.
10915       // So we need to insert an implicit_def to avoid machine verifier
10916       // errors.
10917       BuildMI(*MI.getParent(), MI, MI.getDebugLoc(),
10918               TII->get(AMDGPU::IMPLICIT_DEF), Def);
10919     }
10920     return;
10921   }
10922 }
10923 
10924 static SDValue buildSMovImm32(SelectionDAG &DAG, const SDLoc &DL,
10925                               uint64_t Val) {
10926   SDValue K = DAG.getTargetConstant(Val, DL, MVT::i32);
10927   return SDValue(DAG.getMachineNode(AMDGPU::S_MOV_B32, DL, MVT::i32, K), 0);
10928 }
10929 
10930 MachineSDNode *SITargetLowering::wrapAddr64Rsrc(SelectionDAG &DAG,
10931                                                 const SDLoc &DL,
10932                                                 SDValue Ptr) const {
10933   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
10934 
10935   // Build the half of the subregister with the constants before building the
10936   // full 128-bit register. If we are building multiple resource descriptors,
10937   // this will allow CSEing of the 2-component register.
10938   const SDValue Ops0[] = {
10939     DAG.getTargetConstant(AMDGPU::SGPR_64RegClassID, DL, MVT::i32),
10940     buildSMovImm32(DAG, DL, 0),
10941     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10942     buildSMovImm32(DAG, DL, TII->getDefaultRsrcDataFormat() >> 32),
10943     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32)
10944   };
10945 
10946   SDValue SubRegHi = SDValue(DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL,
10947                                                 MVT::v2i32, Ops0), 0);
10948 
10949   // Combine the constants and the pointer.
10950   const SDValue Ops1[] = {
10951     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10952     Ptr,
10953     DAG.getTargetConstant(AMDGPU::sub0_sub1, DL, MVT::i32),
10954     SubRegHi,
10955     DAG.getTargetConstant(AMDGPU::sub2_sub3, DL, MVT::i32)
10956   };
10957 
10958   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops1);
10959 }
10960 
10961 /// Return a resource descriptor with the 'Add TID' bit enabled
10962 ///        The TID (Thread ID) is multiplied by the stride value (bits [61:48]
10963 ///        of the resource descriptor) to create an offset, which is added to
10964 ///        the resource pointer.
10965 MachineSDNode *SITargetLowering::buildRSRC(SelectionDAG &DAG, const SDLoc &DL,
10966                                            SDValue Ptr, uint32_t RsrcDword1,
10967                                            uint64_t RsrcDword2And3) const {
10968   SDValue PtrLo = DAG.getTargetExtractSubreg(AMDGPU::sub0, DL, MVT::i32, Ptr);
10969   SDValue PtrHi = DAG.getTargetExtractSubreg(AMDGPU::sub1, DL, MVT::i32, Ptr);
10970   if (RsrcDword1) {
10971     PtrHi = SDValue(DAG.getMachineNode(AMDGPU::S_OR_B32, DL, MVT::i32, PtrHi,
10972                                      DAG.getConstant(RsrcDword1, DL, MVT::i32)),
10973                     0);
10974   }
10975 
10976   SDValue DataLo = buildSMovImm32(DAG, DL,
10977                                   RsrcDword2And3 & UINT64_C(0xFFFFFFFF));
10978   SDValue DataHi = buildSMovImm32(DAG, DL, RsrcDword2And3 >> 32);
10979 
10980   const SDValue Ops[] = {
10981     DAG.getTargetConstant(AMDGPU::SGPR_128RegClassID, DL, MVT::i32),
10982     PtrLo,
10983     DAG.getTargetConstant(AMDGPU::sub0, DL, MVT::i32),
10984     PtrHi,
10985     DAG.getTargetConstant(AMDGPU::sub1, DL, MVT::i32),
10986     DataLo,
10987     DAG.getTargetConstant(AMDGPU::sub2, DL, MVT::i32),
10988     DataHi,
10989     DAG.getTargetConstant(AMDGPU::sub3, DL, MVT::i32)
10990   };
10991 
10992   return DAG.getMachineNode(AMDGPU::REG_SEQUENCE, DL, MVT::v4i32, Ops);
10993 }
10994 
10995 //===----------------------------------------------------------------------===//
10996 //                         SI Inline Assembly Support
10997 //===----------------------------------------------------------------------===//
10998 
10999 std::pair<unsigned, const TargetRegisterClass *>
11000 SITargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
11001                                                StringRef Constraint,
11002                                                MVT VT) const {
11003   const TargetRegisterClass *RC = nullptr;
11004   if (Constraint.size() == 1) {
11005     const unsigned BitWidth = VT.getSizeInBits();
11006     switch (Constraint[0]) {
11007     default:
11008       return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11009     case 's':
11010     case 'r':
11011       switch (BitWidth) {
11012       case 16:
11013         RC = &AMDGPU::SReg_32RegClass;
11014         break;
11015       case 64:
11016         RC = &AMDGPU::SGPR_64RegClass;
11017         break;
11018       default:
11019         RC = SIRegisterInfo::getSGPRClassForBitWidth(BitWidth);
11020         if (!RC)
11021           return std::make_pair(0U, nullptr);
11022         break;
11023       }
11024       break;
11025     case 'v':
11026       switch (BitWidth) {
11027       case 16:
11028         RC = &AMDGPU::VGPR_32RegClass;
11029         break;
11030       default:
11031         RC = SIRegisterInfo::getVGPRClassForBitWidth(BitWidth);
11032         if (!RC)
11033           return std::make_pair(0U, nullptr);
11034         break;
11035       }
11036       break;
11037     case 'a':
11038       if (!Subtarget->hasMAIInsts())
11039         break;
11040       switch (BitWidth) {
11041       case 16:
11042         RC = &AMDGPU::AGPR_32RegClass;
11043         break;
11044       default:
11045         RC = SIRegisterInfo::getAGPRClassForBitWidth(BitWidth);
11046         if (!RC)
11047           return std::make_pair(0U, nullptr);
11048         break;
11049       }
11050       break;
11051     }
11052     // We actually support i128, i16 and f16 as inline parameters
11053     // even if they are not reported as legal
11054     if (RC && (isTypeLegal(VT) || VT.SimpleTy == MVT::i128 ||
11055                VT.SimpleTy == MVT::i16 || VT.SimpleTy == MVT::f16))
11056       return std::make_pair(0U, RC);
11057   }
11058 
11059   if (Constraint.size() > 1) {
11060     if (Constraint[1] == 'v') {
11061       RC = &AMDGPU::VGPR_32RegClass;
11062     } else if (Constraint[1] == 's') {
11063       RC = &AMDGPU::SGPR_32RegClass;
11064     } else if (Constraint[1] == 'a') {
11065       RC = &AMDGPU::AGPR_32RegClass;
11066     }
11067 
11068     if (RC) {
11069       uint32_t Idx;
11070       bool Failed = Constraint.substr(2).getAsInteger(10, Idx);
11071       if (!Failed && Idx < RC->getNumRegs())
11072         return std::make_pair(RC->getRegister(Idx), RC);
11073     }
11074   }
11075 
11076   // FIXME: Returns VS_32 for physical SGPR constraints
11077   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
11078 }
11079 
11080 SITargetLowering::ConstraintType
11081 SITargetLowering::getConstraintType(StringRef Constraint) const {
11082   if (Constraint.size() == 1) {
11083     switch (Constraint[0]) {
11084     default: break;
11085     case 's':
11086     case 'v':
11087     case 'a':
11088       return C_RegisterClass;
11089     case 'A':
11090       return C_Other;
11091     }
11092   }
11093   return TargetLowering::getConstraintType(Constraint);
11094 }
11095 
11096 void SITargetLowering::LowerAsmOperandForConstraint(SDValue Op,
11097                                                     std::string &Constraint,
11098                                                     std::vector<SDValue> &Ops,
11099                                                     SelectionDAG &DAG) const {
11100   if (Constraint.length() == 1 && Constraint[0] == 'A') {
11101     LowerAsmOperandForConstraintA(Op, Ops, DAG);
11102   } else {
11103     TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
11104   }
11105 }
11106 
11107 void SITargetLowering::LowerAsmOperandForConstraintA(SDValue Op,
11108                                                      std::vector<SDValue> &Ops,
11109                                                      SelectionDAG &DAG) const {
11110   unsigned Size = Op.getScalarValueSizeInBits();
11111   if (Size > 64)
11112     return;
11113 
11114   uint64_t Val;
11115   bool IsConst = false;
11116   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
11117     Val = C->getSExtValue();
11118     IsConst = true;
11119   } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
11120     Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11121     IsConst = true;
11122   } else if (BuildVectorSDNode *V = dyn_cast<BuildVectorSDNode>(Op)) {
11123     if (Size != 16 || Op.getNumOperands() != 2)
11124       return;
11125     if (Op.getOperand(0).isUndef() || Op.getOperand(1).isUndef())
11126       return;
11127     if (ConstantSDNode *C = V->getConstantSplatNode()) {
11128       Val = C->getSExtValue();
11129       IsConst = true;
11130     } else if (ConstantFPSDNode *C = V->getConstantFPSplatNode()) {
11131       Val = C->getValueAPF().bitcastToAPInt().getSExtValue();
11132       IsConst = true;
11133     }
11134   }
11135 
11136   if (IsConst) {
11137     bool HasInv2Pi = Subtarget->hasInv2PiInlineImm();
11138     if ((Size == 16 && AMDGPU::isInlinableLiteral16(Val, HasInv2Pi)) ||
11139         (Size == 32 && AMDGPU::isInlinableLiteral32(Val, HasInv2Pi)) ||
11140         (Size == 64 && AMDGPU::isInlinableLiteral64(Val, HasInv2Pi))) {
11141       // Clear unused bits of fp constants
11142       if (!AMDGPU::isInlinableIntLiteral(Val)) {
11143         unsigned UnusedBits = 64 - Size;
11144         Val = (Val << UnusedBits) >> UnusedBits;
11145       }
11146       auto Res = DAG.getTargetConstant(Val, SDLoc(Op), MVT::i64);
11147       Ops.push_back(Res);
11148     }
11149   }
11150 }
11151 
11152 // Figure out which registers should be reserved for stack access. Only after
11153 // the function is legalized do we know all of the non-spill stack objects or if
11154 // calls are present.
11155 void SITargetLowering::finalizeLowering(MachineFunction &MF) const {
11156   MachineRegisterInfo &MRI = MF.getRegInfo();
11157   SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11158   const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>();
11159   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11160 
11161   if (Info->isEntryFunction()) {
11162     // Callable functions have fixed registers used for stack access.
11163     reservePrivateMemoryRegs(getTargetMachine(), MF, *TRI, *Info);
11164   }
11165 
11166   assert(!TRI->isSubRegister(Info->getScratchRSrcReg(),
11167                              Info->getStackPtrOffsetReg()));
11168   if (Info->getStackPtrOffsetReg() != AMDGPU::SP_REG)
11169     MRI.replaceRegWith(AMDGPU::SP_REG, Info->getStackPtrOffsetReg());
11170 
11171   // We need to worry about replacing the default register with itself in case
11172   // of MIR testcases missing the MFI.
11173   if (Info->getScratchRSrcReg() != AMDGPU::PRIVATE_RSRC_REG)
11174     MRI.replaceRegWith(AMDGPU::PRIVATE_RSRC_REG, Info->getScratchRSrcReg());
11175 
11176   if (Info->getFrameOffsetReg() != AMDGPU::FP_REG)
11177     MRI.replaceRegWith(AMDGPU::FP_REG, Info->getFrameOffsetReg());
11178 
11179   Info->limitOccupancy(MF);
11180 
11181   if (ST.isWave32() && !MF.empty()) {
11182     // Add VCC_HI def because many instructions marked as imp-use VCC where
11183     // we may only define VCC_LO. If nothing defines VCC_HI we may end up
11184     // having a use of undef.
11185 
11186     const SIInstrInfo *TII = ST.getInstrInfo();
11187     DebugLoc DL;
11188 
11189     MachineBasicBlock &MBB = MF.front();
11190     MachineBasicBlock::iterator I = MBB.getFirstNonDebugInstr();
11191     BuildMI(MBB, I, DL, TII->get(TargetOpcode::IMPLICIT_DEF), AMDGPU::VCC_HI);
11192 
11193     for (auto &MBB : MF) {
11194       for (auto &MI : MBB) {
11195         TII->fixImplicitOperands(MI);
11196       }
11197     }
11198   }
11199 
11200   TargetLoweringBase::finalizeLowering(MF);
11201 
11202   // Allocate a VGPR for future SGPR Spill if
11203   // "amdgpu-reserve-vgpr-for-sgpr-spill" option is used
11204   // FIXME: We won't need this hack if we split SGPR allocation from VGPR
11205   if (VGPRReserveforSGPRSpill && !Info->VGPRReservedForSGPRSpill &&
11206       !Info->isEntryFunction() && MF.getFrameInfo().hasStackObjects())
11207     Info->reserveVGPRforSGPRSpills(MF);
11208 }
11209 
11210 void SITargetLowering::computeKnownBitsForFrameIndex(
11211   const int FI, KnownBits &Known, const MachineFunction &MF) const {
11212   TargetLowering::computeKnownBitsForFrameIndex(FI, Known, MF);
11213 
11214   // Set the high bits to zero based on the maximum allowed scratch size per
11215   // wave. We can't use vaddr in MUBUF instructions if we don't know the address
11216   // calculation won't overflow, so assume the sign bit is never set.
11217   Known.Zero.setHighBits(getSubtarget()->getKnownHighZeroBitsForFrameIndex());
11218 }
11219 
11220 Align SITargetLowering::getPrefLoopAlignment(MachineLoop *ML) const {
11221   const Align PrefAlign = TargetLowering::getPrefLoopAlignment(ML);
11222   const Align CacheLineAlign = Align(64);
11223 
11224   // Pre-GFX10 target did not benefit from loop alignment
11225   if (!ML || DisableLoopAlignment ||
11226       (getSubtarget()->getGeneration() < AMDGPUSubtarget::GFX10) ||
11227       getSubtarget()->hasInstFwdPrefetchBug())
11228     return PrefAlign;
11229 
11230   // On GFX10 I$ is 4 x 64 bytes cache lines.
11231   // By default prefetcher keeps one cache line behind and reads two ahead.
11232   // We can modify it with S_INST_PREFETCH for larger loops to have two lines
11233   // behind and one ahead.
11234   // Therefor we can benefit from aligning loop headers if loop fits 192 bytes.
11235   // If loop fits 64 bytes it always spans no more than two cache lines and
11236   // does not need an alignment.
11237   // Else if loop is less or equal 128 bytes we do not need to modify prefetch,
11238   // Else if loop is less or equal 192 bytes we need two lines behind.
11239 
11240   const SIInstrInfo *TII = getSubtarget()->getInstrInfo();
11241   const MachineBasicBlock *Header = ML->getHeader();
11242   if (Header->getAlignment() != PrefAlign)
11243     return Header->getAlignment(); // Already processed.
11244 
11245   unsigned LoopSize = 0;
11246   for (const MachineBasicBlock *MBB : ML->blocks()) {
11247     // If inner loop block is aligned assume in average half of the alignment
11248     // size to be added as nops.
11249     if (MBB != Header)
11250       LoopSize += MBB->getAlignment().value() / 2;
11251 
11252     for (const MachineInstr &MI : *MBB) {
11253       LoopSize += TII->getInstSizeInBytes(MI);
11254       if (LoopSize > 192)
11255         return PrefAlign;
11256     }
11257   }
11258 
11259   if (LoopSize <= 64)
11260     return PrefAlign;
11261 
11262   if (LoopSize <= 128)
11263     return CacheLineAlign;
11264 
11265   // If any of parent loops is surrounded by prefetch instructions do not
11266   // insert new for inner loop, which would reset parent's settings.
11267   for (MachineLoop *P = ML->getParentLoop(); P; P = P->getParentLoop()) {
11268     if (MachineBasicBlock *Exit = P->getExitBlock()) {
11269       auto I = Exit->getFirstNonDebugInstr();
11270       if (I != Exit->end() && I->getOpcode() == AMDGPU::S_INST_PREFETCH)
11271         return CacheLineAlign;
11272     }
11273   }
11274 
11275   MachineBasicBlock *Pre = ML->getLoopPreheader();
11276   MachineBasicBlock *Exit = ML->getExitBlock();
11277 
11278   if (Pre && Exit) {
11279     BuildMI(*Pre, Pre->getFirstTerminator(), DebugLoc(),
11280             TII->get(AMDGPU::S_INST_PREFETCH))
11281       .addImm(1); // prefetch 2 lines behind PC
11282 
11283     BuildMI(*Exit, Exit->getFirstNonDebugInstr(), DebugLoc(),
11284             TII->get(AMDGPU::S_INST_PREFETCH))
11285       .addImm(2); // prefetch 1 line behind PC
11286   }
11287 
11288   return CacheLineAlign;
11289 }
11290 
11291 LLVM_ATTRIBUTE_UNUSED
11292 static bool isCopyFromRegOfInlineAsm(const SDNode *N) {
11293   assert(N->getOpcode() == ISD::CopyFromReg);
11294   do {
11295     // Follow the chain until we find an INLINEASM node.
11296     N = N->getOperand(0).getNode();
11297     if (N->getOpcode() == ISD::INLINEASM ||
11298         N->getOpcode() == ISD::INLINEASM_BR)
11299       return true;
11300   } while (N->getOpcode() == ISD::CopyFromReg);
11301   return false;
11302 }
11303 
11304 bool SITargetLowering::isSDNodeSourceOfDivergence(const SDNode * N,
11305   FunctionLoweringInfo * FLI, LegacyDivergenceAnalysis * KDA) const
11306 {
11307   switch (N->getOpcode()) {
11308     case ISD::CopyFromReg:
11309     {
11310       const RegisterSDNode *R = cast<RegisterSDNode>(N->getOperand(1));
11311       const MachineRegisterInfo &MRI = FLI->MF->getRegInfo();
11312       const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11313       Register Reg = R->getReg();
11314 
11315       // FIXME: Why does this need to consider isLiveIn?
11316       if (Reg.isPhysical() || MRI.isLiveIn(Reg))
11317         return !TRI->isSGPRReg(MRI, Reg);
11318 
11319       if (const Value *V = FLI->getValueFromVirtualReg(R->getReg()))
11320         return KDA->isDivergent(V);
11321 
11322       assert(Reg == FLI->DemoteRegister || isCopyFromRegOfInlineAsm(N));
11323       return !TRI->isSGPRReg(MRI, Reg);
11324     }
11325     break;
11326     case ISD::LOAD: {
11327       const LoadSDNode *L = cast<LoadSDNode>(N);
11328       unsigned AS = L->getAddressSpace();
11329       // A flat load may access private memory.
11330       return AS == AMDGPUAS::PRIVATE_ADDRESS || AS == AMDGPUAS::FLAT_ADDRESS;
11331     } break;
11332     case ISD::CALLSEQ_END:
11333     return true;
11334     break;
11335     case ISD::INTRINSIC_WO_CHAIN:
11336     {
11337 
11338     }
11339       return AMDGPU::isIntrinsicSourceOfDivergence(
11340       cast<ConstantSDNode>(N->getOperand(0))->getZExtValue());
11341     case ISD::INTRINSIC_W_CHAIN:
11342       return AMDGPU::isIntrinsicSourceOfDivergence(
11343       cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
11344   }
11345   return false;
11346 }
11347 
11348 bool SITargetLowering::denormalsEnabledForType(const SelectionDAG &DAG,
11349                                                EVT VT) const {
11350   switch (VT.getScalarType().getSimpleVT().SimpleTy) {
11351   case MVT::f32:
11352     return hasFP32Denormals(DAG.getMachineFunction());
11353   case MVT::f64:
11354   case MVT::f16:
11355     return hasFP64FP16Denormals(DAG.getMachineFunction());
11356   default:
11357     return false;
11358   }
11359 }
11360 
11361 bool SITargetLowering::isKnownNeverNaNForTargetNode(SDValue Op,
11362                                                     const SelectionDAG &DAG,
11363                                                     bool SNaN,
11364                                                     unsigned Depth) const {
11365   if (Op.getOpcode() == AMDGPUISD::CLAMP) {
11366     const MachineFunction &MF = DAG.getMachineFunction();
11367     const SIMachineFunctionInfo *Info = MF.getInfo<SIMachineFunctionInfo>();
11368 
11369     if (Info->getMode().DX10Clamp)
11370       return true; // Clamped to 0.
11371     return DAG.isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
11372   }
11373 
11374   return AMDGPUTargetLowering::isKnownNeverNaNForTargetNode(Op, DAG,
11375                                                             SNaN, Depth);
11376 }
11377 
11378 TargetLowering::AtomicExpansionKind
11379 SITargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *RMW) const {
11380   switch (RMW->getOperation()) {
11381   case AtomicRMWInst::FAdd: {
11382     Type *Ty = RMW->getType();
11383 
11384     // We don't have a way to support 16-bit atomics now, so just leave them
11385     // as-is.
11386     if (Ty->isHalfTy())
11387       return AtomicExpansionKind::None;
11388 
11389     if (!Ty->isFloatTy())
11390       return AtomicExpansionKind::CmpXChg;
11391 
11392     // TODO: Do have these for flat. Older targets also had them for buffers.
11393     unsigned AS = RMW->getPointerAddressSpace();
11394 
11395     if (AS == AMDGPUAS::GLOBAL_ADDRESS && Subtarget->hasAtomicFaddInsts()) {
11396       return RMW->use_empty() ? AtomicExpansionKind::None :
11397                                 AtomicExpansionKind::CmpXChg;
11398     }
11399 
11400     return (AS == AMDGPUAS::LOCAL_ADDRESS && Subtarget->hasLDSFPAtomics()) ?
11401       AtomicExpansionKind::None : AtomicExpansionKind::CmpXChg;
11402   }
11403   default:
11404     break;
11405   }
11406 
11407   return AMDGPUTargetLowering::shouldExpandAtomicRMWInIR(RMW);
11408 }
11409 
11410 const TargetRegisterClass *
11411 SITargetLowering::getRegClassFor(MVT VT, bool isDivergent) const {
11412   const TargetRegisterClass *RC = TargetLoweringBase::getRegClassFor(VT, false);
11413   const SIRegisterInfo *TRI = Subtarget->getRegisterInfo();
11414   if (RC == &AMDGPU::VReg_1RegClass && !isDivergent)
11415     return Subtarget->getWavefrontSize() == 64 ? &AMDGPU::SReg_64RegClass
11416                                                : &AMDGPU::SReg_32RegClass;
11417   if (!TRI->isSGPRClass(RC) && !isDivergent)
11418     return TRI->getEquivalentSGPRClass(RC);
11419   else if (TRI->isSGPRClass(RC) && isDivergent)
11420     return TRI->getEquivalentVGPRClass(RC);
11421 
11422   return RC;
11423 }
11424 
11425 // FIXME: This is a workaround for DivergenceAnalysis not understanding always
11426 // uniform values (as produced by the mask results of control flow intrinsics)
11427 // used outside of divergent blocks. The phi users need to also be treated as
11428 // always uniform.
11429 static bool hasCFUser(const Value *V, SmallPtrSet<const Value *, 16> &Visited,
11430                       unsigned WaveSize) {
11431   // FIXME: We asssume we never cast the mask results of a control flow
11432   // intrinsic.
11433   // Early exit if the type won't be consistent as a compile time hack.
11434   IntegerType *IT = dyn_cast<IntegerType>(V->getType());
11435   if (!IT || IT->getBitWidth() != WaveSize)
11436     return false;
11437 
11438   if (!isa<Instruction>(V))
11439     return false;
11440   if (!Visited.insert(V).second)
11441     return false;
11442   bool Result = false;
11443   for (auto U : V->users()) {
11444     if (const IntrinsicInst *Intrinsic = dyn_cast<IntrinsicInst>(U)) {
11445       if (V == U->getOperand(1)) {
11446         switch (Intrinsic->getIntrinsicID()) {
11447         default:
11448           Result = false;
11449           break;
11450         case Intrinsic::amdgcn_if_break:
11451         case Intrinsic::amdgcn_if:
11452         case Intrinsic::amdgcn_else:
11453           Result = true;
11454           break;
11455         }
11456       }
11457       if (V == U->getOperand(0)) {
11458         switch (Intrinsic->getIntrinsicID()) {
11459         default:
11460           Result = false;
11461           break;
11462         case Intrinsic::amdgcn_end_cf:
11463         case Intrinsic::amdgcn_loop:
11464           Result = true;
11465           break;
11466         }
11467       }
11468     } else {
11469       Result = hasCFUser(U, Visited, WaveSize);
11470     }
11471     if (Result)
11472       break;
11473   }
11474   return Result;
11475 }
11476 
11477 bool SITargetLowering::requiresUniformRegister(MachineFunction &MF,
11478                                                const Value *V) const {
11479   if (const CallInst *CI = dyn_cast<CallInst>(V)) {
11480     if (CI->isInlineAsm()) {
11481       // FIXME: This cannot give a correct answer. This should only trigger in
11482       // the case where inline asm returns mixed SGPR and VGPR results, used
11483       // outside the defining block. We don't have a specific result to
11484       // consider, so this assumes if any value is SGPR, the overall register
11485       // also needs to be SGPR.
11486       const SIRegisterInfo *SIRI = Subtarget->getRegisterInfo();
11487       TargetLowering::AsmOperandInfoVector TargetConstraints = ParseConstraints(
11488           MF.getDataLayout(), Subtarget->getRegisterInfo(), *CI);
11489       for (auto &TC : TargetConstraints) {
11490         if (TC.Type == InlineAsm::isOutput) {
11491           ComputeConstraintToUse(TC, SDValue());
11492           unsigned AssignedReg;
11493           const TargetRegisterClass *RC;
11494           std::tie(AssignedReg, RC) = getRegForInlineAsmConstraint(
11495               SIRI, TC.ConstraintCode, TC.ConstraintVT);
11496           if (RC) {
11497             MachineRegisterInfo &MRI = MF.getRegInfo();
11498             if (AssignedReg != 0 && SIRI->isSGPRReg(MRI, AssignedReg))
11499               return true;
11500             else if (SIRI->isSGPRClass(RC))
11501               return true;
11502           }
11503         }
11504       }
11505     }
11506   }
11507   SmallPtrSet<const Value *, 16> Visited;
11508   return hasCFUser(V, Visited, Subtarget->getWavefrontSize());
11509 }
11510